blob: bbee11ba7c98a3104c2a62bf4b49ded8fc201355 [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 Gregor16896c42010-10-28 15:44:59 +000047using llvm::TimeRecord;
48
49namespace {
50 class SimpleTimer {
51 bool WantTiming;
52 TimeRecord Start;
53 std::string Output;
54
55 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000056 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000057 Start = TimeRecord::getCurrentTime();
58 }
59
60 void setOutput(llvm::StringRef Output) {
61 if (WantTiming)
62 this->Output = Output;
63 }
64
65 void setOutput(llvm::Twine Output) {
66 if (WantTiming)
67 this->Output = Output.str();
68 }
69
70 void setOutput(const char *Output) {
71 if (WantTiming)
72 this->Output = Output;
73 }
74
75 ~SimpleTimer() {
76 if (WantTiming) {
77 TimeRecord Elapsed = TimeRecord::getCurrentTime();
78 Elapsed -= Start;
79 llvm::errs() << Output << ':';
80 Elapsed.print(Elapsed, llvm::errs());
81 llvm::errs() << '\n';
82 }
83 }
84 };
85}
86
Douglas Gregorbb420ab2010-08-04 05:53:38 +000087/// \brief After failing to build a precompiled preamble (due to
88/// errors in the source that occurs in the preamble), the number of
89/// reparses during which we'll skip even trying to precompile the
90/// preamble.
91const unsigned DefaultPreambleRebuildInterval = 5;
92
Douglas Gregord03e8232010-04-05 21:10:19 +000093ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000095 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
96 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000097 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000098 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000099 ShouldCacheCodeCompletionResults(false),
100 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000101 CacheCodeCompletionCoolDown(0),
102 UnsafeToFree(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000103}
Douglas Gregord03e8232010-04-05 21:10:19 +0000104
Daniel Dunbar764c0822009-12-01 09:51:01 +0000105ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000106 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000107 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000108 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000109 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000110
111 // Free the buffers associated with remapped files. We are required to
112 // perform this operation here because we explicitly request that the
113 // compiler instance *not* free these buffers for each invocation of the
114 // parser.
115 if (Invocation.get()) {
116 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
117 for (PreprocessorOptions::remapped_file_buffer_iterator
118 FB = PPOpts.remapped_file_buffer_begin(),
119 FBEnd = PPOpts.remapped_file_buffer_end();
120 FB != FBEnd;
121 ++FB)
122 delete FB->second;
123 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000124
125 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000126 delete PreambleBuffer;
127
Douglas Gregor16896c42010-10-28 15:44:59 +0000128 ClearCachedCompletionResults();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000129}
130
131void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000132 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
133 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000134 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000135}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000136
Douglas Gregor39982192010-08-15 06:18:01 +0000137/// \brief Determine the set of code-completion contexts in which this
138/// declaration should be shown.
139static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000140 const LangOptions &LangOpts,
141 bool &IsNestedNameSpecifier) {
142 IsNestedNameSpecifier = false;
143
Douglas Gregor39982192010-08-15 06:18:01 +0000144 if (isa<UsingShadowDecl>(ND))
145 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
146 if (!ND)
147 return 0;
148
149 unsigned Contexts = 0;
150 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
151 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
152 // Types can appear in these contexts.
153 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
154 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
155 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
156 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
157 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000158 | (1 << (CodeCompletionContext::CCC_Type - 1))
159 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000160
161 // In C++, types can appear in expressions contexts (for functional casts).
162 if (LangOpts.CPlusPlus)
163 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
164
165 // In Objective-C, message sends can send interfaces. In Objective-C++,
166 // all types are available due to functional casts.
167 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
168 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
169
170 // Deal with tag names.
171 if (isa<EnumDecl>(ND)) {
172 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
173
Douglas Gregor59cab552010-08-16 23:05:20 +0000174 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000175 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000176 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000177 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
178 if (Record->isUnion())
179 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
180 else
181 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
182
Douglas Gregor39982192010-08-15 06:18:01 +0000183 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000184 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000185 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000186 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000187 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
188 // Values can appear in these contexts.
189 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
190 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000191 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000192 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
193 } else if (isa<ObjCProtocolDecl>(ND)) {
194 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
195 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000196 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000197
198 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000199 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000200 }
201
202 return Contexts;
203}
204
Douglas Gregorb14904c2010-08-13 22:48:40 +0000205void ASTUnit::CacheCodeCompletionResults() {
206 if (!TheSema)
207 return;
208
Douglas Gregor16896c42010-10-28 15:44:59 +0000209 SimpleTimer Timer(WantTiming);
210 if (WantTiming)
211 Timer.setOutput( "Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000212
213 // Clear out the previous results.
214 ClearCachedCompletionResults();
215
216 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000217 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000218 llvm::SmallVector<Result, 8> Results;
219 TheSema->GatherGlobalCodeCompletions(Results);
220
221 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000222 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
223
Douglas Gregorb14904c2010-08-13 22:48:40 +0000224 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
225 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000226 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000227 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000228 CachedCodeCompletionResult CachedResult;
229 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
230 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000231 Ctx->getLangOptions(),
232 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000233 CachedResult.Priority = Results[I].Priority;
234 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000235 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000236
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000237 // Keep track of the type of this completion in an ASTContext-agnostic
238 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000239 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000240 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000241 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000242 CachedResult.Type = 0;
243 } else {
244 CanQualType CanUsageType
245 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
246 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
247
248 // Determine whether we have already seen this type. If so, we save
249 // ourselves the work of formatting the type string by using the
250 // temporary, CanQualType-based hash table to find the associated value.
251 unsigned &TypeValue = CompletionTypes[CanUsageType];
252 if (TypeValue == 0) {
253 TypeValue = CompletionTypes.size();
254 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
255 = TypeValue;
256 }
257
258 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000259 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000260
Douglas Gregor39982192010-08-15 06:18:01 +0000261 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000262
263 /// Handle nested-name-specifiers in C++.
264 if (TheSema->Context.getLangOptions().CPlusPlus &&
265 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
266 // The contexts in which a nested-name-specifier can appear in C++.
267 unsigned NNSContexts
268 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
269 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
270 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
271 | (1 << (CodeCompletionContext::CCC_Statement - 1))
272 | (1 << (CodeCompletionContext::CCC_Expression - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
274 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
275 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
276 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000277 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000278 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
279 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000280
281 if (isa<NamespaceDecl>(Results[I].Declaration) ||
282 isa<NamespaceAliasDecl>(Results[I].Declaration))
283 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
284
285 if (unsigned RemainingContexts
286 = NNSContexts & ~CachedResult.ShowInContexts) {
287 // If there any contexts where this completion can be a
288 // nested-name-specifier but isn't already an option, create a
289 // nested-name-specifier completion.
290 Results[I].StartsNestedNameSpecifier = true;
291 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
292 CachedResult.ShowInContexts = RemainingContexts;
293 CachedResult.Priority = CCP_NestedNameSpecifier;
294 CachedResult.TypeClass = STC_Void;
295 CachedResult.Type = 0;
296 CachedCompletionResults.push_back(CachedResult);
297 }
298 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000299 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000300 }
301
Douglas Gregorb14904c2010-08-13 22:48:40 +0000302 case Result::RK_Keyword:
303 case Result::RK_Pattern:
304 // Ignore keywords and patterns; we don't care, since they are so
305 // easily regenerated.
306 break;
307
308 case Result::RK_Macro: {
309 CachedCodeCompletionResult CachedResult;
310 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
311 CachedResult.ShowInContexts
312 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
313 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
314 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
315 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
316 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
317 | (1 << (CodeCompletionContext::CCC_Statement - 1))
318 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000319 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000320 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000321 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
322 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
323
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000324
Douglas Gregorb14904c2010-08-13 22:48:40 +0000325 CachedResult.Priority = Results[I].Priority;
326 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000327 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000328 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000329 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000330 CachedCompletionResults.push_back(CachedResult);
331 break;
332 }
333 }
334 Results[I].Destroy();
335 }
336
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000337 // Make a note of the state when we performed this caching.
338 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
339 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340}
341
342void ASTUnit::ClearCachedCompletionResults() {
343 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
344 delete CachedCompletionResults[I].Completion;
345 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000346 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000347}
348
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000349namespace {
350
Sebastian Redl2c499f62010-08-18 23:56:43 +0000351/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000352/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000353class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000354 LangOptions &LangOpt;
355 HeaderSearch &HSI;
356 std::string &TargetTriple;
357 std::string &Predefines;
358 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000360 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000361
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000362public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000363 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000364 std::string &TargetTriple, std::string &Predefines,
365 unsigned &Counter)
366 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
367 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000368
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000369 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
370 LangOpt = LangOpts;
371 return false;
372 }
Mike Stump11289f42009-09-09 15:08:12 +0000373
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000374 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000375 TargetTriple = Triple;
376 return false;
377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Sebastian Redl8b41f302010-07-14 23:29:55 +0000379 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000380 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000381 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000382 Predefines = Buffers[0].Data;
383 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
384 Predefines += Buffers[I].Data;
385 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000386 return false;
387 }
Mike Stump11289f42009-09-09 15:08:12 +0000388
Douglas Gregora2f49452010-03-16 19:09:18 +0000389 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000390 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000393 virtual void ReadCounter(unsigned Value) {
394 Counter = Value;
395 }
396};
397
Douglas Gregor33cdd812010-02-18 18:08:43 +0000398class StoredDiagnosticClient : public DiagnosticClient {
399 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
400
401public:
402 explicit StoredDiagnosticClient(
403 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
404 : StoredDiags(StoredDiags) { }
405
406 virtual void HandleDiagnostic(Diagnostic::Level Level,
407 const DiagnosticInfo &Info);
408};
409
410/// \brief RAII object that optionally captures diagnostics, if
411/// there is no diagnostic client to capture them already.
412class CaptureDroppedDiagnostics {
413 Diagnostic &Diags;
414 StoredDiagnosticClient Client;
415 DiagnosticClient *PreviousClient;
416
417public:
418 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
419 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000420 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000421 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000422 if (RequestCapture || Diags.getClient() == 0) {
423 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000424 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000425 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000426 }
427
428 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000429 if (Diags.getClient() == &Client) {
430 Diags.takeClient();
431 Diags.setClient(PreviousClient);
432 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000433 }
434};
435
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000436} // anonymous namespace
437
Douglas Gregor33cdd812010-02-18 18:08:43 +0000438void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
439 const DiagnosticInfo &Info) {
440 StoredDiags.push_back(StoredDiagnostic(Level, Info));
441}
442
Steve Naroffc0683b92009-09-03 18:19:54 +0000443const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000444 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000445}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000446
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000447const std::string &ASTUnit::getASTFileName() {
448 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000449 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000450}
451
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000452llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
453 std::string *ErrorStr,
454 int64_t FileSize,
455 struct stat *FileInfo) {
456 return FileMgr->getBufferForFile(Filename, FileSystemOpts,
457 ErrorStr, FileSize, FileInfo);
458}
459
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000460ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000461 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000462 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000463 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000464 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000465 unsigned NumRemappedFiles,
466 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000467 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
468
Douglas Gregor7f95d262010-04-05 23:52:57 +0000469 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000470 // No diagnostics engine was provided, so create our own diagnostics object
471 // with the default options.
472 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000473 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000474 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000475
476 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000477 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000478 AST->Diagnostics = Diags;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000479 AST->FileSystemOpts = FileSystemOpts;
Douglas Gregord03e8232010-04-05 21:10:19 +0000480 AST->FileMgr.reset(new FileManager);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000481 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
482 AST->getFileManager(),
483 AST->getFileSystemOpts()));
484 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
485 AST->getFileSystemOpts()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000486
Douglas Gregor33cdd812010-02-18 18:08:43 +0000487 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000488 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000489 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000490
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000491 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
492 // Create the file entry for the file that we're mapping from.
493 const FileEntry *FromFile
494 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
495 RemappedFiles[I].second->getBufferSize(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000496 0,
497 AST->getFileSystemOpts());
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000498 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000499 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000500 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000501 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000502 continue;
503 }
504
505 // Override the contents of the "from" file with the contents of
506 // the "to" file.
507 AST->getSourceManager().overrideFileContents(FromFile,
508 RemappedFiles[I].second);
509 }
510
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000511 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000512
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 LangOptions LangInfo;
514 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
515 std::string TargetTriple;
516 std::string Predefines;
517 unsigned Counter;
518
Sebastian Redl2c499f62010-08-18 23:56:43 +0000519 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520
Sebastian Redl2c499f62010-08-18 23:56:43 +0000521 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000522 AST->getFileSystemOpts(), AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000523 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000524 Predefines, Counter));
525
Sebastian Redl009e7f22010-10-05 16:15:19 +0000526 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000527 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000528 break;
Mike Stump11289f42009-09-09 15:08:12 +0000529
Sebastian Redl2c499f62010-08-18 23:56:43 +0000530 case ASTReader::Failure:
531 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000532 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000533 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000534 }
Mike Stump11289f42009-09-09 15:08:12 +0000535
Daniel Dunbara8a50932009-12-02 08:44:16 +0000536 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
537
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000538 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000539
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000540 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000541 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000542 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000543 TargetOptions TargetOpts;
544 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000545 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000546 TargetOpts.CPU = "";
547 TargetOpts.Features.clear();
548 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000549 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
550 TargetOpts));
551 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
552 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000553 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000554 Preprocessor &PP = *AST->PP.get();
555
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000556 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000557 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000558 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000559
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000560 // Create and initialize the ASTContext.
561
562 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000563 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000564 *AST->Target.get(),
565 PP.getIdentifierTable(),
566 PP.getSelectorTable(),
567 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000568 /* size_reserve = */0));
569 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000570
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000571 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Sebastian Redl2c499f62010-08-18 23:56:43 +0000573 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000574 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000575 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000576 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000577 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000578 Context.setExternalSource(Source);
579
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000580 // Create an AST consumer, even though it isn't used.
581 AST->Consumer.reset(new ASTConsumer);
582
Sebastian Redl2c499f62010-08-18 23:56:43 +0000583 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000584 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
585 AST->TheSema->Initialize();
586 ReaderPtr->InitializeSema(*AST->TheSema);
587
Mike Stump11289f42009-09-09 15:08:12 +0000588 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000589}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000590
591namespace {
592
Daniel Dunbar644dca02009-12-04 08:17:33 +0000593class TopLevelDeclTrackerConsumer : public ASTConsumer {
594 ASTUnit &Unit;
595
596public:
597 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
598
599 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000600 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
601 Decl *D = *it;
602 // FIXME: Currently ObjC method declarations are incorrectly being
603 // reported as top-level declarations, even though their DeclContext
604 // is the containing ObjC @interface/@implementation. This is a
605 // fundamental problem in the parser right now.
606 if (isa<ObjCMethodDecl>(D))
607 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000608 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000609 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000610 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000611
612 // We're not interested in "interesting" decls.
613 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000614};
615
616class TopLevelDeclTrackerAction : public ASTFrontendAction {
617public:
618 ASTUnit &Unit;
619
Daniel Dunbar764c0822009-12-01 09:51:01 +0000620 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
621 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000622 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000623 }
624
625public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000626 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
627
Daniel Dunbar764c0822009-12-01 09:51:01 +0000628 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000629 virtual bool usesCompleteTranslationUnit() {
630 return Unit.isCompleteTranslationUnit();
631 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000632};
633
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000634class PrecompilePreambleConsumer : public PCHGenerator {
635 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000636 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000637
638public:
639 PrecompilePreambleConsumer(ASTUnit &Unit,
640 const Preprocessor &PP, bool Chaining,
641 const char *isysroot, llvm::raw_ostream *Out)
642 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
643
Douglas Gregore9db88f2010-08-03 19:06:41 +0000644 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000645 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
646 Decl *D = *it;
647 // FIXME: Currently ObjC method declarations are incorrectly being
648 // reported as top-level declarations, even though their DeclContext
649 // is the containing ObjC @interface/@implementation. This is a
650 // fundamental problem in the parser right now.
651 if (isa<ObjCMethodDecl>(D))
652 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000653 TopLevelDecls.push_back(D);
654 }
655 }
656
657 virtual void HandleTranslationUnit(ASTContext &Ctx) {
658 PCHGenerator::HandleTranslationUnit(Ctx);
659 if (!Unit.getDiagnostics().hasErrorOccurred()) {
660 // Translate the top-level declarations we captured during
661 // parsing into declaration IDs in the precompiled
662 // preamble. This will allow us to deserialize those top-level
663 // declarations when requested.
664 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
665 Unit.addTopLevelDeclFromPreamble(
666 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000667 }
668 }
669};
670
671class PrecompilePreambleAction : public ASTFrontendAction {
672 ASTUnit &Unit;
673
674public:
675 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
676
677 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
678 llvm::StringRef InFile) {
679 std::string Sysroot;
680 llvm::raw_ostream *OS = 0;
681 bool Chaining;
682 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
683 OS, Chaining))
684 return 0;
685
686 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
687 Sysroot.c_str() : 0;
688 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
689 isysroot, OS);
690 }
691
692 virtual bool hasCodeCompletionSupport() const { return false; }
693 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000694 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000695};
696
Daniel Dunbar764c0822009-12-01 09:51:01 +0000697}
698
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000699/// Parse the source file into a translation unit using the given compiler
700/// invocation, replacing the current translation unit.
701///
702/// \returns True if a failure occurred that causes the ASTUnit not to
703/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000704bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000705 delete SavedMainFileBuffer;
706 SavedMainFileBuffer = 0;
707
Douglas Gregora0734c52010-08-19 01:33:06 +0000708 if (!Invocation.get()) {
709 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000710 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000711 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000712
Daniel Dunbar764c0822009-12-01 09:51:01 +0000713 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000714 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000715 Clang.setInvocation(Invocation.take());
716 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
717
Douglas Gregor8e984da2010-08-04 16:47:14 +0000718 // Set up diagnostics, capturing any diagnostics that would
719 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000720 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000721 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
722 getDiagnostics(),
723 StoredDiagnostics);
Douglas Gregord03e8232010-04-05 21:10:19 +0000724
Daniel Dunbar764c0822009-12-01 09:51:01 +0000725 // Create the target instance.
726 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
727 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000728 if (!Clang.hasTarget()) {
729 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000730 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000731 }
732
Daniel Dunbar764c0822009-12-01 09:51:01 +0000733 // Inform the target of the language options.
734 //
735 // FIXME: We shouldn't need to do this, the target should be immutable once
736 // created. This complexity should be lifted elsewhere.
737 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000738
Daniel Dunbar764c0822009-12-01 09:51:01 +0000739 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
740 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000741 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000742 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000743 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
744 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000745
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000746 // Configure the various subsystems.
747 // FIXME: Should we retain the previous file manager?
748 FileMgr.reset(new FileManager);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000749 FileSystemOpts = Clang.getFileSystemOpts();
750 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr, FileSystemOpts));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000751 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000752 Ctx.reset();
753 PP.reset();
754
755 // Clear out old caches and data.
756 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000757 CleanTemporaryFiles();
758 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000759
Douglas Gregor7b02b582010-08-20 00:02:33 +0000760 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000761 StoredDiagnostics.erase(
762 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
763 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000764 TopLevelDeclsInPreamble.clear();
765 }
766
Daniel Dunbar764c0822009-12-01 09:51:01 +0000767 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000768 Clang.setFileManager(&getFileManager());
769
Daniel Dunbar764c0822009-12-01 09:51:01 +0000770 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000771 Clang.setSourceManager(&getSourceManager());
772
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000773 // If the main file has been overridden due to the use of a preamble,
774 // make that override happen and introduce the preamble.
775 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000776 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000777 if (OverrideMainBuffer) {
778 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
779 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
780 PreprocessorOpts.PrecompiledPreambleBytes.second
781 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000782 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000783 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000784 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000785
Douglas Gregord9a30af2010-08-02 20:51:39 +0000786 // The stored diagnostic has the old source manager in it; update
787 // the locations to refer into the new source manager. Since we've
788 // been careful to make sure that the source manager's state
789 // before and after are identical, so that we can reuse the source
790 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000791 for (unsigned I = NumStoredDiagnosticsFromDriver,
792 N = StoredDiagnostics.size();
793 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000794 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
795 getSourceManager());
796 StoredDiagnostics[I].setLocation(Loc);
797 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000798
799 // Keep track of the override buffer;
800 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000801 } else {
802 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
803 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000804 }
805
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000806 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
807 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000808 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000809 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000810 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000811
Daniel Dunbar644dca02009-12-04 08:17:33 +0000812 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000813
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000814 // Steal the created target, context, and preprocessor, and take back the
815 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000816 TheSema.reset(Clang.takeSema());
817 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000818 Ctx.reset(Clang.takeASTContext());
819 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000820 Clang.takeSourceManager();
821 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000822 Target.reset(Clang.takeTarget());
823
Daniel Dunbar644dca02009-12-04 08:17:33 +0000824 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000825
826 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000827 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000828 PreprocessorOpts.eraseRemappedFile(
829 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000830 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
831 }
832
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000833 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000834
835 // If we were asked to cache code-completion results and don't have any
836 // results yet, do so now.
837 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
838 CacheCodeCompletionResults();
Douglas Gregorbb6a8812010-10-08 04:03:57 +0000839
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000840 return false;
841
Daniel Dunbar764c0822009-12-01 09:51:01 +0000842error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000843 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000844 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000845 PreprocessorOpts.eraseRemappedFile(
846 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000847 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000848 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000849 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000850 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000851 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000852
Douglas Gregorefc46952010-10-12 16:25:54 +0000853 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000854 Clang.takeSourceManager();
855 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000856 Invocation.reset(Clang.takeInvocation());
857 return true;
858}
859
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000860/// \brief Simple function to retrieve a path for a preamble precompiled header.
861static std::string GetPreamblePCHPath() {
862 // FIXME: This is lame; sys::Path should provide this function (in particular,
863 // it should know how to find the temporary files dir).
864 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000865 // FIXME: This is a hack so that we can override the preamble file during
866 // crash-recovery testing, which is the only case where the preamble files
867 // are not necessarily cleaned up.
868 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
869 if (TmpFile)
870 return TmpFile;
871
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000872 std::string Error;
873 const char *TmpDir = ::getenv("TMPDIR");
874 if (!TmpDir)
875 TmpDir = ::getenv("TEMP");
876 if (!TmpDir)
877 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000878#ifdef LLVM_ON_WIN32
879 if (!TmpDir)
880 TmpDir = ::getenv("USERPROFILE");
881#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000882 if (!TmpDir)
883 TmpDir = "/tmp";
884 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000885 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000886 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000887 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000888 if (P.createTemporaryFileOnDisk())
889 return std::string();
890
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000891 return P.str();
892}
893
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000894/// \brief Compute the preamble for the main file, providing the source buffer
895/// that corresponds to the main file along with a pair (bytes, start-of-line)
896/// that describes the preamble.
897std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000898ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
899 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000900 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000901 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000902 = Invocation.getPreprocessorOpts();
903 CreatedBuffer = false;
904
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000905 // Try to determine if the main file has been remapped, either from the
906 // command line (to another file) or directly through the compiler invocation
907 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000908 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000909 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
910 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
911 // Check whether there is a file-file remapping of the main file
912 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000913 M = PreprocessorOpts.remapped_file_begin(),
914 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000915 M != E;
916 ++M) {
917 llvm::sys::PathWithStatus MPath(M->first);
918 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
919 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
920 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000921 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000922 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000923 CreatedBuffer = false;
924 }
925
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000926 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000927 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000928 return std::make_pair((llvm::MemoryBuffer*)0,
929 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000930 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000931 }
932 }
933 }
934
935 // Check whether there is a file-buffer remapping. It supercedes the
936 // file-file remapping.
937 for (PreprocessorOptions::remapped_file_buffer_iterator
938 M = PreprocessorOpts.remapped_file_buffer_begin(),
939 E = PreprocessorOpts.remapped_file_buffer_end();
940 M != E;
941 ++M) {
942 llvm::sys::PathWithStatus MPath(M->first);
943 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
944 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
945 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000946 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000947 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000948 CreatedBuffer = false;
949 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000950
Douglas Gregor4dde7492010-07-23 23:58:40 +0000951 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000952 }
953 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000954 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000955 }
956
957 // If the main source file was not remapped, load it now.
958 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000959 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000960 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000961 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000962
963 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000964 }
965
Douglas Gregor028d3e42010-08-09 20:45:32 +0000966 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000967}
968
Douglas Gregor6481ef12010-07-24 00:38:13 +0000969static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
970 bool DeleteOld,
971 unsigned NewSize,
972 llvm::StringRef NewName) {
973 llvm::MemoryBuffer *Result
974 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
975 memcpy(const_cast<char*>(Result->getBufferStart()),
976 Old->getBufferStart(), Old->getBufferSize());
977 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000978 ' ', NewSize - Old->getBufferSize() - 1);
979 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000980
981 if (DeleteOld)
982 delete Old;
983
984 return Result;
985}
986
Douglas Gregor4dde7492010-07-23 23:58:40 +0000987/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
988/// the source file.
989///
990/// This routine will compute the preamble of the main source file. If a
991/// non-trivial preamble is found, it will precompile that preamble into a
992/// precompiled header so that the precompiled preamble can be used to reduce
993/// reparsing time. If a precompiled preamble has already been constructed,
994/// this routine will determine if it is still valid and, if so, avoid
995/// rebuilding the precompiled preamble.
996///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000997/// \param AllowRebuild When true (the default), this routine is
998/// allowed to rebuild the precompiled preamble if it is found to be
999/// out-of-date.
1000///
1001/// \param MaxLines When non-zero, the maximum number of lines that
1002/// can occur within the preamble.
1003///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001004/// \returns If the precompiled preamble can be used, returns a newly-allocated
1005/// buffer that should be used in place of the main file when doing so.
1006/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001007llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001008 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001009 bool AllowRebuild,
1010 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001011 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1012 PreprocessorOptions &PreprocessorOpts
1013 = PreambleInvocation.getPreprocessorOpts();
1014
1015 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001016 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001017 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001018
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001019 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001020 // We couldn't find a preamble in the main source. Clear out the current
1021 // preamble, if we have one. It's obviously no good any more.
1022 Preamble.clear();
1023 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001024 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001025 PreambleFile.clear();
1026 }
1027 if (CreatedPreambleBuffer)
1028 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001029
1030 // The next time we actually see a preamble, precompile it.
1031 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001032 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001033 }
1034
1035 if (!Preamble.empty()) {
1036 // We've previously computed a preamble. Check whether we have the same
1037 // preamble now that we did before, and that there's enough space in
1038 // the main-file buffer within the precompiled preamble to fit the
1039 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001040 if (Preamble.size() == NewPreamble.second.first &&
1041 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001042 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001043 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001044 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001045 // The preamble has not changed. We may be able to re-use the precompiled
1046 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001047
Douglas Gregor0e119552010-07-31 00:40:00 +00001048 // Check that none of the files used by the preamble have changed.
1049 bool AnyFileChanged = false;
1050
1051 // First, make a record of those files that have been overridden via
1052 // remapping or unsaved_files.
1053 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1054 for (PreprocessorOptions::remapped_file_iterator
1055 R = PreprocessorOpts.remapped_file_begin(),
1056 REnd = PreprocessorOpts.remapped_file_end();
1057 !AnyFileChanged && R != REnd;
1058 ++R) {
1059 struct stat StatBuf;
1060 if (stat(R->second.c_str(), &StatBuf)) {
1061 // If we can't stat the file we're remapping to, assume that something
1062 // horrible happened.
1063 AnyFileChanged = true;
1064 break;
1065 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001066
Douglas Gregor0e119552010-07-31 00:40:00 +00001067 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1068 StatBuf.st_mtime);
1069 }
1070 for (PreprocessorOptions::remapped_file_buffer_iterator
1071 R = PreprocessorOpts.remapped_file_buffer_begin(),
1072 REnd = PreprocessorOpts.remapped_file_buffer_end();
1073 !AnyFileChanged && R != REnd;
1074 ++R) {
1075 // FIXME: Should we actually compare the contents of file->buffer
1076 // remappings?
1077 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1078 0);
1079 }
1080
1081 // Check whether anything has changed.
1082 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1083 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1084 !AnyFileChanged && F != FEnd;
1085 ++F) {
1086 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1087 = OverriddenFiles.find(F->first());
1088 if (Overridden != OverriddenFiles.end()) {
1089 // This file was remapped; check whether the newly-mapped file
1090 // matches up with the previous mapping.
1091 if (Overridden->second != F->second)
1092 AnyFileChanged = true;
1093 continue;
1094 }
1095
1096 // The file was not remapped; check whether it has changed on disk.
1097 struct stat StatBuf;
1098 if (stat(F->first(), &StatBuf)) {
1099 // If we can't stat the file, assume that something horrible happened.
1100 AnyFileChanged = true;
1101 } else if (StatBuf.st_size != F->second.first ||
1102 StatBuf.st_mtime != F->second.second)
1103 AnyFileChanged = true;
1104 }
1105
1106 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001107 // Okay! We can re-use the precompiled preamble.
1108
1109 // Set the state of the diagnostic object to mimic its state
1110 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001111 // FIXME: This won't catch any #pragma push warning changes that
1112 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001113 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001114 ProcessWarningOptions(getDiagnostics(),
1115 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001116 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1117 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1118 StoredDiagnostics.erase(
1119 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1120 StoredDiagnostics.end());
1121
1122 // Create a version of the main file buffer that is padded to
1123 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001124 return CreatePaddedMainFileBuffer(NewPreamble.first,
1125 CreatedPreambleBuffer,
1126 PreambleReservedSize,
1127 FrontendOpts.Inputs[0].second);
1128 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001129 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001130
1131 // If we aren't allowed to rebuild the precompiled preamble, just
1132 // return now.
1133 if (!AllowRebuild)
1134 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001135
Douglas Gregor4dde7492010-07-23 23:58:40 +00001136 // We can't reuse the previously-computed preamble. Build a new one.
1137 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001138 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001139 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001140 } else if (!AllowRebuild) {
1141 // We aren't allowed to rebuild the precompiled preamble; just
1142 // return now.
1143 return 0;
1144 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001145
1146 // If the preamble rebuild counter > 1, it's because we previously
1147 // failed to build a preamble and we're not yet ready to try
1148 // again. Decrement the counter and return a failure.
1149 if (PreambleRebuildCounter > 1) {
1150 --PreambleRebuildCounter;
1151 return 0;
1152 }
1153
Douglas Gregore10f0e52010-09-11 17:56:52 +00001154 // Create a temporary file for the precompiled preamble. In rare
1155 // circumstances, this can fail.
1156 std::string PreamblePCHPath = GetPreamblePCHPath();
1157 if (PreamblePCHPath.empty()) {
1158 // Try again next time.
1159 PreambleRebuildCounter = 1;
1160 return 0;
1161 }
1162
Douglas Gregor4dde7492010-07-23 23:58:40 +00001163 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001164 SimpleTimer PreambleTimer(WantTiming);
1165 if (WantTiming)
1166 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001167
1168 // Create a new buffer that stores the preamble. The buffer also contains
1169 // extra space for the original contents of the file (which will be present
1170 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001171 // grows.
1172 PreambleReservedSize = NewPreamble.first->getBufferSize();
1173 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001174 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001175 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001176 PreambleReservedSize *= 2;
1177
Douglas Gregord9a30af2010-08-02 20:51:39 +00001178 // Save the preamble text for later; we'll need to compare against it for
1179 // subsequent reparses.
1180 Preamble.assign(NewPreamble.first->getBufferStart(),
1181 NewPreamble.first->getBufferStart()
1182 + NewPreamble.second.first);
1183 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1184
Douglas Gregora0734c52010-08-19 01:33:06 +00001185 delete PreambleBuffer;
1186 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001187 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001188 FrontendOpts.Inputs[0].second);
1189 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001190 NewPreamble.first->getBufferStart(), Preamble.size());
1191 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001192 ' ', PreambleReservedSize - Preamble.size() - 1);
1193 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001194
1195 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001196 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001197 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1198
1199 // Tell the compiler invocation to generate a temporary precompiled header.
1200 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001201 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001202 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001203 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001204 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1205 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206
1207 // Create the compiler instance to use for building the precompiled preamble.
1208 CompilerInstance Clang;
1209 Clang.setInvocation(&PreambleInvocation);
1210 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1211
Douglas Gregor8e984da2010-08-04 16:47:14 +00001212 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001213 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001214 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1215 getDiagnostics(),
1216 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001217
1218 // Create the target instance.
1219 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1220 Clang.getTargetOpts()));
1221 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001222 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1223 Preamble.clear();
1224 if (CreatedPreambleBuffer)
1225 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001226 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001227 PreprocessorOpts.eraseRemappedFile(
1228 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001229 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001230 }
1231
1232 // Inform the target of the language options.
1233 //
1234 // FIXME: We shouldn't need to do this, the target should be immutable once
1235 // created. This complexity should be lifted elsewhere.
1236 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1237
1238 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1239 "Invocation must have exactly one source file!");
1240 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1241 "FIXME: AST inputs not yet supported here!");
1242 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1243 "IR inputs not support here!");
1244
1245 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001246 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001247 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001248 StoredDiagnostics.erase(
1249 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1250 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001251 TopLevelDecls.clear();
1252 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001253
1254 // Create a file manager object to provide access to and cache the filesystem.
1255 Clang.setFileManager(new FileManager);
1256
1257 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001258 Clang.setSourceManager(new SourceManager(getDiagnostics(),
1259 Clang.getFileManager(),
1260 Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001261
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001262 llvm::OwningPtr<PrecompilePreambleAction> Act;
1263 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001264 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1265 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001266 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001267 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1268 Preamble.clear();
1269 if (CreatedPreambleBuffer)
1270 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001271 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001272 PreprocessorOpts.eraseRemappedFile(
1273 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001274 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001275 }
1276
1277 Act->Execute();
1278 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001279 Clang.takeInvocation();
1280
Douglas Gregore9db88f2010-08-03 19:06:41 +00001281 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001282 // There were errors parsing the preamble, so no precompiled header was
1283 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001284 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001285 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1286 Preamble.clear();
1287 if (CreatedPreambleBuffer)
1288 delete NewPreamble.first;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001289 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001290 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001291 PreprocessorOpts.eraseRemappedFile(
1292 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001293 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001294 }
1295
1296 // Keep track of the preamble we precompiled.
1297 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001298 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1299 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001300
1301 // Keep track of all of the files that the source manager knows about,
1302 // so we can verify whether they have changed or not.
1303 FilesInPreamble.clear();
1304 SourceManager &SourceMgr = Clang.getSourceManager();
1305 const llvm::MemoryBuffer *MainFileBuffer
1306 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1307 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1308 FEnd = SourceMgr.fileinfo_end();
1309 F != FEnd;
1310 ++F) {
1311 const FileEntry *File = F->second->Entry;
1312 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1313 continue;
1314
1315 FilesInPreamble[File->getName()]
1316 = std::make_pair(F->second->getSize(), File->getModificationTime());
1317 }
1318
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001319 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001320 PreprocessorOpts.eraseRemappedFile(
1321 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001322 return CreatePaddedMainFileBuffer(NewPreamble.first,
1323 CreatedPreambleBuffer,
1324 PreambleReservedSize,
1325 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001326}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001327
Douglas Gregore9db88f2010-08-03 19:06:41 +00001328void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1329 std::vector<Decl *> Resolved;
1330 Resolved.reserve(TopLevelDeclsInPreamble.size());
1331 ExternalASTSource &Source = *getASTContext().getExternalSource();
1332 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1333 // Resolve the declaration ID to an actual declaration, possibly
1334 // deserializing the declaration in the process.
1335 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1336 if (D)
1337 Resolved.push_back(D);
1338 }
1339 TopLevelDeclsInPreamble.clear();
1340 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1341}
1342
1343unsigned ASTUnit::getMaxPCHLevel() const {
1344 if (!getOnlyLocalDecls())
1345 return Decl::MaxPCHLevel;
1346
Sebastian Redl009e7f22010-10-05 16:15:19 +00001347 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001348}
1349
Douglas Gregor16896c42010-10-28 15:44:59 +00001350llvm::StringRef ASTUnit::getMainFileName() const {
1351 return Invocation->getFrontendOpts().Inputs[0].second;
1352}
1353
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001354bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1355 if (!Invocation)
1356 return true;
1357
1358 // We'll manage file buffers ourselves.
1359 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1360 Invocation->getFrontendOpts().DisableFree = false;
1361
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001362 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001363 if (PrecompilePreamble) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001364 PreambleRebuildCounter = 1;
1365 OverrideMainBuffer
1366 = getMainBufferWithPrecompiledPreamble(*Invocation);
1367 }
1368
Douglas Gregor16896c42010-10-28 15:44:59 +00001369 SimpleTimer ParsingTimer(WantTiming);
1370 if (WantTiming)
1371 ParsingTimer.setOutput( "Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001372
Douglas Gregor16896c42010-10-28 15:44:59 +00001373 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001374}
1375
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001376ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1377 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1378 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001379 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001380 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001381 bool CompleteTranslationUnit,
1382 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001383 if (!Diags.getPtr()) {
1384 // No diagnostics engine was provided, so create our own diagnostics object
1385 // with the default options.
1386 DiagnosticOptions DiagOpts;
1387 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1388 }
1389
1390 // Create the AST unit.
1391 llvm::OwningPtr<ASTUnit> AST;
1392 AST.reset(new ASTUnit(false));
1393 AST->Diagnostics = Diags;
1394 AST->CaptureDiagnostics = CaptureDiagnostics;
1395 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001396 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001397 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001398 AST->Invocation.reset(CI);
1399
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001400 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001401}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001402
1403ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1404 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001405 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001406 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001407 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001408 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001409 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001410 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001411 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001412 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001413 bool CacheCodeCompletionResults,
1414 bool CXXPrecompilePreamble,
1415 bool CXXChainedPCH) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001416 bool CreatedDiagnosticsObject = false;
1417
Douglas Gregor7f95d262010-04-05 23:52:57 +00001418 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001419 // No diagnostics engine was provided, so create our own diagnostics object
1420 // with the default options.
1421 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001422 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001423 CreatedDiagnosticsObject = true;
Douglas Gregord03e8232010-04-05 21:10:19 +00001424 }
1425
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001426 llvm::SmallVector<const char *, 16> Args;
1427 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1428 Args.insert(Args.end(), ArgBegin, ArgEnd);
1429
1430 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1431 // also want to force it to use clang.
1432 Args.push_back("-fsyntax-only");
1433
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001434 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1435
1436 llvm::OwningPtr<CompilerInvocation> CI;
1437 {
1438 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1439 *Diags,
1440 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001441
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001442 // FIXME: We shouldn't have to pass in the path info.
1443 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1444 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001445
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001446 // Don't check that inputs exist, they have been remapped.
1447 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001448
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001449 llvm::OwningPtr<driver::Compilation> C(
1450 TheDriver.BuildCompilation(Args.size(), Args.data()));
1451
1452 // We expect to get back exactly one command job, if we didn't something
1453 // failed.
1454 const driver::JobList &Jobs = C->getJobs();
1455 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1456 llvm::SmallString<256> Msg;
1457 llvm::raw_svector_ostream OS(Msg);
1458 C->PrintJob(OS, C->getJobs(), "; ", true);
1459 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1460 return 0;
1461 }
1462
1463 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1464 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1465 Diags->Report(diag::err_fe_expected_clang_command);
1466 return 0;
1467 }
1468
1469 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1470 CI.reset(new CompilerInvocation);
1471 CompilerInvocation::CreateFromArgs(*CI,
1472 const_cast<const char **>(CCArgs.data()),
1473 const_cast<const char **>(CCArgs.data()) +
1474 CCArgs.size(),
1475 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001476 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001477
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001478 // Override any files that need remapping
1479 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001480 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001481 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001482
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001483 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001484 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001485
Douglas Gregorf5a18542010-10-27 17:24:53 +00001486 // Check whether we should precompile the preamble and/or use chained PCH.
1487 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1488 if (CI->getLangOpts().CPlusPlus) {
1489 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1490
1491 if (PrecompilePreamble && !CXXChainedPCH &&
1492 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1493 PrecompilePreamble = false;
1494 }
1495
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001496 // Create the AST unit.
1497 llvm::OwningPtr<ASTUnit> AST;
1498 AST.reset(new ASTUnit(false));
1499 AST->Diagnostics = Diags;
1500 AST->CaptureDiagnostics = CaptureDiagnostics;
1501 AST->OnlyLocalDecls = OnlyLocalDecls;
1502 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1503 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1504 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1505 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1506 AST->StoredDiagnostics.swap(StoredDiagnostics);
1507 AST->Invocation.reset(CI.take());
1508 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001509}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001510
1511bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1512 if (!Invocation.get())
1513 return true;
1514
Douglas Gregor16896c42010-10-28 15:44:59 +00001515 SimpleTimer ParsingTimer(WantTiming);
1516 if (WantTiming)
1517 ParsingTimer.setOutput( "Reparsing " + getMainFileName());
1518
Douglas Gregor0e119552010-07-31 00:40:00 +00001519 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001520 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1521 for (PreprocessorOptions::remapped_file_buffer_iterator
1522 R = PPOpts.remapped_file_buffer_begin(),
1523 REnd = PPOpts.remapped_file_buffer_end();
1524 R != REnd;
1525 ++R) {
1526 delete R->second;
1527 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001528 Invocation->getPreprocessorOpts().clearRemappedFiles();
1529 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1530 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1531 RemappedFiles[I].second);
1532
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001533 // If we have a preamble file lying around, or if we might try to
1534 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001535 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001536 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001537 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001538
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001539 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001540 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001541 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001542 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1543 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001544
Douglas Gregor4dde7492010-07-23 23:58:40 +00001545 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001546 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001547
1548 if (ShouldCacheCodeCompletionResults) {
1549 if (CacheCodeCompletionCoolDown > 0)
1550 --CacheCodeCompletionCoolDown;
1551 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1552 CacheCodeCompletionResults();
1553 }
1554
Douglas Gregor4dde7492010-07-23 23:58:40 +00001555 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001556}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001557
Douglas Gregorb14904c2010-08-13 22:48:40 +00001558//----------------------------------------------------------------------------//
1559// Code completion
1560//----------------------------------------------------------------------------//
1561
1562namespace {
1563 /// \brief Code completion consumer that combines the cached code-completion
1564 /// results from an ASTUnit with the code-completion results provided to it,
1565 /// then passes the result on to
1566 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1567 unsigned NormalContexts;
1568 ASTUnit &AST;
1569 CodeCompleteConsumer &Next;
1570
1571 public:
1572 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001573 bool IncludeMacros, bool IncludeCodePatterns,
1574 bool IncludeGlobals)
1575 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001576 Next.isOutputBinary()), AST(AST), Next(Next)
1577 {
1578 // Compute the set of contexts in which we will look when we don't have
1579 // any information about the specific context.
1580 NormalContexts
1581 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1582 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1583 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1584 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1585 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1586 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1587 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1588 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001589 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001590 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1591 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001592
Douglas Gregorb14904c2010-08-13 22:48:40 +00001593 if (AST.getASTContext().getLangOptions().CPlusPlus)
1594 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1595 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1596 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1597 }
1598
1599 virtual void ProcessCodeCompleteResults(Sema &S,
1600 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001601 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001602 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001603
1604 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1605 OverloadCandidate *Candidates,
1606 unsigned NumCandidates) {
1607 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1608 }
1609 };
1610}
Douglas Gregord46cf182010-08-16 20:01:48 +00001611
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001612/// \brief Helper function that computes which global names are hidden by the
1613/// local code-completion results.
1614void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall276321a2010-08-25 06:19:51 +00001615 CodeCompletionResult *Results,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001616 unsigned NumResults,
1617 ASTContext &Ctx,
1618 llvm::StringSet<> &HiddenNames) {
1619 bool OnlyTagNames = false;
1620 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001621 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001622 case CodeCompletionContext::CCC_TopLevel:
1623 case CodeCompletionContext::CCC_ObjCInterface:
1624 case CodeCompletionContext::CCC_ObjCImplementation:
1625 case CodeCompletionContext::CCC_ObjCIvarList:
1626 case CodeCompletionContext::CCC_ClassStructUnion:
1627 case CodeCompletionContext::CCC_Statement:
1628 case CodeCompletionContext::CCC_Expression:
1629 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1630 case CodeCompletionContext::CCC_MemberAccess:
1631 case CodeCompletionContext::CCC_Namespace:
1632 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001633 case CodeCompletionContext::CCC_Name:
1634 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001635 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001636 break;
1637
1638 case CodeCompletionContext::CCC_EnumTag:
1639 case CodeCompletionContext::CCC_UnionTag:
1640 case CodeCompletionContext::CCC_ClassOrStructTag:
1641 OnlyTagNames = true;
1642 break;
1643
1644 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001645 case CodeCompletionContext::CCC_MacroName:
1646 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001647 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001648 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001649 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001650 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001651 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001652 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001653 // We're looking for nothing, or we're looking for names that cannot
1654 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001655 return;
1656 }
1657
John McCall276321a2010-08-25 06:19:51 +00001658 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001659 for (unsigned I = 0; I != NumResults; ++I) {
1660 if (Results[I].Kind != Result::RK_Declaration)
1661 continue;
1662
1663 unsigned IDNS
1664 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1665
1666 bool Hiding = false;
1667 if (OnlyTagNames)
1668 Hiding = (IDNS & Decl::IDNS_Tag);
1669 else {
1670 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001671 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1672 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001673 if (Ctx.getLangOptions().CPlusPlus)
1674 HiddenIDNS |= Decl::IDNS_Tag;
1675 Hiding = (IDNS & HiddenIDNS);
1676 }
1677
1678 if (!Hiding)
1679 continue;
1680
1681 DeclarationName Name = Results[I].Declaration->getDeclName();
1682 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1683 HiddenNames.insert(Identifier->getName());
1684 else
1685 HiddenNames.insert(Name.getAsString());
1686 }
1687}
1688
1689
Douglas Gregord46cf182010-08-16 20:01:48 +00001690void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1691 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001692 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001693 unsigned NumResults) {
1694 // Merge the results we were given with the results we cached.
1695 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001696 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001697 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001698 : (1 << (Context.getKind() - 1)));
1699
1700 // Contains the set of names that are hidden by "local" completion results.
1701 llvm::StringSet<> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001702 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001703 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001704 llvm::SmallVector<Result, 8> AllResults;
1705 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001706 C = AST.cached_completion_begin(),
1707 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001708 C != CEnd; ++C) {
1709 // If the context we are in matches any of the contexts we are
1710 // interested in, we'll add this result.
1711 if ((C->ShowInContexts & InContexts) == 0)
1712 continue;
1713
1714 // If we haven't added any results previously, do so now.
1715 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001716 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1717 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001718 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1719 AddedResult = true;
1720 }
1721
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001722 // Determine whether this global completion result is hidden by a local
1723 // completion result. If so, skip it.
1724 if (C->Kind != CXCursor_MacroDefinition &&
1725 HiddenNames.count(C->Completion->getTypedText()))
1726 continue;
1727
Douglas Gregord46cf182010-08-16 20:01:48 +00001728 // Adjust priority based on similar type classes.
1729 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001730 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001731 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001732 if (!Context.getPreferredType().isNull()) {
1733 if (C->Kind == CXCursor_MacroDefinition) {
1734 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001735 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001736 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001737 } else if (C->Type) {
1738 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001739 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001740 Context.getPreferredType().getUnqualifiedType());
1741 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1742 if (ExpectedSTC == C->TypeClass) {
1743 // We know this type is similar; check for an exact match.
1744 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001745 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001746 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001747 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001748 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1749 Priority /= CCF_ExactTypeMatch;
1750 else
1751 Priority /= CCF_SimilarTypeMatch;
1752 }
1753 }
1754 }
1755
Douglas Gregor12785102010-08-24 20:21:13 +00001756 // Adjust the completion string, if required.
1757 if (C->Kind == CXCursor_MacroDefinition &&
1758 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1759 // Create a new code-completion string that just contains the
1760 // macro name, without its arguments.
1761 Completion = new CodeCompletionString;
1762 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1763 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001764 CursorKind = CXCursor_NotImplemented;
1765 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001766 }
1767
Douglas Gregor8850aa32010-08-25 18:03:13 +00001768 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001769 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001770 }
1771
1772 // If we did not add any cached completion results, just forward the
1773 // results we were given to the next consumer.
1774 if (!AddedResult) {
1775 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1776 return;
1777 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001778
Douglas Gregord46cf182010-08-16 20:01:48 +00001779 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1780 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001781
1782 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1783 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001784}
1785
1786
1787
Douglas Gregor8e984da2010-08-04 16:47:14 +00001788void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1789 RemappedFile *RemappedFiles,
1790 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001791 bool IncludeMacros,
1792 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001793 CodeCompleteConsumer &Consumer,
1794 Diagnostic &Diag, LangOptions &LangOpts,
1795 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001796 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1797 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001798 if (!Invocation.get())
1799 return;
1800
Douglas Gregor16896c42010-10-28 15:44:59 +00001801 SimpleTimer CompletionTimer(WantTiming);
1802 if (WantTiming) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001803 llvm::SmallString<128> TimerName;
1804 llvm::raw_svector_ostream TimerNameOut(TimerName);
1805 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1806 << Column;
Douglas Gregor16896c42010-10-28 15:44:59 +00001807 CompletionTimer.setOutput(TimerNameOut.str());
Douglas Gregor028d3e42010-08-09 20:45:32 +00001808 }
1809
Douglas Gregor8e984da2010-08-04 16:47:14 +00001810 CompilerInvocation CCInvocation(*Invocation);
1811 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1812 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001813
Douglas Gregorb14904c2010-08-13 22:48:40 +00001814 FrontendOpts.ShowMacrosInCodeCompletion
1815 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001816 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001817 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1818 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001819 FrontendOpts.CodeCompletionAt.FileName = File;
1820 FrontendOpts.CodeCompletionAt.Line = Line;
1821 FrontendOpts.CodeCompletionAt.Column = Column;
1822
1823 // Set the language options appropriately.
1824 LangOpts = CCInvocation.getLangOpts();
1825
1826 CompilerInstance Clang;
1827 Clang.setInvocation(&CCInvocation);
1828 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1829
1830 // Set up diagnostics, capturing any diagnostics produced.
1831 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001832 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001833 CaptureDroppedDiagnostics Capture(true,
1834 Clang.getDiagnostics(),
1835 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001836
1837 // Create the target instance.
1838 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1839 Clang.getTargetOpts()));
1840 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001841 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001842 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001843 }
1844
1845 // Inform the target of the language options.
1846 //
1847 // FIXME: We shouldn't need to do this, the target should be immutable once
1848 // created. This complexity should be lifted elsewhere.
1849 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1850
1851 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1852 "Invocation must have exactly one source file!");
1853 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1854 "FIXME: AST inputs not yet supported here!");
1855 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1856 "IR inputs not support here!");
1857
1858
1859 // Use the source and file managers that we were given.
1860 Clang.setFileManager(&FileMgr);
1861 Clang.setSourceManager(&SourceMgr);
1862
1863 // Remap files.
1864 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001865 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001866 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001867 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1868 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001869 OwnedBuffers.push_back(RemappedFiles[I].second);
1870 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001871
Douglas Gregorb14904c2010-08-13 22:48:40 +00001872 // Use the code completion consumer we were given, but adding any cached
1873 // code-completion results.
1874 AugmentedCodeCompleteConsumer
1875 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001876 FrontendOpts.ShowCodePatternsInCodeCompletion,
1877 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001878 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001879
Douglas Gregor028d3e42010-08-09 20:45:32 +00001880 // If we have a precompiled preamble, try to use it. We only allow
1881 // the use of the precompiled preamble if we're if the completion
1882 // point is within the main file, after the end of the precompiled
1883 // preamble.
1884 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1885 if (!PreambleFile.empty()) {
1886 using llvm::sys::FileStatus;
1887 llvm::sys::PathWithStatus CompleteFilePath(File);
1888 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1889 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1890 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1891 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001892 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001893 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1894 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001895 }
1896
1897 // If the main file has been overridden due to the use of a preamble,
1898 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001899 StoredDiagnostics.insert(StoredDiagnostics.end(),
1900 this->StoredDiagnostics.begin(),
1901 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001902 if (OverrideMainBuffer) {
1903 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1904 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1905 PreprocessorOpts.PrecompiledPreambleBytes.second
1906 = PreambleEndsAtStartOfLine;
1907 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1908 PreprocessorOpts.DisablePCHValidation = true;
1909
1910 // The stored diagnostics have the old source manager. Copy them
1911 // to our output set of stored diagnostics, updating the source
1912 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001913 for (unsigned I = NumStoredDiagnosticsFromDriver,
1914 N = this->StoredDiagnostics.size();
1915 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001916 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1917 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1918 StoredDiagnostics[I].setLocation(Loc);
1919 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001920
Douglas Gregorb97b6662010-08-20 00:59:43 +00001921 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001922 } else {
1923 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1924 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001925 }
1926
Douglas Gregor8e984da2010-08-04 16:47:14 +00001927 llvm::OwningPtr<SyntaxOnlyAction> Act;
1928 Act.reset(new SyntaxOnlyAction);
1929 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1930 Clang.getFrontendOpts().Inputs[0].first)) {
1931 Act->Execute();
1932 Act->EndSourceFile();
1933 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001934
Douglas Gregor8e984da2010-08-04 16:47:14 +00001935 // Steal back our resources.
1936 Clang.takeFileManager();
1937 Clang.takeSourceManager();
1938 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001939 Clang.takeCodeCompletionConsumer();
1940}
Douglas Gregore9386682010-08-13 05:36:37 +00001941
1942bool ASTUnit::Save(llvm::StringRef File) {
1943 if (getDiagnostics().hasErrorOccurred())
1944 return true;
1945
1946 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1947 // unconditionally create a stat cache when we parse the file?
1948 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001949 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1950 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001951 if (!ErrorInfo.empty() || Out.has_error())
1952 return true;
1953
1954 std::vector<unsigned char> Buffer;
1955 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001956 ASTWriter Writer(Stream);
1957 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001958
1959 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001960 if (!Buffer.empty())
1961 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001962 Out.close();
1963 return Out.has_error();
1964}