blob: 4319df3e92e3be6a5087915c44aa95b64d4db97c [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000030#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000033#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000034#include "clang/Basic/TargetInfo.h"
35#include "clang/Basic/Diagnostic.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000038#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000039#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000042#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000043#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000044#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000045using namespace clang;
46
Douglas Gregorbb420ab2010-08-04 05:53:38 +000047/// \brief After failing to build a precompiled preamble (due to
48/// errors in the source that occurs in the preamble), the number of
49/// reparses during which we'll skip even trying to precompile the
50/// preamble.
51const unsigned DefaultPreambleRebuildInterval = 5;
52
Douglas Gregord03e8232010-04-05 21:10:19 +000053ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000054 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000055 CompleteTranslationUnit(true), NumStoredDiagnosticsFromDriver(0),
56 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000057 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000058 ShouldCacheCodeCompletionResults(false),
59 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000060 CacheCodeCompletionCoolDown(0),
61 UnsafeToFree(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000062}
Douglas Gregord03e8232010-04-05 21:10:19 +000063
Daniel Dunbar764c0822009-12-01 09:51:01 +000064ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000065 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000066 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000067 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000068 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000069
70 // Free the buffers associated with remapped files. We are required to
71 // perform this operation here because we explicitly request that the
72 // compiler instance *not* free these buffers for each invocation of the
73 // parser.
74 if (Invocation.get()) {
75 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
76 for (PreprocessorOptions::remapped_file_buffer_iterator
77 FB = PPOpts.remapped_file_buffer_begin(),
78 FBEnd = PPOpts.remapped_file_buffer_end();
79 FB != FBEnd;
80 ++FB)
81 delete FB->second;
82 }
Douglas Gregor96c04262010-07-27 14:52:07 +000083
84 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +000085 delete PreambleBuffer;
86
Douglas Gregorb14904c2010-08-13 22:48:40 +000087 ClearCachedCompletionResults();
88
Douglas Gregor2c844822010-09-24 21:18:36 +000089 if (TimerGroup)
90 TimerGroup->printAll(llvm::errs());
91
Douglas Gregor15ba0b32010-07-30 20:58:08 +000092 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
93 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094}
95
96void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000097 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
98 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000099 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000100}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000101
Douglas Gregor39982192010-08-15 06:18:01 +0000102/// \brief Determine the set of code-completion contexts in which this
103/// declaration should be shown.
104static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000105 const LangOptions &LangOpts,
106 bool &IsNestedNameSpecifier) {
107 IsNestedNameSpecifier = false;
108
Douglas Gregor39982192010-08-15 06:18:01 +0000109 if (isa<UsingShadowDecl>(ND))
110 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
111 if (!ND)
112 return 0;
113
114 unsigned Contexts = 0;
115 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
116 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
117 // Types can appear in these contexts.
118 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
119 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
120 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
121 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
122 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000123 | (1 << (CodeCompletionContext::CCC_Type - 1))
124 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000125
126 // In C++, types can appear in expressions contexts (for functional casts).
127 if (LangOpts.CPlusPlus)
128 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
129
130 // In Objective-C, message sends can send interfaces. In Objective-C++,
131 // all types are available due to functional casts.
132 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
133 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
134
135 // Deal with tag names.
136 if (isa<EnumDecl>(ND)) {
137 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
138
Douglas Gregor59cab552010-08-16 23:05:20 +0000139 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000140 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000141 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000142 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
143 if (Record->isUnion())
144 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
145 else
146 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
147
Douglas Gregor39982192010-08-15 06:18:01 +0000148 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000149 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000150 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000151 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000152 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
153 // Values can appear in these contexts.
154 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
155 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000156 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000157 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
158 } else if (isa<ObjCProtocolDecl>(ND)) {
159 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
160 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000161 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000162
163 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000164 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000165 }
166
167 return Contexts;
168}
169
Douglas Gregorb14904c2010-08-13 22:48:40 +0000170void ASTUnit::CacheCodeCompletionResults() {
171 if (!TheSema)
172 return;
173
174 llvm::Timer *CachingTimer = 0;
175 if (TimerGroup.get()) {
176 CachingTimer = new llvm::Timer("Cache global code completions",
177 *TimerGroup);
178 CachingTimer->startTimer();
179 Timers.push_back(CachingTimer);
180 }
181
182 // Clear out the previous results.
183 ClearCachedCompletionResults();
184
185 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000186 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000187 llvm::SmallVector<Result, 8> Results;
188 TheSema->GatherGlobalCodeCompletions(Results);
189
190 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000191 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
192
Douglas Gregorb14904c2010-08-13 22:48:40 +0000193 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
194 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000195 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000196 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000197 CachedCodeCompletionResult CachedResult;
198 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
199 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000200 Ctx->getLangOptions(),
201 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000202 CachedResult.Priority = Results[I].Priority;
203 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000204 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000205
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000206 // Keep track of the type of this completion in an ASTContext-agnostic
207 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000208 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000209 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000210 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000211 CachedResult.Type = 0;
212 } else {
213 CanQualType CanUsageType
214 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
215 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
216
217 // Determine whether we have already seen this type. If so, we save
218 // ourselves the work of formatting the type string by using the
219 // temporary, CanQualType-based hash table to find the associated value.
220 unsigned &TypeValue = CompletionTypes[CanUsageType];
221 if (TypeValue == 0) {
222 TypeValue = CompletionTypes.size();
223 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
224 = TypeValue;
225 }
226
227 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000228 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000229
Douglas Gregor39982192010-08-15 06:18:01 +0000230 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000231
232 /// Handle nested-name-specifiers in C++.
233 if (TheSema->Context.getLangOptions().CPlusPlus &&
234 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
235 // The contexts in which a nested-name-specifier can appear in C++.
236 unsigned NNSContexts
237 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
238 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
239 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
240 | (1 << (CodeCompletionContext::CCC_Statement - 1))
241 | (1 << (CodeCompletionContext::CCC_Expression - 1))
242 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
243 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
244 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
245 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000246 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000247 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
248 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000249
250 if (isa<NamespaceDecl>(Results[I].Declaration) ||
251 isa<NamespaceAliasDecl>(Results[I].Declaration))
252 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
253
254 if (unsigned RemainingContexts
255 = NNSContexts & ~CachedResult.ShowInContexts) {
256 // If there any contexts where this completion can be a
257 // nested-name-specifier but isn't already an option, create a
258 // nested-name-specifier completion.
259 Results[I].StartsNestedNameSpecifier = true;
260 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
261 CachedResult.ShowInContexts = RemainingContexts;
262 CachedResult.Priority = CCP_NestedNameSpecifier;
263 CachedResult.TypeClass = STC_Void;
264 CachedResult.Type = 0;
265 CachedCompletionResults.push_back(CachedResult);
266 }
267 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000268 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000269 }
270
Douglas Gregorb14904c2010-08-13 22:48:40 +0000271 case Result::RK_Keyword:
272 case Result::RK_Pattern:
273 // Ignore keywords and patterns; we don't care, since they are so
274 // easily regenerated.
275 break;
276
277 case Result::RK_Macro: {
278 CachedCodeCompletionResult CachedResult;
279 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
280 CachedResult.ShowInContexts
281 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
282 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
283 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
286 | (1 << (CodeCompletionContext::CCC_Statement - 1))
287 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000288 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000289 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000290 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
291 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
292
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000293
Douglas Gregorb14904c2010-08-13 22:48:40 +0000294 CachedResult.Priority = Results[I].Priority;
295 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000296 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000297 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000298 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000299 CachedCompletionResults.push_back(CachedResult);
300 break;
301 }
302 }
303 Results[I].Destroy();
304 }
305
306 if (CachingTimer)
307 CachingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000308
309 // Make a note of the state when we performed this caching.
310 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
311 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000312}
313
314void ASTUnit::ClearCachedCompletionResults() {
315 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
316 delete CachedCompletionResults[I].Completion;
317 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000318 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000319}
320
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000321namespace {
322
Sebastian Redl2c499f62010-08-18 23:56:43 +0000323/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000324/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000325class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000326 LangOptions &LangOpt;
327 HeaderSearch &HSI;
328 std::string &TargetTriple;
329 std::string &Predefines;
330 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000331
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000332 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000333
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000334public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000335 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000336 std::string &TargetTriple, std::string &Predefines,
337 unsigned &Counter)
338 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
339 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000340
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000341 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
342 LangOpt = LangOpts;
343 return false;
344 }
Mike Stump11289f42009-09-09 15:08:12 +0000345
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000346 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000347 TargetTriple = Triple;
348 return false;
349 }
Mike Stump11289f42009-09-09 15:08:12 +0000350
Sebastian Redl8b41f302010-07-14 23:29:55 +0000351 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000352 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000353 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000354 Predefines = Buffers[0].Data;
355 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
356 Predefines += Buffers[I].Data;
357 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000358 return false;
359 }
Mike Stump11289f42009-09-09 15:08:12 +0000360
Douglas Gregora2f49452010-03-16 19:09:18 +0000361 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000362 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
363 }
Mike Stump11289f42009-09-09 15:08:12 +0000364
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000365 virtual void ReadCounter(unsigned Value) {
366 Counter = Value;
367 }
368};
369
Douglas Gregor33cdd812010-02-18 18:08:43 +0000370class StoredDiagnosticClient : public DiagnosticClient {
371 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
372
373public:
374 explicit StoredDiagnosticClient(
375 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
376 : StoredDiags(StoredDiags) { }
377
378 virtual void HandleDiagnostic(Diagnostic::Level Level,
379 const DiagnosticInfo &Info);
380};
381
382/// \brief RAII object that optionally captures diagnostics, if
383/// there is no diagnostic client to capture them already.
384class CaptureDroppedDiagnostics {
385 Diagnostic &Diags;
386 StoredDiagnosticClient Client;
387 DiagnosticClient *PreviousClient;
388
389public:
390 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
391 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000392 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000393 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000394 if (RequestCapture || Diags.getClient() == 0) {
395 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000396 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000397 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000398 }
399
400 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000401 if (Diags.getClient() == &Client) {
402 Diags.takeClient();
403 Diags.setClient(PreviousClient);
404 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000405 }
406};
407
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000408} // anonymous namespace
409
Douglas Gregor33cdd812010-02-18 18:08:43 +0000410void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
411 const DiagnosticInfo &Info) {
412 StoredDiags.push_back(StoredDiagnostic(Level, Info));
413}
414
Steve Naroffc0683b92009-09-03 18:19:54 +0000415const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000416 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000417}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000418
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000419const std::string &ASTUnit::getASTFileName() {
420 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000421 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000422}
423
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000424ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000425 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000426 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000427 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000428 unsigned NumRemappedFiles,
429 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000430 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
431
Douglas Gregor7f95d262010-04-05 23:52:57 +0000432 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000433 // No diagnostics engine was provided, so create our own diagnostics object
434 // with the default options.
435 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000436 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000437 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000438
439 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000440 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000441 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000442 AST->FileMgr.reset(new FileManager);
443 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000444 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000445
Douglas Gregor33cdd812010-02-18 18:08:43 +0000446 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000447 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000448 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000449
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000450 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
451 // Create the file entry for the file that we're mapping from.
452 const FileEntry *FromFile
453 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
454 RemappedFiles[I].second->getBufferSize(),
455 0);
456 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000457 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000458 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000459 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000460 continue;
461 }
462
463 // Override the contents of the "from" file with the contents of
464 // the "to" file.
465 AST->getSourceManager().overrideFileContents(FromFile,
466 RemappedFiles[I].second);
467 }
468
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000469 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000470
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000471 LangOptions LangInfo;
472 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
473 std::string TargetTriple;
474 std::string Predefines;
475 unsigned Counter;
476
Sebastian Redl2c499f62010-08-18 23:56:43 +0000477 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000478
Sebastian Redl2c499f62010-08-18 23:56:43 +0000479 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000480 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000481 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000482 Predefines, Counter));
483
Sebastian Redl009e7f22010-10-05 16:15:19 +0000484 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000485 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000486 break;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Sebastian Redl2c499f62010-08-18 23:56:43 +0000488 case ASTReader::Failure:
489 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000490 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000491 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000492 }
Mike Stump11289f42009-09-09 15:08:12 +0000493
Daniel Dunbara8a50932009-12-02 08:44:16 +0000494 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
495
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000496 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000497
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000498 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000499 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000500 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000501 TargetOptions TargetOpts;
502 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000503 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000504 TargetOpts.CPU = "";
505 TargetOpts.Features.clear();
506 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000507 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
508 TargetOpts));
509 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
510 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000511 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000512 Preprocessor &PP = *AST->PP.get();
513
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000514 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000515 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000516 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000517
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000518 // Create and initialize the ASTContext.
519
520 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000521 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 *AST->Target.get(),
523 PP.getIdentifierTable(),
524 PP.getSelectorTable(),
525 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000526 /* size_reserve = */0));
527 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000528
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000529 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Sebastian Redl2c499f62010-08-18 23:56:43 +0000531 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000532 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000533 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000534 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000535 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000536 Context.setExternalSource(Source);
537
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000538 // Create an AST consumer, even though it isn't used.
539 AST->Consumer.reset(new ASTConsumer);
540
Sebastian Redl2c499f62010-08-18 23:56:43 +0000541 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000542 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
543 AST->TheSema->Initialize();
544 ReaderPtr->InitializeSema(*AST->TheSema);
545
Mike Stump11289f42009-09-09 15:08:12 +0000546 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000547}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000548
549namespace {
550
Daniel Dunbar644dca02009-12-04 08:17:33 +0000551class TopLevelDeclTrackerConsumer : public ASTConsumer {
552 ASTUnit &Unit;
553
554public:
555 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
556
557 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000558 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
559 Decl *D = *it;
560 // FIXME: Currently ObjC method declarations are incorrectly being
561 // reported as top-level declarations, even though their DeclContext
562 // is the containing ObjC @interface/@implementation. This is a
563 // fundamental problem in the parser right now.
564 if (isa<ObjCMethodDecl>(D))
565 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000566 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000567 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000568 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000569
570 // We're not interested in "interesting" decls.
571 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000572};
573
574class TopLevelDeclTrackerAction : public ASTFrontendAction {
575public:
576 ASTUnit &Unit;
577
Daniel Dunbar764c0822009-12-01 09:51:01 +0000578 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
579 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000580 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000581 }
582
583public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000584 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
585
Daniel Dunbar764c0822009-12-01 09:51:01 +0000586 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000587 virtual bool usesCompleteTranslationUnit() {
588 return Unit.isCompleteTranslationUnit();
589 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000590};
591
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000592class PrecompilePreambleConsumer : public PCHGenerator {
593 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000594 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000595
596public:
597 PrecompilePreambleConsumer(ASTUnit &Unit,
598 const Preprocessor &PP, bool Chaining,
599 const char *isysroot, llvm::raw_ostream *Out)
600 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
601
Douglas Gregore9db88f2010-08-03 19:06:41 +0000602 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000603 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
604 Decl *D = *it;
605 // FIXME: Currently ObjC method declarations are incorrectly being
606 // reported as top-level declarations, even though their DeclContext
607 // is the containing ObjC @interface/@implementation. This is a
608 // fundamental problem in the parser right now.
609 if (isa<ObjCMethodDecl>(D))
610 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000611 TopLevelDecls.push_back(D);
612 }
613 }
614
615 virtual void HandleTranslationUnit(ASTContext &Ctx) {
616 PCHGenerator::HandleTranslationUnit(Ctx);
617 if (!Unit.getDiagnostics().hasErrorOccurred()) {
618 // Translate the top-level declarations we captured during
619 // parsing into declaration IDs in the precompiled
620 // preamble. This will allow us to deserialize those top-level
621 // declarations when requested.
622 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
623 Unit.addTopLevelDeclFromPreamble(
624 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000625 }
626 }
627};
628
629class PrecompilePreambleAction : public ASTFrontendAction {
630 ASTUnit &Unit;
631
632public:
633 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
634
635 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
636 llvm::StringRef InFile) {
637 std::string Sysroot;
638 llvm::raw_ostream *OS = 0;
639 bool Chaining;
640 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
641 OS, Chaining))
642 return 0;
643
644 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
645 Sysroot.c_str() : 0;
646 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
647 isysroot, OS);
648 }
649
650 virtual bool hasCodeCompletionSupport() const { return false; }
651 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000652 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000653};
654
Daniel Dunbar764c0822009-12-01 09:51:01 +0000655}
656
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000657/// Parse the source file into a translation unit using the given compiler
658/// invocation, replacing the current translation unit.
659///
660/// \returns True if a failure occurred that causes the ASTUnit not to
661/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000662bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000663 delete SavedMainFileBuffer;
664 SavedMainFileBuffer = 0;
665
Douglas Gregora0734c52010-08-19 01:33:06 +0000666 if (!Invocation.get()) {
667 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000668 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000669 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000670
Daniel Dunbar764c0822009-12-01 09:51:01 +0000671 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000672 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000673 Clang.setInvocation(Invocation.take());
674 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
675
Douglas Gregor8e984da2010-08-04 16:47:14 +0000676 // Set up diagnostics, capturing any diagnostics that would
677 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000678 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000679 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
680 getDiagnostics(),
681 StoredDiagnostics);
Douglas Gregord03e8232010-04-05 21:10:19 +0000682
Daniel Dunbar764c0822009-12-01 09:51:01 +0000683 // Create the target instance.
684 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
685 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000686 if (!Clang.hasTarget()) {
687 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000688 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000689 }
690
Daniel Dunbar764c0822009-12-01 09:51:01 +0000691 // Inform the target of the language options.
692 //
693 // FIXME: We shouldn't need to do this, the target should be immutable once
694 // created. This complexity should be lifted elsewhere.
695 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000696
Daniel Dunbar764c0822009-12-01 09:51:01 +0000697 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
698 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000699 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000700 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000701 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
702 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000703
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000704 // Configure the various subsystems.
705 // FIXME: Should we retain the previous file manager?
706 FileMgr.reset(new FileManager);
707 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000708 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000709 Ctx.reset();
710 PP.reset();
711
712 // Clear out old caches and data.
713 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000714 CleanTemporaryFiles();
715 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000716
Douglas Gregor7b02b582010-08-20 00:02:33 +0000717 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000718 StoredDiagnostics.erase(
719 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
720 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000721 TopLevelDeclsInPreamble.clear();
722 }
723
Daniel Dunbar764c0822009-12-01 09:51:01 +0000724 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000725 Clang.setFileManager(&getFileManager());
726
Daniel Dunbar764c0822009-12-01 09:51:01 +0000727 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000728 Clang.setSourceManager(&getSourceManager());
729
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000730 // If the main file has been overridden due to the use of a preamble,
731 // make that override happen and introduce the preamble.
732 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000733 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000734 if (OverrideMainBuffer) {
735 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
736 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
737 PreprocessorOpts.PrecompiledPreambleBytes.second
738 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000739 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000740 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000741 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000742
Douglas Gregord9a30af2010-08-02 20:51:39 +0000743 // The stored diagnostic has the old source manager in it; update
744 // the locations to refer into the new source manager. Since we've
745 // been careful to make sure that the source manager's state
746 // before and after are identical, so that we can reuse the source
747 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000748 for (unsigned I = NumStoredDiagnosticsFromDriver,
749 N = StoredDiagnostics.size();
750 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000751 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
752 getSourceManager());
753 StoredDiagnostics[I].setLocation(Loc);
754 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000755
756 // Keep track of the override buffer;
757 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000758 } else {
759 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
760 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000761 }
762
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000763 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
764 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000765 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000766 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000767 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000768
Daniel Dunbar644dca02009-12-04 08:17:33 +0000769 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000770
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000771 // Steal the created target, context, and preprocessor, and take back the
772 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000773 TheSema.reset(Clang.takeSema());
774 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000775 Ctx.reset(Clang.takeASTContext());
776 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000777 Clang.takeSourceManager();
778 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000779 Target.reset(Clang.takeTarget());
780
Daniel Dunbar644dca02009-12-04 08:17:33 +0000781 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000782
783 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000784 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000785 PreprocessorOpts.eraseRemappedFile(
786 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000787 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
788 }
789
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000790 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000791
792 // If we were asked to cache code-completion results and don't have any
793 // results yet, do so now.
794 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
795 CacheCodeCompletionResults();
Douglas Gregorbb6a8812010-10-08 04:03:57 +0000796
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000797 return false;
798
Daniel Dunbar764c0822009-12-01 09:51:01 +0000799error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000800 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000801 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000802 PreprocessorOpts.eraseRemappedFile(
803 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000804 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000805 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000806 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000807 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000808 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000809
Daniel Dunbar764c0822009-12-01 09:51:01 +0000810 Clang.takeSourceManager();
811 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000812 Invocation.reset(Clang.takeInvocation());
813 return true;
814}
815
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000816/// \brief Simple function to retrieve a path for a preamble precompiled header.
817static std::string GetPreamblePCHPath() {
818 // FIXME: This is lame; sys::Path should provide this function (in particular,
819 // it should know how to find the temporary files dir).
820 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000821 // FIXME: This is a hack so that we can override the preamble file during
822 // crash-recovery testing, which is the only case where the preamble files
823 // are not necessarily cleaned up.
824 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
825 if (TmpFile)
826 return TmpFile;
827
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000828 std::string Error;
829 const char *TmpDir = ::getenv("TMPDIR");
830 if (!TmpDir)
831 TmpDir = ::getenv("TEMP");
832 if (!TmpDir)
833 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000834#ifdef LLVM_ON_WIN32
835 if (!TmpDir)
836 TmpDir = ::getenv("USERPROFILE");
837#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000838 if (!TmpDir)
839 TmpDir = "/tmp";
840 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000841 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000842 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000843 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000844 if (P.createTemporaryFileOnDisk())
845 return std::string();
846
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000847 return P.str();
848}
849
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000850/// \brief Compute the preamble for the main file, providing the source buffer
851/// that corresponds to the main file along with a pair (bytes, start-of-line)
852/// that describes the preamble.
853std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000854ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
855 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000856 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000857 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000858 = Invocation.getPreprocessorOpts();
859 CreatedBuffer = false;
860
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000861 // Try to determine if the main file has been remapped, either from the
862 // command line (to another file) or directly through the compiler invocation
863 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000864 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000865 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
866 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
867 // Check whether there is a file-file remapping of the main file
868 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000869 M = PreprocessorOpts.remapped_file_begin(),
870 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000871 M != E;
872 ++M) {
873 llvm::sys::PathWithStatus MPath(M->first);
874 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
875 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
876 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000877 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000878 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000879 CreatedBuffer = false;
880 }
881
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000882 Buffer = llvm::MemoryBuffer::getFile(M->second);
883 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000884 return std::make_pair((llvm::MemoryBuffer*)0,
885 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000886 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000887 }
888 }
889 }
890
891 // Check whether there is a file-buffer remapping. It supercedes the
892 // file-file remapping.
893 for (PreprocessorOptions::remapped_file_buffer_iterator
894 M = PreprocessorOpts.remapped_file_buffer_begin(),
895 E = PreprocessorOpts.remapped_file_buffer_end();
896 M != E;
897 ++M) {
898 llvm::sys::PathWithStatus MPath(M->first);
899 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
900 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
901 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000902 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000903 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000904 CreatedBuffer = false;
905 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000906
Douglas Gregor4dde7492010-07-23 23:58:40 +0000907 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000908 }
909 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000910 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000911 }
912
913 // If the main source file was not remapped, load it now.
914 if (!Buffer) {
915 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
916 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000917 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000918
919 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000920 }
921
Douglas Gregor028d3e42010-08-09 20:45:32 +0000922 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000923}
924
Douglas Gregor6481ef12010-07-24 00:38:13 +0000925static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
926 bool DeleteOld,
927 unsigned NewSize,
928 llvm::StringRef NewName) {
929 llvm::MemoryBuffer *Result
930 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
931 memcpy(const_cast<char*>(Result->getBufferStart()),
932 Old->getBufferStart(), Old->getBufferSize());
933 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000934 ' ', NewSize - Old->getBufferSize() - 1);
935 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000936
937 if (DeleteOld)
938 delete Old;
939
940 return Result;
941}
942
Douglas Gregor4dde7492010-07-23 23:58:40 +0000943/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
944/// the source file.
945///
946/// This routine will compute the preamble of the main source file. If a
947/// non-trivial preamble is found, it will precompile that preamble into a
948/// precompiled header so that the precompiled preamble can be used to reduce
949/// reparsing time. If a precompiled preamble has already been constructed,
950/// this routine will determine if it is still valid and, if so, avoid
951/// rebuilding the precompiled preamble.
952///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000953/// \param AllowRebuild When true (the default), this routine is
954/// allowed to rebuild the precompiled preamble if it is found to be
955/// out-of-date.
956///
957/// \param MaxLines When non-zero, the maximum number of lines that
958/// can occur within the preamble.
959///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000960/// \returns If the precompiled preamble can be used, returns a newly-allocated
961/// buffer that should be used in place of the main file when doing so.
962/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000963llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +0000964 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +0000965 bool AllowRebuild,
966 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000967 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
968 PreprocessorOptions &PreprocessorOpts
969 = PreambleInvocation.getPreprocessorOpts();
970
971 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000972 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +0000973 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000974
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000975 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000976 // We couldn't find a preamble in the main source. Clear out the current
977 // preamble, if we have one. It's obviously no good any more.
978 Preamble.clear();
979 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000980 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000981 PreambleFile.clear();
982 }
983 if (CreatedPreambleBuffer)
984 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000985
986 // The next time we actually see a preamble, precompile it.
987 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000988 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000989 }
990
991 if (!Preamble.empty()) {
992 // We've previously computed a preamble. Check whether we have the same
993 // preamble now that we did before, and that there's enough space in
994 // the main-file buffer within the precompiled preamble to fit the
995 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000996 if (Preamble.size() == NewPreamble.second.first &&
997 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000998 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000999 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001000 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001001 // The preamble has not changed. We may be able to re-use the precompiled
1002 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001003
Douglas Gregor0e119552010-07-31 00:40:00 +00001004 // Check that none of the files used by the preamble have changed.
1005 bool AnyFileChanged = false;
1006
1007 // First, make a record of those files that have been overridden via
1008 // remapping or unsaved_files.
1009 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1010 for (PreprocessorOptions::remapped_file_iterator
1011 R = PreprocessorOpts.remapped_file_begin(),
1012 REnd = PreprocessorOpts.remapped_file_end();
1013 !AnyFileChanged && R != REnd;
1014 ++R) {
1015 struct stat StatBuf;
1016 if (stat(R->second.c_str(), &StatBuf)) {
1017 // If we can't stat the file we're remapping to, assume that something
1018 // horrible happened.
1019 AnyFileChanged = true;
1020 break;
1021 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001022
Douglas Gregor0e119552010-07-31 00:40:00 +00001023 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1024 StatBuf.st_mtime);
1025 }
1026 for (PreprocessorOptions::remapped_file_buffer_iterator
1027 R = PreprocessorOpts.remapped_file_buffer_begin(),
1028 REnd = PreprocessorOpts.remapped_file_buffer_end();
1029 !AnyFileChanged && R != REnd;
1030 ++R) {
1031 // FIXME: Should we actually compare the contents of file->buffer
1032 // remappings?
1033 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1034 0);
1035 }
1036
1037 // Check whether anything has changed.
1038 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1039 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1040 !AnyFileChanged && F != FEnd;
1041 ++F) {
1042 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1043 = OverriddenFiles.find(F->first());
1044 if (Overridden != OverriddenFiles.end()) {
1045 // This file was remapped; check whether the newly-mapped file
1046 // matches up with the previous mapping.
1047 if (Overridden->second != F->second)
1048 AnyFileChanged = true;
1049 continue;
1050 }
1051
1052 // The file was not remapped; check whether it has changed on disk.
1053 struct stat StatBuf;
1054 if (stat(F->first(), &StatBuf)) {
1055 // If we can't stat the file, assume that something horrible happened.
1056 AnyFileChanged = true;
1057 } else if (StatBuf.st_size != F->second.first ||
1058 StatBuf.st_mtime != F->second.second)
1059 AnyFileChanged = true;
1060 }
1061
1062 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001063 // Okay! We can re-use the precompiled preamble.
1064
1065 // Set the state of the diagnostic object to mimic its state
1066 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001067 // FIXME: This won't catch any #pragma push warning changes that
1068 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001069 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001070 ProcessWarningOptions(getDiagnostics(),
1071 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001072 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1073 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1074 StoredDiagnostics.erase(
1075 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1076 StoredDiagnostics.end());
1077
1078 // Create a version of the main file buffer that is padded to
1079 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001080 return CreatePaddedMainFileBuffer(NewPreamble.first,
1081 CreatedPreambleBuffer,
1082 PreambleReservedSize,
1083 FrontendOpts.Inputs[0].second);
1084 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001085 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001086
1087 // If we aren't allowed to rebuild the precompiled preamble, just
1088 // return now.
1089 if (!AllowRebuild)
1090 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001091
Douglas Gregor4dde7492010-07-23 23:58:40 +00001092 // We can't reuse the previously-computed preamble. Build a new one.
1093 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001094 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001095 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001096 } else if (!AllowRebuild) {
1097 // We aren't allowed to rebuild the precompiled preamble; just
1098 // return now.
1099 return 0;
1100 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001101
1102 // If the preamble rebuild counter > 1, it's because we previously
1103 // failed to build a preamble and we're not yet ready to try
1104 // again. Decrement the counter and return a failure.
1105 if (PreambleRebuildCounter > 1) {
1106 --PreambleRebuildCounter;
1107 return 0;
1108 }
1109
Douglas Gregore10f0e52010-09-11 17:56:52 +00001110 // Create a temporary file for the precompiled preamble. In rare
1111 // circumstances, this can fail.
1112 std::string PreamblePCHPath = GetPreamblePCHPath();
1113 if (PreamblePCHPath.empty()) {
1114 // Try again next time.
1115 PreambleRebuildCounter = 1;
1116 return 0;
1117 }
1118
Douglas Gregor4dde7492010-07-23 23:58:40 +00001119 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001120 llvm::Timer *PreambleTimer = 0;
1121 if (TimerGroup.get()) {
1122 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1123 PreambleTimer->startTimer();
1124 Timers.push_back(PreambleTimer);
1125 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001126
1127 // Create a new buffer that stores the preamble. The buffer also contains
1128 // extra space for the original contents of the file (which will be present
1129 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001130 // grows.
1131 PreambleReservedSize = NewPreamble.first->getBufferSize();
1132 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001133 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001134 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001135 PreambleReservedSize *= 2;
1136
Douglas Gregord9a30af2010-08-02 20:51:39 +00001137 // Save the preamble text for later; we'll need to compare against it for
1138 // subsequent reparses.
1139 Preamble.assign(NewPreamble.first->getBufferStart(),
1140 NewPreamble.first->getBufferStart()
1141 + NewPreamble.second.first);
1142 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1143
Douglas Gregora0734c52010-08-19 01:33:06 +00001144 delete PreambleBuffer;
1145 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001146 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001147 FrontendOpts.Inputs[0].second);
1148 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001149 NewPreamble.first->getBufferStart(), Preamble.size());
1150 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001151 ' ', PreambleReservedSize - Preamble.size() - 1);
1152 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001153
1154 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001155 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001156 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1157
1158 // Tell the compiler invocation to generate a temporary precompiled header.
1159 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001160 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001161 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001162 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001163 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1164 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001165
1166 // Create the compiler instance to use for building the precompiled preamble.
1167 CompilerInstance Clang;
1168 Clang.setInvocation(&PreambleInvocation);
1169 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1170
Douglas Gregor8e984da2010-08-04 16:47:14 +00001171 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001172 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001173 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1174 getDiagnostics(),
1175 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001176
1177 // Create the target instance.
1178 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1179 Clang.getTargetOpts()));
1180 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001181 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1182 Preamble.clear();
1183 if (CreatedPreambleBuffer)
1184 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001185 if (PreambleTimer)
1186 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001187 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001188 PreprocessorOpts.eraseRemappedFile(
1189 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001190 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191 }
1192
1193 // Inform the target of the language options.
1194 //
1195 // FIXME: We shouldn't need to do this, the target should be immutable once
1196 // created. This complexity should be lifted elsewhere.
1197 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1198
1199 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1200 "Invocation must have exactly one source file!");
1201 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1202 "FIXME: AST inputs not yet supported here!");
1203 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1204 "IR inputs not support here!");
1205
1206 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001207 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001208 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001209 StoredDiagnostics.erase(
1210 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1211 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001212 TopLevelDecls.clear();
1213 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001214
1215 // Create a file manager object to provide access to and cache the filesystem.
1216 Clang.setFileManager(new FileManager);
1217
1218 // Create the source manager.
1219 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1220
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001221 llvm::OwningPtr<PrecompilePreambleAction> Act;
1222 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001223 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1224 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001225 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001226 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1227 Preamble.clear();
1228 if (CreatedPreambleBuffer)
1229 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001230 if (PreambleTimer)
1231 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001232 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001233 PreprocessorOpts.eraseRemappedFile(
1234 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001235 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236 }
1237
1238 Act->Execute();
1239 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001240 Clang.takeInvocation();
1241
Douglas Gregore9db88f2010-08-03 19:06:41 +00001242 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001243 // There were errors parsing the preamble, so no precompiled header was
1244 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001245 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001246 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1247 Preamble.clear();
1248 if (CreatedPreambleBuffer)
1249 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001250 if (PreambleTimer)
1251 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001252 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001253 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001254 PreprocessorOpts.eraseRemappedFile(
1255 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001256 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001257 }
1258
1259 // Keep track of the preamble we precompiled.
1260 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001261 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1262 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001263
1264 // Keep track of all of the files that the source manager knows about,
1265 // so we can verify whether they have changed or not.
1266 FilesInPreamble.clear();
1267 SourceManager &SourceMgr = Clang.getSourceManager();
1268 const llvm::MemoryBuffer *MainFileBuffer
1269 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1270 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1271 FEnd = SourceMgr.fileinfo_end();
1272 F != FEnd;
1273 ++F) {
1274 const FileEntry *File = F->second->Entry;
1275 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1276 continue;
1277
1278 FilesInPreamble[File->getName()]
1279 = std::make_pair(F->second->getSize(), File->getModificationTime());
1280 }
1281
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001282 if (PreambleTimer)
1283 PreambleTimer->stopTimer();
Douglas Gregora6f74e22010-09-27 16:43:25 +00001284
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001285 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001286 PreprocessorOpts.eraseRemappedFile(
1287 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001288 return CreatePaddedMainFileBuffer(NewPreamble.first,
1289 CreatedPreambleBuffer,
1290 PreambleReservedSize,
1291 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001292}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001293
Douglas Gregore9db88f2010-08-03 19:06:41 +00001294void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1295 std::vector<Decl *> Resolved;
1296 Resolved.reserve(TopLevelDeclsInPreamble.size());
1297 ExternalASTSource &Source = *getASTContext().getExternalSource();
1298 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1299 // Resolve the declaration ID to an actual declaration, possibly
1300 // deserializing the declaration in the process.
1301 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1302 if (D)
1303 Resolved.push_back(D);
1304 }
1305 TopLevelDeclsInPreamble.clear();
1306 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1307}
1308
1309unsigned ASTUnit::getMaxPCHLevel() const {
1310 if (!getOnlyLocalDecls())
1311 return Decl::MaxPCHLevel;
1312
Sebastian Redl009e7f22010-10-05 16:15:19 +00001313 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001314}
1315
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001316bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1317 if (!Invocation)
1318 return true;
1319
1320 // We'll manage file buffers ourselves.
1321 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1322 Invocation->getFrontendOpts().DisableFree = false;
1323
1324 if (getenv("LIBCLANG_TIMING"))
1325 TimerGroup.reset(
1326 new llvm::TimerGroup(Invocation->getFrontendOpts().Inputs[0].second));
1327
1328
1329 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1330 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
1331 if (PrecompilePreamble && !Invocation->getLangOpts().CPlusPlus) {
1332 PreambleRebuildCounter = 1;
1333 OverrideMainBuffer
1334 = getMainBufferWithPrecompiledPreamble(*Invocation);
1335 }
1336
1337 llvm::Timer *ParsingTimer = 0;
1338 if (TimerGroup.get()) {
1339 ParsingTimer = new llvm::Timer("Initial parse", *TimerGroup);
1340 ParsingTimer->startTimer();
1341 Timers.push_back(ParsingTimer);
1342 }
1343
1344 bool Failed = Parse(OverrideMainBuffer);
1345 if (ParsingTimer)
1346 ParsingTimer->stopTimer();
1347
1348 return Failed;
1349}
1350
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001351ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1352 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1353 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001354 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001355 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001356 bool CompleteTranslationUnit,
1357 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001358 if (!Diags.getPtr()) {
1359 // No diagnostics engine was provided, so create our own diagnostics object
1360 // with the default options.
1361 DiagnosticOptions DiagOpts;
1362 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1363 }
1364
1365 // Create the AST unit.
1366 llvm::OwningPtr<ASTUnit> AST;
1367 AST.reset(new ASTUnit(false));
1368 AST->Diagnostics = Diags;
1369 AST->CaptureDiagnostics = CaptureDiagnostics;
1370 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001371 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001372 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001373 AST->Invocation.reset(CI);
1374
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001375 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001376}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001377
1378ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1379 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001380 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001381 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001382 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001383 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001384 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001385 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001386 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001387 bool CompleteTranslationUnit,
1388 bool CacheCodeCompletionResults) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001389 bool CreatedDiagnosticsObject = false;
1390
Douglas Gregor7f95d262010-04-05 23:52:57 +00001391 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001392 // No diagnostics engine was provided, so create our own diagnostics object
1393 // with the default options.
1394 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001395 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001396 CreatedDiagnosticsObject = true;
Douglas Gregord03e8232010-04-05 21:10:19 +00001397 }
1398
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001399 llvm::SmallVector<const char *, 16> Args;
1400 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1401 Args.insert(Args.end(), ArgBegin, ArgEnd);
1402
1403 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1404 // also want to force it to use clang.
1405 Args.push_back("-fsyntax-only");
1406
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001407 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1408
1409 llvm::OwningPtr<CompilerInvocation> CI;
1410 {
1411 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1412 *Diags,
1413 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001414
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001415 // FIXME: We shouldn't have to pass in the path info.
1416 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1417 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001418
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001419 // Don't check that inputs exist, they have been remapped.
1420 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001421
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001422 llvm::OwningPtr<driver::Compilation> C(
1423 TheDriver.BuildCompilation(Args.size(), Args.data()));
1424
1425 // We expect to get back exactly one command job, if we didn't something
1426 // failed.
1427 const driver::JobList &Jobs = C->getJobs();
1428 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1429 llvm::SmallString<256> Msg;
1430 llvm::raw_svector_ostream OS(Msg);
1431 C->PrintJob(OS, C->getJobs(), "; ", true);
1432 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1433 return 0;
1434 }
1435
1436 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1437 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1438 Diags->Report(diag::err_fe_expected_clang_command);
1439 return 0;
1440 }
1441
1442 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1443 CI.reset(new CompilerInvocation);
1444 CompilerInvocation::CreateFromArgs(*CI,
1445 const_cast<const char **>(CCArgs.data()),
1446 const_cast<const char **>(CCArgs.data()) +
1447 CCArgs.size(),
1448 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001449 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001450
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001451 // Override any files that need remapping
1452 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001453 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001454 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001455
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001456 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001457 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001458
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001459 // Create the AST unit.
1460 llvm::OwningPtr<ASTUnit> AST;
1461 AST.reset(new ASTUnit(false));
1462 AST->Diagnostics = Diags;
1463 AST->CaptureDiagnostics = CaptureDiagnostics;
1464 AST->OnlyLocalDecls = OnlyLocalDecls;
1465 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1466 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1467 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1468 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1469 AST->StoredDiagnostics.swap(StoredDiagnostics);
1470 AST->Invocation.reset(CI.take());
1471 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001472}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001473
1474bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1475 if (!Invocation.get())
1476 return true;
1477
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001478 llvm::Timer *ReparsingTimer = 0;
1479 if (TimerGroup.get()) {
1480 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1481 ReparsingTimer->startTimer();
1482 Timers.push_back(ReparsingTimer);
1483 }
1484
Douglas Gregor0e119552010-07-31 00:40:00 +00001485 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001486 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1487 for (PreprocessorOptions::remapped_file_buffer_iterator
1488 R = PPOpts.remapped_file_buffer_begin(),
1489 REnd = PPOpts.remapped_file_buffer_end();
1490 R != REnd;
1491 ++R) {
1492 delete R->second;
1493 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001494 Invocation->getPreprocessorOpts().clearRemappedFiles();
1495 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1496 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1497 RemappedFiles[I].second);
1498
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001499 // If we have a preamble file lying around, or if we might try to
1500 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001501 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001502 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001503 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001504
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001505 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001506 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001507 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001508 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1509 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001510
Douglas Gregor4dde7492010-07-23 23:58:40 +00001511 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001512 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001513 if (ReparsingTimer)
1514 ReparsingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001515
1516 if (ShouldCacheCodeCompletionResults) {
1517 if (CacheCodeCompletionCoolDown > 0)
1518 --CacheCodeCompletionCoolDown;
1519 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1520 CacheCodeCompletionResults();
1521 }
1522
Douglas Gregor4dde7492010-07-23 23:58:40 +00001523 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001524}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001525
Douglas Gregorb14904c2010-08-13 22:48:40 +00001526//----------------------------------------------------------------------------//
1527// Code completion
1528//----------------------------------------------------------------------------//
1529
1530namespace {
1531 /// \brief Code completion consumer that combines the cached code-completion
1532 /// results from an ASTUnit with the code-completion results provided to it,
1533 /// then passes the result on to
1534 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1535 unsigned NormalContexts;
1536 ASTUnit &AST;
1537 CodeCompleteConsumer &Next;
1538
1539 public:
1540 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001541 bool IncludeMacros, bool IncludeCodePatterns,
1542 bool IncludeGlobals)
1543 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001544 Next.isOutputBinary()), AST(AST), Next(Next)
1545 {
1546 // Compute the set of contexts in which we will look when we don't have
1547 // any information about the specific context.
1548 NormalContexts
1549 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1550 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1551 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1552 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1553 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1554 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1555 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1556 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001557 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001558 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1559 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001560
Douglas Gregorb14904c2010-08-13 22:48:40 +00001561 if (AST.getASTContext().getLangOptions().CPlusPlus)
1562 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1563 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1564 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1565 }
1566
1567 virtual void ProcessCodeCompleteResults(Sema &S,
1568 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001569 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001570 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001571
1572 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1573 OverloadCandidate *Candidates,
1574 unsigned NumCandidates) {
1575 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1576 }
1577 };
1578}
Douglas Gregord46cf182010-08-16 20:01:48 +00001579
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001580/// \brief Helper function that computes which global names are hidden by the
1581/// local code-completion results.
1582void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall276321a2010-08-25 06:19:51 +00001583 CodeCompletionResult *Results,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001584 unsigned NumResults,
1585 ASTContext &Ctx,
1586 llvm::StringSet<> &HiddenNames) {
1587 bool OnlyTagNames = false;
1588 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001589 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001590 case CodeCompletionContext::CCC_TopLevel:
1591 case CodeCompletionContext::CCC_ObjCInterface:
1592 case CodeCompletionContext::CCC_ObjCImplementation:
1593 case CodeCompletionContext::CCC_ObjCIvarList:
1594 case CodeCompletionContext::CCC_ClassStructUnion:
1595 case CodeCompletionContext::CCC_Statement:
1596 case CodeCompletionContext::CCC_Expression:
1597 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1598 case CodeCompletionContext::CCC_MemberAccess:
1599 case CodeCompletionContext::CCC_Namespace:
1600 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001601 case CodeCompletionContext::CCC_Name:
1602 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001603 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001604 break;
1605
1606 case CodeCompletionContext::CCC_EnumTag:
1607 case CodeCompletionContext::CCC_UnionTag:
1608 case CodeCompletionContext::CCC_ClassOrStructTag:
1609 OnlyTagNames = true;
1610 break;
1611
1612 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001613 case CodeCompletionContext::CCC_MacroName:
1614 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001615 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001616 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001617 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001618 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001619 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001620 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001621 // We're looking for nothing, or we're looking for names that cannot
1622 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001623 return;
1624 }
1625
John McCall276321a2010-08-25 06:19:51 +00001626 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001627 for (unsigned I = 0; I != NumResults; ++I) {
1628 if (Results[I].Kind != Result::RK_Declaration)
1629 continue;
1630
1631 unsigned IDNS
1632 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1633
1634 bool Hiding = false;
1635 if (OnlyTagNames)
1636 Hiding = (IDNS & Decl::IDNS_Tag);
1637 else {
1638 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001639 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1640 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001641 if (Ctx.getLangOptions().CPlusPlus)
1642 HiddenIDNS |= Decl::IDNS_Tag;
1643 Hiding = (IDNS & HiddenIDNS);
1644 }
1645
1646 if (!Hiding)
1647 continue;
1648
1649 DeclarationName Name = Results[I].Declaration->getDeclName();
1650 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1651 HiddenNames.insert(Identifier->getName());
1652 else
1653 HiddenNames.insert(Name.getAsString());
1654 }
1655}
1656
1657
Douglas Gregord46cf182010-08-16 20:01:48 +00001658void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1659 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001660 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001661 unsigned NumResults) {
1662 // Merge the results we were given with the results we cached.
1663 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001664 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001665 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001666 : (1 << (Context.getKind() - 1)));
1667
1668 // Contains the set of names that are hidden by "local" completion results.
1669 llvm::StringSet<> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001670 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001671 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001672 llvm::SmallVector<Result, 8> AllResults;
1673 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001674 C = AST.cached_completion_begin(),
1675 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001676 C != CEnd; ++C) {
1677 // If the context we are in matches any of the contexts we are
1678 // interested in, we'll add this result.
1679 if ((C->ShowInContexts & InContexts) == 0)
1680 continue;
1681
1682 // If we haven't added any results previously, do so now.
1683 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001684 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1685 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001686 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1687 AddedResult = true;
1688 }
1689
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001690 // Determine whether this global completion result is hidden by a local
1691 // completion result. If so, skip it.
1692 if (C->Kind != CXCursor_MacroDefinition &&
1693 HiddenNames.count(C->Completion->getTypedText()))
1694 continue;
1695
Douglas Gregord46cf182010-08-16 20:01:48 +00001696 // Adjust priority based on similar type classes.
1697 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001698 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001699 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001700 if (!Context.getPreferredType().isNull()) {
1701 if (C->Kind == CXCursor_MacroDefinition) {
1702 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001703 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001704 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001705 } else if (C->Type) {
1706 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001707 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001708 Context.getPreferredType().getUnqualifiedType());
1709 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1710 if (ExpectedSTC == C->TypeClass) {
1711 // We know this type is similar; check for an exact match.
1712 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001713 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001714 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001715 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001716 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1717 Priority /= CCF_ExactTypeMatch;
1718 else
1719 Priority /= CCF_SimilarTypeMatch;
1720 }
1721 }
1722 }
1723
Douglas Gregor12785102010-08-24 20:21:13 +00001724 // Adjust the completion string, if required.
1725 if (C->Kind == CXCursor_MacroDefinition &&
1726 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1727 // Create a new code-completion string that just contains the
1728 // macro name, without its arguments.
1729 Completion = new CodeCompletionString;
1730 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1731 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001732 CursorKind = CXCursor_NotImplemented;
1733 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001734 }
1735
Douglas Gregor8850aa32010-08-25 18:03:13 +00001736 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001737 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001738 }
1739
1740 // If we did not add any cached completion results, just forward the
1741 // results we were given to the next consumer.
1742 if (!AddedResult) {
1743 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1744 return;
1745 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001746
Douglas Gregord46cf182010-08-16 20:01:48 +00001747 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1748 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001749
1750 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1751 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001752}
1753
1754
1755
Douglas Gregor8e984da2010-08-04 16:47:14 +00001756void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1757 RemappedFile *RemappedFiles,
1758 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001759 bool IncludeMacros,
1760 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001761 CodeCompleteConsumer &Consumer,
1762 Diagnostic &Diag, LangOptions &LangOpts,
1763 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001764 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1765 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001766 if (!Invocation.get())
1767 return;
1768
Douglas Gregor028d3e42010-08-09 20:45:32 +00001769 llvm::Timer *CompletionTimer = 0;
1770 if (TimerGroup.get()) {
1771 llvm::SmallString<128> TimerName;
1772 llvm::raw_svector_ostream TimerNameOut(TimerName);
1773 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1774 << Column;
1775 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1776 CompletionTimer->startTimer();
1777 Timers.push_back(CompletionTimer);
1778 }
1779
Douglas Gregor8e984da2010-08-04 16:47:14 +00001780 CompilerInvocation CCInvocation(*Invocation);
1781 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1782 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001783
Douglas Gregorb14904c2010-08-13 22:48:40 +00001784 FrontendOpts.ShowMacrosInCodeCompletion
1785 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001786 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001787 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1788 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001789 FrontendOpts.CodeCompletionAt.FileName = File;
1790 FrontendOpts.CodeCompletionAt.Line = Line;
1791 FrontendOpts.CodeCompletionAt.Column = Column;
1792
1793 // Set the language options appropriately.
1794 LangOpts = CCInvocation.getLangOpts();
1795
1796 CompilerInstance Clang;
1797 Clang.setInvocation(&CCInvocation);
1798 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1799
1800 // Set up diagnostics, capturing any diagnostics produced.
1801 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001802 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001803 CaptureDroppedDiagnostics Capture(true,
1804 Clang.getDiagnostics(),
1805 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001806
1807 // Create the target instance.
1808 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1809 Clang.getTargetOpts()));
1810 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001811 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001812 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001813 }
1814
1815 // Inform the target of the language options.
1816 //
1817 // FIXME: We shouldn't need to do this, the target should be immutable once
1818 // created. This complexity should be lifted elsewhere.
1819 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1820
1821 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1822 "Invocation must have exactly one source file!");
1823 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1824 "FIXME: AST inputs not yet supported here!");
1825 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1826 "IR inputs not support here!");
1827
1828
1829 // Use the source and file managers that we were given.
1830 Clang.setFileManager(&FileMgr);
1831 Clang.setSourceManager(&SourceMgr);
1832
1833 // Remap files.
1834 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001835 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001836 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001837 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1838 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001839 OwnedBuffers.push_back(RemappedFiles[I].second);
1840 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001841
Douglas Gregorb14904c2010-08-13 22:48:40 +00001842 // Use the code completion consumer we were given, but adding any cached
1843 // code-completion results.
1844 AugmentedCodeCompleteConsumer
1845 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001846 FrontendOpts.ShowCodePatternsInCodeCompletion,
1847 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001848 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001849
Douglas Gregor028d3e42010-08-09 20:45:32 +00001850 // If we have a precompiled preamble, try to use it. We only allow
1851 // the use of the precompiled preamble if we're if the completion
1852 // point is within the main file, after the end of the precompiled
1853 // preamble.
1854 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1855 if (!PreambleFile.empty()) {
1856 using llvm::sys::FileStatus;
1857 llvm::sys::PathWithStatus CompleteFilePath(File);
1858 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1859 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1860 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1861 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001862 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001863 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1864 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001865 }
1866
1867 // If the main file has been overridden due to the use of a preamble,
1868 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001869 StoredDiagnostics.insert(StoredDiagnostics.end(),
1870 this->StoredDiagnostics.begin(),
1871 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001872 if (OverrideMainBuffer) {
1873 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1874 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1875 PreprocessorOpts.PrecompiledPreambleBytes.second
1876 = PreambleEndsAtStartOfLine;
1877 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1878 PreprocessorOpts.DisablePCHValidation = true;
1879
1880 // The stored diagnostics have the old source manager. Copy them
1881 // to our output set of stored diagnostics, updating the source
1882 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001883 for (unsigned I = NumStoredDiagnosticsFromDriver,
1884 N = this->StoredDiagnostics.size();
1885 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001886 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1887 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1888 StoredDiagnostics[I].setLocation(Loc);
1889 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001890
Douglas Gregorb97b6662010-08-20 00:59:43 +00001891 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001892 } else {
1893 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1894 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001895 }
1896
Douglas Gregor8e984da2010-08-04 16:47:14 +00001897 llvm::OwningPtr<SyntaxOnlyAction> Act;
1898 Act.reset(new SyntaxOnlyAction);
1899 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1900 Clang.getFrontendOpts().Inputs[0].first)) {
1901 Act->Execute();
1902 Act->EndSourceFile();
1903 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001904
1905 if (CompletionTimer)
1906 CompletionTimer->stopTimer();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001907
1908 // Steal back our resources.
1909 Clang.takeFileManager();
1910 Clang.takeSourceManager();
1911 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001912 Clang.takeCodeCompletionConsumer();
1913}
Douglas Gregore9386682010-08-13 05:36:37 +00001914
1915bool ASTUnit::Save(llvm::StringRef File) {
1916 if (getDiagnostics().hasErrorOccurred())
1917 return true;
1918
1919 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1920 // unconditionally create a stat cache when we parse the file?
1921 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001922 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1923 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001924 if (!ErrorInfo.empty() || Out.has_error())
1925 return true;
1926
1927 std::vector<unsigned char> Buffer;
1928 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001929 ASTWriter Writer(Stream);
1930 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001931
1932 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001933 if (!Buffer.empty())
1934 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001935 Out.close();
1936 return Out.has_error();
1937}