blob: ff05f45b14d6ffc7ba9c8e30ffc9aff99be6b5b0 [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
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000055 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000056 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000057 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000058 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000059 }
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000064 }
65
Douglas Gregor16896c42010-10-28 15:44:59 +000066 ~SimpleTimer() {
67 if (WantTiming) {
68 TimeRecord Elapsed = TimeRecord::getCurrentTime();
69 Elapsed -= Start;
70 llvm::errs() << Output << ':';
71 Elapsed.print(Elapsed, llvm::errs());
72 llvm::errs() << '\n';
73 }
74 }
75 };
76}
77
Douglas Gregorbb420ab2010-08-04 05:53:38 +000078/// \brief After failing to build a precompiled preamble (due to
79/// errors in the source that occurs in the preamble), the number of
80/// reparses during which we'll skip even trying to precompile the
81/// preamble.
82const unsigned DefaultPreambleRebuildInterval = 5;
83
Douglas Gregord03e8232010-04-05 21:10:19 +000084ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000085 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000086 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
87 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000088 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000089 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000090 ShouldCacheCodeCompletionResults(false),
91 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000092 CacheCodeCompletionCoolDown(0),
93 UnsafeToFree(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000094}
Douglas Gregord03e8232010-04-05 21:10:19 +000095
Daniel Dunbar764c0822009-12-01 09:51:01 +000096ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000097 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000098 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000099 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000100 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000101
102 // Free the buffers associated with remapped files. We are required to
103 // perform this operation here because we explicitly request that the
104 // compiler instance *not* free these buffers for each invocation of the
105 // parser.
106 if (Invocation.get()) {
107 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
108 for (PreprocessorOptions::remapped_file_buffer_iterator
109 FB = PPOpts.remapped_file_buffer_begin(),
110 FBEnd = PPOpts.remapped_file_buffer_end();
111 FB != FBEnd;
112 ++FB)
113 delete FB->second;
114 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000115
116 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000117 delete PreambleBuffer;
118
Douglas Gregor16896c42010-10-28 15:44:59 +0000119 ClearCachedCompletionResults();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000120}
121
122void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000123 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
124 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000125 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000126}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000127
Douglas Gregor39982192010-08-15 06:18:01 +0000128/// \brief Determine the set of code-completion contexts in which this
129/// declaration should be shown.
130static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000131 const LangOptions &LangOpts,
132 bool &IsNestedNameSpecifier) {
133 IsNestedNameSpecifier = false;
134
Douglas Gregor39982192010-08-15 06:18:01 +0000135 if (isa<UsingShadowDecl>(ND))
136 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
137 if (!ND)
138 return 0;
139
140 unsigned Contexts = 0;
141 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
142 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
143 // Types can appear in these contexts.
144 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
145 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
146 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
147 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
148 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000149 | (1 << (CodeCompletionContext::CCC_Type - 1))
150 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000151
152 // In C++, types can appear in expressions contexts (for functional casts).
153 if (LangOpts.CPlusPlus)
154 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
155
156 // In Objective-C, message sends can send interfaces. In Objective-C++,
157 // all types are available due to functional casts.
158 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
159 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
160
161 // Deal with tag names.
162 if (isa<EnumDecl>(ND)) {
163 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
164
Douglas Gregor59cab552010-08-16 23:05:20 +0000165 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000166 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000167 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000168 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
169 if (Record->isUnion())
170 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
171 else
172 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
173
Douglas Gregor39982192010-08-15 06:18:01 +0000174 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000175 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000176 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000177 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000178 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
179 // Values can appear in these contexts.
180 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
181 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000182 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000183 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
184 } else if (isa<ObjCProtocolDecl>(ND)) {
185 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
186 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000187 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000188
189 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000190 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000191 }
192
193 return Contexts;
194}
195
Douglas Gregorb14904c2010-08-13 22:48:40 +0000196void ASTUnit::CacheCodeCompletionResults() {
197 if (!TheSema)
198 return;
199
Douglas Gregor16896c42010-10-28 15:44:59 +0000200 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000201 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000202
203 // Clear out the previous results.
204 ClearCachedCompletionResults();
205
206 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000207 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000208 llvm::SmallVector<Result, 8> Results;
209 TheSema->GatherGlobalCodeCompletions(Results);
210
211 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000212 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
213
Douglas Gregorb14904c2010-08-13 22:48:40 +0000214 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
215 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000216 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000217 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000218 CachedCodeCompletionResult CachedResult;
219 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
220 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000221 Ctx->getLangOptions(),
222 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000223 CachedResult.Priority = Results[I].Priority;
224 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000225 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000226
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000227 // Keep track of the type of this completion in an ASTContext-agnostic
228 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000229 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000230 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000231 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000232 CachedResult.Type = 0;
233 } else {
234 CanQualType CanUsageType
235 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
236 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
237
238 // Determine whether we have already seen this type. If so, we save
239 // ourselves the work of formatting the type string by using the
240 // temporary, CanQualType-based hash table to find the associated value.
241 unsigned &TypeValue = CompletionTypes[CanUsageType];
242 if (TypeValue == 0) {
243 TypeValue = CompletionTypes.size();
244 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
245 = TypeValue;
246 }
247
248 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000249 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000250
Douglas Gregor39982192010-08-15 06:18:01 +0000251 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000252
253 /// Handle nested-name-specifiers in C++.
254 if (TheSema->Context.getLangOptions().CPlusPlus &&
255 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
256 // The contexts in which a nested-name-specifier can appear in C++.
257 unsigned NNSContexts
258 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
259 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
260 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
261 | (1 << (CodeCompletionContext::CCC_Statement - 1))
262 | (1 << (CodeCompletionContext::CCC_Expression - 1))
263 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
264 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
265 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
266 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000267 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000268 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
269 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000270
271 if (isa<NamespaceDecl>(Results[I].Declaration) ||
272 isa<NamespaceAliasDecl>(Results[I].Declaration))
273 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
274
275 if (unsigned RemainingContexts
276 = NNSContexts & ~CachedResult.ShowInContexts) {
277 // If there any contexts where this completion can be a
278 // nested-name-specifier but isn't already an option, create a
279 // nested-name-specifier completion.
280 Results[I].StartsNestedNameSpecifier = true;
281 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
282 CachedResult.ShowInContexts = RemainingContexts;
283 CachedResult.Priority = CCP_NestedNameSpecifier;
284 CachedResult.TypeClass = STC_Void;
285 CachedResult.Type = 0;
286 CachedCompletionResults.push_back(CachedResult);
287 }
288 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000289 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000290 }
291
Douglas Gregorb14904c2010-08-13 22:48:40 +0000292 case Result::RK_Keyword:
293 case Result::RK_Pattern:
294 // Ignore keywords and patterns; we don't care, since they are so
295 // easily regenerated.
296 break;
297
298 case Result::RK_Macro: {
299 CachedCodeCompletionResult CachedResult;
300 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
301 CachedResult.ShowInContexts
302 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
303 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
304 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
305 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
306 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
307 | (1 << (CodeCompletionContext::CCC_Statement - 1))
308 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000309 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000310 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000311 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
312 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
313
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000314
Douglas Gregorb14904c2010-08-13 22:48:40 +0000315 CachedResult.Priority = Results[I].Priority;
316 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000317 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000318 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000319 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000320 CachedCompletionResults.push_back(CachedResult);
321 break;
322 }
323 }
324 Results[I].Destroy();
325 }
326
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000327 // Make a note of the state when we performed this caching.
328 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
329 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000330}
331
332void ASTUnit::ClearCachedCompletionResults() {
333 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
334 delete CachedCompletionResults[I].Completion;
335 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000336 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000337}
338
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000339namespace {
340
Sebastian Redl2c499f62010-08-18 23:56:43 +0000341/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000342/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000343class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000344 LangOptions &LangOpt;
345 HeaderSearch &HSI;
346 std::string &TargetTriple;
347 std::string &Predefines;
348 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000349
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000350 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000351
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000352public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000353 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000354 std::string &TargetTriple, std::string &Predefines,
355 unsigned &Counter)
356 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
357 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000358
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000359 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
360 LangOpt = LangOpts;
361 return false;
362 }
Mike Stump11289f42009-09-09 15:08:12 +0000363
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000364 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000365 TargetTriple = Triple;
366 return false;
367 }
Mike Stump11289f42009-09-09 15:08:12 +0000368
Sebastian Redl8b41f302010-07-14 23:29:55 +0000369 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000370 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000371 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000372 Predefines = Buffers[0].Data;
373 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
374 Predefines += Buffers[I].Data;
375 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000376 return false;
377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Douglas Gregora2f49452010-03-16 19:09:18 +0000379 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000380 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000383 virtual void ReadCounter(unsigned Value) {
384 Counter = Value;
385 }
386};
387
Douglas Gregor33cdd812010-02-18 18:08:43 +0000388class StoredDiagnosticClient : public DiagnosticClient {
389 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
390
391public:
392 explicit StoredDiagnosticClient(
393 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
394 : StoredDiags(StoredDiags) { }
395
396 virtual void HandleDiagnostic(Diagnostic::Level Level,
397 const DiagnosticInfo &Info);
398};
399
400/// \brief RAII object that optionally captures diagnostics, if
401/// there is no diagnostic client to capture them already.
402class CaptureDroppedDiagnostics {
403 Diagnostic &Diags;
404 StoredDiagnosticClient Client;
405 DiagnosticClient *PreviousClient;
406
407public:
408 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000409 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000410 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000411 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000412 if (RequestCapture || Diags.getClient() == 0) {
413 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000414 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000415 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000416 }
417
418 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000419 if (Diags.getClient() == &Client) {
420 Diags.takeClient();
421 Diags.setClient(PreviousClient);
422 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000423 }
424};
425
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000426} // anonymous namespace
427
Douglas Gregor33cdd812010-02-18 18:08:43 +0000428void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
429 const DiagnosticInfo &Info) {
430 StoredDiags.push_back(StoredDiagnostic(Level, Info));
431}
432
Steve Naroffc0683b92009-09-03 18:19:54 +0000433const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000434 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000435}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000436
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000437const std::string &ASTUnit::getASTFileName() {
438 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000439 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000440}
441
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000442llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
443 std::string *ErrorStr,
444 int64_t FileSize,
445 struct stat *FileInfo) {
446 return FileMgr->getBufferForFile(Filename, FileSystemOpts,
447 ErrorStr, FileSize, FileInfo);
448}
449
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000450/// \brief Configure the diagnostics object for use with ASTUnit.
451void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
452 ASTUnit &AST, bool CaptureDiagnostics) {
453 if (!Diags.getPtr()) {
454 // No diagnostics engine was provided, so create our own diagnostics object
455 // with the default options.
456 DiagnosticOptions DiagOpts;
457 DiagnosticClient *Client = 0;
458 if (CaptureDiagnostics)
459 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
460 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0, Client);
461 } else if (CaptureDiagnostics) {
462 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
463 }
464}
465
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000466ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000467 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000468 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000469 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000470 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000471 unsigned NumRemappedFiles,
472 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000473 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000474 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000475
Douglas Gregor16bef852009-10-16 20:01:17 +0000476 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000477 AST->CaptureDiagnostics = CaptureDiagnostics;
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 Gregoraa98ed92010-01-23 00:14:00 +0000487 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
488 // Create the file entry for the file that we're mapping from.
489 const FileEntry *FromFile
490 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
491 RemappedFiles[I].second->getBufferSize(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000492 0,
493 AST->getFileSystemOpts());
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000494 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000495 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000496 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000497 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000498 continue;
499 }
500
501 // Override the contents of the "from" file with the contents of
502 // the "to" file.
503 AST->getSourceManager().overrideFileContents(FromFile,
504 RemappedFiles[I].second);
505 }
506
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000507 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000508
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000509 LangOptions LangInfo;
510 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
511 std::string TargetTriple;
512 std::string Predefines;
513 unsigned Counter;
514
Sebastian Redl2c499f62010-08-18 23:56:43 +0000515 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516
Sebastian Redl2c499f62010-08-18 23:56:43 +0000517 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000518 AST->getFileSystemOpts(), AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000519 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000520 Predefines, Counter));
521
Sebastian Redl009e7f22010-10-05 16:15:19 +0000522 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000523 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000524 break;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Sebastian Redl2c499f62010-08-18 23:56:43 +0000526 case ASTReader::Failure:
527 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000528 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000529 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Daniel Dunbara8a50932009-12-02 08:44:16 +0000532 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
533
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000534 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000535
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000536 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000537 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000538 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000539 TargetOptions TargetOpts;
540 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000541 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000542 TargetOpts.CPU = "";
543 TargetOpts.Features.clear();
544 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000545 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
546 TargetOpts));
547 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
548 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000549 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000550 Preprocessor &PP = *AST->PP.get();
551
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000552 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000554 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000555
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000556 // Create and initialize the ASTContext.
557
558 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000559 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000560 *AST->Target.get(),
561 PP.getIdentifierTable(),
562 PP.getSelectorTable(),
563 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000564 /* size_reserve = */0));
565 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000566
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000567 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000568
Sebastian Redl2c499f62010-08-18 23:56:43 +0000569 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000570 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000571 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000572 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000573 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000574 Context.setExternalSource(Source);
575
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000576 // Create an AST consumer, even though it isn't used.
577 AST->Consumer.reset(new ASTConsumer);
578
Sebastian Redl2c499f62010-08-18 23:56:43 +0000579 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000580 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
581 AST->TheSema->Initialize();
582 ReaderPtr->InitializeSema(*AST->TheSema);
583
Mike Stump11289f42009-09-09 15:08:12 +0000584 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000585}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000586
587namespace {
588
Daniel Dunbar644dca02009-12-04 08:17:33 +0000589class TopLevelDeclTrackerConsumer : public ASTConsumer {
590 ASTUnit &Unit;
591
592public:
593 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
594
595 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000596 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
597 Decl *D = *it;
598 // FIXME: Currently ObjC method declarations are incorrectly being
599 // reported as top-level declarations, even though their DeclContext
600 // is the containing ObjC @interface/@implementation. This is a
601 // fundamental problem in the parser right now.
602 if (isa<ObjCMethodDecl>(D))
603 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000604 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000605 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000606 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000607
608 // We're not interested in "interesting" decls.
609 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000610};
611
612class TopLevelDeclTrackerAction : public ASTFrontendAction {
613public:
614 ASTUnit &Unit;
615
Daniel Dunbar764c0822009-12-01 09:51:01 +0000616 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
617 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000618 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000619 }
620
621public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000622 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
623
Daniel Dunbar764c0822009-12-01 09:51:01 +0000624 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000625 virtual bool usesCompleteTranslationUnit() {
626 return Unit.isCompleteTranslationUnit();
627 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000628};
629
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000630class PrecompilePreambleConsumer : public PCHGenerator {
631 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000632 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000633
634public:
635 PrecompilePreambleConsumer(ASTUnit &Unit,
636 const Preprocessor &PP, bool Chaining,
637 const char *isysroot, llvm::raw_ostream *Out)
638 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
639
Douglas Gregore9db88f2010-08-03 19:06:41 +0000640 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000641 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
642 Decl *D = *it;
643 // FIXME: Currently ObjC method declarations are incorrectly being
644 // reported as top-level declarations, even though their DeclContext
645 // is the containing ObjC @interface/@implementation. This is a
646 // fundamental problem in the parser right now.
647 if (isa<ObjCMethodDecl>(D))
648 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000649 TopLevelDecls.push_back(D);
650 }
651 }
652
653 virtual void HandleTranslationUnit(ASTContext &Ctx) {
654 PCHGenerator::HandleTranslationUnit(Ctx);
655 if (!Unit.getDiagnostics().hasErrorOccurred()) {
656 // Translate the top-level declarations we captured during
657 // parsing into declaration IDs in the precompiled
658 // preamble. This will allow us to deserialize those top-level
659 // declarations when requested.
660 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
661 Unit.addTopLevelDeclFromPreamble(
662 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000663 }
664 }
665};
666
667class PrecompilePreambleAction : public ASTFrontendAction {
668 ASTUnit &Unit;
669
670public:
671 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
672
673 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
674 llvm::StringRef InFile) {
675 std::string Sysroot;
676 llvm::raw_ostream *OS = 0;
677 bool Chaining;
678 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
679 OS, Chaining))
680 return 0;
681
682 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
683 Sysroot.c_str() : 0;
684 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
685 isysroot, OS);
686 }
687
688 virtual bool hasCodeCompletionSupport() const { return false; }
689 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000690 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000691};
692
Daniel Dunbar764c0822009-12-01 09:51:01 +0000693}
694
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000695/// Parse the source file into a translation unit using the given compiler
696/// invocation, replacing the current translation unit.
697///
698/// \returns True if a failure occurred that causes the ASTUnit not to
699/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000700bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000701 delete SavedMainFileBuffer;
702 SavedMainFileBuffer = 0;
703
Douglas Gregora0734c52010-08-19 01:33:06 +0000704 if (!Invocation.get()) {
705 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000706 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000707 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000708
Daniel Dunbar764c0822009-12-01 09:51:01 +0000709 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000710 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000711 Clang.setInvocation(Invocation.take());
712 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
713
Douglas Gregor8e984da2010-08-04 16:47:14 +0000714 // Set up diagnostics, capturing any diagnostics that would
715 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000716 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000717
Daniel Dunbar764c0822009-12-01 09:51:01 +0000718 // Create the target instance.
719 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
720 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000721 if (!Clang.hasTarget()) {
722 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000723 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000724 }
725
Daniel Dunbar764c0822009-12-01 09:51:01 +0000726 // Inform the target of the language options.
727 //
728 // FIXME: We shouldn't need to do this, the target should be immutable once
729 // created. This complexity should be lifted elsewhere.
730 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000731
Daniel Dunbar764c0822009-12-01 09:51:01 +0000732 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
733 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000734 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000735 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000736 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
737 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000738
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000739 // Configure the various subsystems.
740 // FIXME: Should we retain the previous file manager?
741 FileMgr.reset(new FileManager);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000742 FileSystemOpts = Clang.getFileSystemOpts();
743 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr, FileSystemOpts));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000744 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000745 Ctx.reset();
746 PP.reset();
747
748 // Clear out old caches and data.
749 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000750 CleanTemporaryFiles();
751 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000752
Douglas Gregor7b02b582010-08-20 00:02:33 +0000753 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000754 StoredDiagnostics.erase(
755 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
756 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000757 TopLevelDeclsInPreamble.clear();
758 }
759
Daniel Dunbar764c0822009-12-01 09:51:01 +0000760 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000761 Clang.setFileManager(&getFileManager());
762
Daniel Dunbar764c0822009-12-01 09:51:01 +0000763 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000764 Clang.setSourceManager(&getSourceManager());
765
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000766 // If the main file has been overridden due to the use of a preamble,
767 // make that override happen and introduce the preamble.
768 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000769 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000770 if (OverrideMainBuffer) {
771 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
772 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
773 PreprocessorOpts.PrecompiledPreambleBytes.second
774 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000775 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000776 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000777 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000778
Douglas Gregord9a30af2010-08-02 20:51:39 +0000779 // The stored diagnostic has the old source manager in it; update
780 // the locations to refer into the new source manager. Since we've
781 // been careful to make sure that the source manager's state
782 // before and after are identical, so that we can reuse the source
783 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000784 for (unsigned I = NumStoredDiagnosticsFromDriver,
785 N = StoredDiagnostics.size();
786 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000787 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
788 getSourceManager());
789 StoredDiagnostics[I].setLocation(Loc);
790 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000791
792 // Keep track of the override buffer;
793 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000794 } else {
795 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
796 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000797 }
798
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000799 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
800 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000801 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000802 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000803 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000804
Daniel Dunbar644dca02009-12-04 08:17:33 +0000805 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000806
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000807 // Steal the created target, context, and preprocessor, and take back the
808 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000809 TheSema.reset(Clang.takeSema());
810 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000811 Ctx.reset(Clang.takeASTContext());
812 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000813 Clang.takeSourceManager();
814 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000815 Target.reset(Clang.takeTarget());
816
Daniel Dunbar644dca02009-12-04 08:17:33 +0000817 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000818
819 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000820 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000821 PreprocessorOpts.eraseRemappedFile(
822 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000823 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
824 }
825
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000826 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000827
828 // If we were asked to cache code-completion results and don't have any
829 // results yet, do so now.
830 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
831 CacheCodeCompletionResults();
Douglas Gregorbb6a8812010-10-08 04:03:57 +0000832
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000833 return false;
834
Daniel Dunbar764c0822009-12-01 09:51:01 +0000835error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000836 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000837 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000838 PreprocessorOpts.eraseRemappedFile(
839 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000840 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000841 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000842 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000843 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000844 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000845
Douglas Gregorefc46952010-10-12 16:25:54 +0000846 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000847 Clang.takeSourceManager();
848 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000849 Invocation.reset(Clang.takeInvocation());
850 return true;
851}
852
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000853/// \brief Simple function to retrieve a path for a preamble precompiled header.
854static std::string GetPreamblePCHPath() {
855 // FIXME: This is lame; sys::Path should provide this function (in particular,
856 // it should know how to find the temporary files dir).
857 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000858 // FIXME: This is a hack so that we can override the preamble file during
859 // crash-recovery testing, which is the only case where the preamble files
860 // are not necessarily cleaned up.
861 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
862 if (TmpFile)
863 return TmpFile;
864
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000865 std::string Error;
866 const char *TmpDir = ::getenv("TMPDIR");
867 if (!TmpDir)
868 TmpDir = ::getenv("TEMP");
869 if (!TmpDir)
870 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000871#ifdef LLVM_ON_WIN32
872 if (!TmpDir)
873 TmpDir = ::getenv("USERPROFILE");
874#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000875 if (!TmpDir)
876 TmpDir = "/tmp";
877 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000878 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000879 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000880 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000881 if (P.createTemporaryFileOnDisk())
882 return std::string();
883
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000884 return P.str();
885}
886
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000887/// \brief Compute the preamble for the main file, providing the source buffer
888/// that corresponds to the main file along with a pair (bytes, start-of-line)
889/// that describes the preamble.
890std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000891ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
892 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000893 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000894 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000895 = Invocation.getPreprocessorOpts();
896 CreatedBuffer = false;
897
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000898 // Try to determine if the main file has been remapped, either from the
899 // command line (to another file) or directly through the compiler invocation
900 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000901 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000902 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
903 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
904 // Check whether there is a file-file remapping of the main file
905 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000906 M = PreprocessorOpts.remapped_file_begin(),
907 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000908 M != E;
909 ++M) {
910 llvm::sys::PathWithStatus MPath(M->first);
911 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
912 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
913 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000914 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000915 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000916 CreatedBuffer = false;
917 }
918
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000919 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000920 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000921 return std::make_pair((llvm::MemoryBuffer*)0,
922 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000923 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000924 }
925 }
926 }
927
928 // Check whether there is a file-buffer remapping. It supercedes the
929 // file-file remapping.
930 for (PreprocessorOptions::remapped_file_buffer_iterator
931 M = PreprocessorOpts.remapped_file_buffer_begin(),
932 E = PreprocessorOpts.remapped_file_buffer_end();
933 M != E;
934 ++M) {
935 llvm::sys::PathWithStatus MPath(M->first);
936 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
937 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
938 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000939 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000940 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000941 CreatedBuffer = false;
942 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000943
Douglas Gregor4dde7492010-07-23 23:58:40 +0000944 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000945 }
946 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000947 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000948 }
949
950 // If the main source file was not remapped, load it now.
951 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000952 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000953 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000954 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000955
956 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000957 }
958
Douglas Gregor028d3e42010-08-09 20:45:32 +0000959 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000960}
961
Douglas Gregor6481ef12010-07-24 00:38:13 +0000962static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
963 bool DeleteOld,
964 unsigned NewSize,
965 llvm::StringRef NewName) {
966 llvm::MemoryBuffer *Result
967 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
968 memcpy(const_cast<char*>(Result->getBufferStart()),
969 Old->getBufferStart(), Old->getBufferSize());
970 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000971 ' ', NewSize - Old->getBufferSize() - 1);
972 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000973
974 if (DeleteOld)
975 delete Old;
976
977 return Result;
978}
979
Douglas Gregor4dde7492010-07-23 23:58:40 +0000980/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
981/// the source file.
982///
983/// This routine will compute the preamble of the main source file. If a
984/// non-trivial preamble is found, it will precompile that preamble into a
985/// precompiled header so that the precompiled preamble can be used to reduce
986/// reparsing time. If a precompiled preamble has already been constructed,
987/// this routine will determine if it is still valid and, if so, avoid
988/// rebuilding the precompiled preamble.
989///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000990/// \param AllowRebuild When true (the default), this routine is
991/// allowed to rebuild the precompiled preamble if it is found to be
992/// out-of-date.
993///
994/// \param MaxLines When non-zero, the maximum number of lines that
995/// can occur within the preamble.
996///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000997/// \returns If the precompiled preamble can be used, returns a newly-allocated
998/// buffer that should be used in place of the main file when doing so.
999/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001000llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001001 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001002 bool AllowRebuild,
1003 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001004 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1005 PreprocessorOptions &PreprocessorOpts
1006 = PreambleInvocation.getPreprocessorOpts();
1007
1008 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001009 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001010 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001011
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001012 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001013 // We couldn't find a preamble in the main source. Clear out the current
1014 // preamble, if we have one. It's obviously no good any more.
1015 Preamble.clear();
1016 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001017 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001018 PreambleFile.clear();
1019 }
1020 if (CreatedPreambleBuffer)
1021 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001022
1023 // The next time we actually see a preamble, precompile it.
1024 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001025 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001026 }
1027
1028 if (!Preamble.empty()) {
1029 // We've previously computed a preamble. Check whether we have the same
1030 // preamble now that we did before, and that there's enough space in
1031 // the main-file buffer within the precompiled preamble to fit the
1032 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001033 if (Preamble.size() == NewPreamble.second.first &&
1034 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001035 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001036 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001037 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001038 // The preamble has not changed. We may be able to re-use the precompiled
1039 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001040
Douglas Gregor0e119552010-07-31 00:40:00 +00001041 // Check that none of the files used by the preamble have changed.
1042 bool AnyFileChanged = false;
1043
1044 // First, make a record of those files that have been overridden via
1045 // remapping or unsaved_files.
1046 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1047 for (PreprocessorOptions::remapped_file_iterator
1048 R = PreprocessorOpts.remapped_file_begin(),
1049 REnd = PreprocessorOpts.remapped_file_end();
1050 !AnyFileChanged && R != REnd;
1051 ++R) {
1052 struct stat StatBuf;
1053 if (stat(R->second.c_str(), &StatBuf)) {
1054 // If we can't stat the file we're remapping to, assume that something
1055 // horrible happened.
1056 AnyFileChanged = true;
1057 break;
1058 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001059
Douglas Gregor0e119552010-07-31 00:40:00 +00001060 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1061 StatBuf.st_mtime);
1062 }
1063 for (PreprocessorOptions::remapped_file_buffer_iterator
1064 R = PreprocessorOpts.remapped_file_buffer_begin(),
1065 REnd = PreprocessorOpts.remapped_file_buffer_end();
1066 !AnyFileChanged && R != REnd;
1067 ++R) {
1068 // FIXME: Should we actually compare the contents of file->buffer
1069 // remappings?
1070 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1071 0);
1072 }
1073
1074 // Check whether anything has changed.
1075 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1076 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1077 !AnyFileChanged && F != FEnd;
1078 ++F) {
1079 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1080 = OverriddenFiles.find(F->first());
1081 if (Overridden != OverriddenFiles.end()) {
1082 // This file was remapped; check whether the newly-mapped file
1083 // matches up with the previous mapping.
1084 if (Overridden->second != F->second)
1085 AnyFileChanged = true;
1086 continue;
1087 }
1088
1089 // The file was not remapped; check whether it has changed on disk.
1090 struct stat StatBuf;
1091 if (stat(F->first(), &StatBuf)) {
1092 // If we can't stat the file, assume that something horrible happened.
1093 AnyFileChanged = true;
1094 } else if (StatBuf.st_size != F->second.first ||
1095 StatBuf.st_mtime != F->second.second)
1096 AnyFileChanged = true;
1097 }
1098
1099 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001100 // Okay! We can re-use the precompiled preamble.
1101
1102 // Set the state of the diagnostic object to mimic its state
1103 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001104 // FIXME: This won't catch any #pragma push warning changes that
1105 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001106 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001107 ProcessWarningOptions(getDiagnostics(),
1108 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001109 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1110 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1111 StoredDiagnostics.erase(
1112 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1113 StoredDiagnostics.end());
1114
1115 // Create a version of the main file buffer that is padded to
1116 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001117 return CreatePaddedMainFileBuffer(NewPreamble.first,
1118 CreatedPreambleBuffer,
1119 PreambleReservedSize,
1120 FrontendOpts.Inputs[0].second);
1121 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001122 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001123
1124 // If we aren't allowed to rebuild the precompiled preamble, just
1125 // return now.
1126 if (!AllowRebuild)
1127 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001128
Douglas Gregor4dde7492010-07-23 23:58:40 +00001129 // We can't reuse the previously-computed preamble. Build a new one.
1130 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001131 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001132 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001133 } else if (!AllowRebuild) {
1134 // We aren't allowed to rebuild the precompiled preamble; just
1135 // return now.
1136 return 0;
1137 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001138
1139 // If the preamble rebuild counter > 1, it's because we previously
1140 // failed to build a preamble and we're not yet ready to try
1141 // again. Decrement the counter and return a failure.
1142 if (PreambleRebuildCounter > 1) {
1143 --PreambleRebuildCounter;
1144 return 0;
1145 }
1146
Douglas Gregore10f0e52010-09-11 17:56:52 +00001147 // Create a temporary file for the precompiled preamble. In rare
1148 // circumstances, this can fail.
1149 std::string PreamblePCHPath = GetPreamblePCHPath();
1150 if (PreamblePCHPath.empty()) {
1151 // Try again next time.
1152 PreambleRebuildCounter = 1;
1153 return 0;
1154 }
1155
Douglas Gregor4dde7492010-07-23 23:58:40 +00001156 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001157 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001158 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001159
1160 // Create a new buffer that stores the preamble. The buffer also contains
1161 // extra space for the original contents of the file (which will be present
1162 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001163 // grows.
1164 PreambleReservedSize = NewPreamble.first->getBufferSize();
1165 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001166 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001167 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001168 PreambleReservedSize *= 2;
1169
Douglas Gregord9a30af2010-08-02 20:51:39 +00001170 // Save the preamble text for later; we'll need to compare against it for
1171 // subsequent reparses.
1172 Preamble.assign(NewPreamble.first->getBufferStart(),
1173 NewPreamble.first->getBufferStart()
1174 + NewPreamble.second.first);
1175 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1176
Douglas Gregora0734c52010-08-19 01:33:06 +00001177 delete PreambleBuffer;
1178 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001179 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001180 FrontendOpts.Inputs[0].second);
1181 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001182 NewPreamble.first->getBufferStart(), Preamble.size());
1183 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001184 ' ', PreambleReservedSize - Preamble.size() - 1);
1185 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001186
1187 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001188 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1190
1191 // Tell the compiler invocation to generate a temporary precompiled header.
1192 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001193 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001194 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001195 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001196 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1197 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001198
1199 // Create the compiler instance to use for building the precompiled preamble.
1200 CompilerInstance Clang;
1201 Clang.setInvocation(&PreambleInvocation);
1202 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1203
Douglas Gregor8e984da2010-08-04 16:47:14 +00001204 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001205 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206
1207 // Create the target instance.
1208 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1209 Clang.getTargetOpts()));
1210 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1212 Preamble.clear();
1213 if (CreatedPreambleBuffer)
1214 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001215 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001216 PreprocessorOpts.eraseRemappedFile(
1217 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001218 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219 }
1220
1221 // Inform the target of the language options.
1222 //
1223 // FIXME: We shouldn't need to do this, the target should be immutable once
1224 // created. This complexity should be lifted elsewhere.
1225 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1226
1227 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1228 "Invocation must have exactly one source file!");
1229 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1230 "FIXME: AST inputs not yet supported here!");
1231 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1232 "IR inputs not support here!");
1233
1234 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001235 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001236 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001237 StoredDiagnostics.erase(
1238 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1239 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001240 TopLevelDecls.clear();
1241 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001242
1243 // Create a file manager object to provide access to and cache the filesystem.
1244 Clang.setFileManager(new FileManager);
1245
1246 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001247 Clang.setSourceManager(new SourceManager(getDiagnostics(),
1248 Clang.getFileManager(),
1249 Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001250
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001251 llvm::OwningPtr<PrecompilePreambleAction> Act;
1252 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001253 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1254 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001255 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001256 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1257 Preamble.clear();
1258 if (CreatedPreambleBuffer)
1259 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001260 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001261 PreprocessorOpts.eraseRemappedFile(
1262 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001263 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001264 }
1265
1266 Act->Execute();
1267 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001268 Clang.takeInvocation();
1269
Douglas Gregore9db88f2010-08-03 19:06:41 +00001270 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001271 // There were errors parsing the preamble, so no precompiled header was
1272 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001273 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001274 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1275 Preamble.clear();
1276 if (CreatedPreambleBuffer)
1277 delete NewPreamble.first;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001278 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001279 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001280 PreprocessorOpts.eraseRemappedFile(
1281 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001282 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001283 }
1284
1285 // Keep track of the preamble we precompiled.
1286 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001287 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1288 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001289
1290 // Keep track of all of the files that the source manager knows about,
1291 // so we can verify whether they have changed or not.
1292 FilesInPreamble.clear();
1293 SourceManager &SourceMgr = Clang.getSourceManager();
1294 const llvm::MemoryBuffer *MainFileBuffer
1295 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1296 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1297 FEnd = SourceMgr.fileinfo_end();
1298 F != FEnd;
1299 ++F) {
1300 const FileEntry *File = F->second->Entry;
1301 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1302 continue;
1303
1304 FilesInPreamble[File->getName()]
1305 = std::make_pair(F->second->getSize(), File->getModificationTime());
1306 }
1307
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001308 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001309 PreprocessorOpts.eraseRemappedFile(
1310 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001311 return CreatePaddedMainFileBuffer(NewPreamble.first,
1312 CreatedPreambleBuffer,
1313 PreambleReservedSize,
1314 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001315}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001316
Douglas Gregore9db88f2010-08-03 19:06:41 +00001317void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1318 std::vector<Decl *> Resolved;
1319 Resolved.reserve(TopLevelDeclsInPreamble.size());
1320 ExternalASTSource &Source = *getASTContext().getExternalSource();
1321 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1322 // Resolve the declaration ID to an actual declaration, possibly
1323 // deserializing the declaration in the process.
1324 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1325 if (D)
1326 Resolved.push_back(D);
1327 }
1328 TopLevelDeclsInPreamble.clear();
1329 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1330}
1331
1332unsigned ASTUnit::getMaxPCHLevel() const {
1333 if (!getOnlyLocalDecls())
1334 return Decl::MaxPCHLevel;
1335
Sebastian Redl009e7f22010-10-05 16:15:19 +00001336 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001337}
1338
Douglas Gregor16896c42010-10-28 15:44:59 +00001339llvm::StringRef ASTUnit::getMainFileName() const {
1340 return Invocation->getFrontendOpts().Inputs[0].second;
1341}
1342
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001343bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1344 if (!Invocation)
1345 return true;
1346
1347 // We'll manage file buffers ourselves.
1348 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1349 Invocation->getFrontendOpts().DisableFree = false;
1350
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001351 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001352 if (PrecompilePreamble) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001353 PreambleRebuildCounter = 1;
1354 OverrideMainBuffer
1355 = getMainBufferWithPrecompiledPreamble(*Invocation);
1356 }
1357
Douglas Gregor16896c42010-10-28 15:44:59 +00001358 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001359 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001360
Douglas Gregor16896c42010-10-28 15:44:59 +00001361 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001362}
1363
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001364ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1365 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1366 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001367 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001368 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001369 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001370 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001371 // Create the AST unit.
1372 llvm::OwningPtr<ASTUnit> AST;
1373 AST.reset(new ASTUnit(false));
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001374 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001375 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001376 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001377 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001378 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001379 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001380 AST->Invocation.reset(CI);
1381
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001382 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001383}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001384
1385ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1386 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001387 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001388 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001389 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001390 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001391 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001392 unsigned NumRemappedFiles,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001393 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001394 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001395 bool CacheCodeCompletionResults,
1396 bool CXXPrecompilePreamble,
1397 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001398 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001399 // No diagnostics engine was provided, so create our own diagnostics object
1400 // with the default options.
1401 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001402 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +00001403 }
1404
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001405 llvm::SmallVector<const char *, 16> Args;
1406 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1407 Args.insert(Args.end(), ArgBegin, ArgEnd);
1408
1409 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1410 // also want to force it to use clang.
1411 Args.push_back("-fsyntax-only");
1412
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001413 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1414
1415 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001416
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001417 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001418 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001419 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001420
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001421 // FIXME: We shouldn't have to pass in the path info.
1422 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1423 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001424
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001425 // Don't check that inputs exist, they have been remapped.
1426 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001427
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001428 llvm::OwningPtr<driver::Compilation> C(
1429 TheDriver.BuildCompilation(Args.size(), Args.data()));
1430
1431 // We expect to get back exactly one command job, if we didn't something
1432 // failed.
1433 const driver::JobList &Jobs = C->getJobs();
1434 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1435 llvm::SmallString<256> Msg;
1436 llvm::raw_svector_ostream OS(Msg);
1437 C->PrintJob(OS, C->getJobs(), "; ", true);
1438 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1439 return 0;
1440 }
1441
1442 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1443 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1444 Diags->Report(diag::err_fe_expected_clang_command);
1445 return 0;
1446 }
1447
1448 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1449 CI.reset(new CompilerInvocation);
1450 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001451 const_cast<const char **>(CCArgs.data()),
1452 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001453 CCArgs.size(),
1454 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001455 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001456
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001457 // Override any files that need remapping
1458 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001459 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001460 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001461
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001462 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001463 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001464
Douglas Gregorf5a18542010-10-27 17:24:53 +00001465 // Check whether we should precompile the preamble and/or use chained PCH.
1466 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1467 if (CI->getLangOpts().CPlusPlus) {
1468 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1469
1470 if (PrecompilePreamble && !CXXChainedPCH &&
1471 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1472 PrecompilePreamble = false;
1473 }
1474
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001475 // Create the AST unit.
1476 llvm::OwningPtr<ASTUnit> AST;
1477 AST.reset(new ASTUnit(false));
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001478 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001479 AST->Diagnostics = Diags;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001480 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001481 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001482 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1483 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1484 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1485 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1486 AST->StoredDiagnostics.swap(StoredDiagnostics);
1487 AST->Invocation.reset(CI.take());
1488 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001489}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001490
1491bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1492 if (!Invocation.get())
1493 return true;
1494
Douglas Gregor16896c42010-10-28 15:44:59 +00001495 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001496 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001497
Douglas Gregor0e119552010-07-31 00:40:00 +00001498 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001499 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1500 for (PreprocessorOptions::remapped_file_buffer_iterator
1501 R = PPOpts.remapped_file_buffer_begin(),
1502 REnd = PPOpts.remapped_file_buffer_end();
1503 R != REnd;
1504 ++R) {
1505 delete R->second;
1506 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001507 Invocation->getPreprocessorOpts().clearRemappedFiles();
1508 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1509 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1510 RemappedFiles[I].second);
1511
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001512 // If we have a preamble file lying around, or if we might try to
1513 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001514 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001515 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001516 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001517
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001518 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001519 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001520 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001521 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1522 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001523
Douglas Gregor4dde7492010-07-23 23:58:40 +00001524 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001525 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001526
1527 if (ShouldCacheCodeCompletionResults) {
1528 if (CacheCodeCompletionCoolDown > 0)
1529 --CacheCodeCompletionCoolDown;
1530 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1531 CacheCodeCompletionResults();
1532 }
1533
Douglas Gregor4dde7492010-07-23 23:58:40 +00001534 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001535}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001536
Douglas Gregorb14904c2010-08-13 22:48:40 +00001537//----------------------------------------------------------------------------//
1538// Code completion
1539//----------------------------------------------------------------------------//
1540
1541namespace {
1542 /// \brief Code completion consumer that combines the cached code-completion
1543 /// results from an ASTUnit with the code-completion results provided to it,
1544 /// then passes the result on to
1545 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1546 unsigned NormalContexts;
1547 ASTUnit &AST;
1548 CodeCompleteConsumer &Next;
1549
1550 public:
1551 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001552 bool IncludeMacros, bool IncludeCodePatterns,
1553 bool IncludeGlobals)
1554 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001555 Next.isOutputBinary()), AST(AST), Next(Next)
1556 {
1557 // Compute the set of contexts in which we will look when we don't have
1558 // any information about the specific context.
1559 NormalContexts
1560 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1561 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1562 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1563 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1564 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1565 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1566 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1567 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001568 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001569 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1570 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001571
Douglas Gregorb14904c2010-08-13 22:48:40 +00001572 if (AST.getASTContext().getLangOptions().CPlusPlus)
1573 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1574 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1575 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1576 }
1577
1578 virtual void ProcessCodeCompleteResults(Sema &S,
1579 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001580 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001581 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001582
1583 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1584 OverloadCandidate *Candidates,
1585 unsigned NumCandidates) {
1586 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1587 }
1588 };
1589}
Douglas Gregord46cf182010-08-16 20:01:48 +00001590
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001591/// \brief Helper function that computes which global names are hidden by the
1592/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001593static void CalculateHiddenNames(const CodeCompletionContext &Context,
1594 CodeCompletionResult *Results,
1595 unsigned NumResults,
1596 ASTContext &Ctx,
1597 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001598 bool OnlyTagNames = false;
1599 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001600 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001601 case CodeCompletionContext::CCC_TopLevel:
1602 case CodeCompletionContext::CCC_ObjCInterface:
1603 case CodeCompletionContext::CCC_ObjCImplementation:
1604 case CodeCompletionContext::CCC_ObjCIvarList:
1605 case CodeCompletionContext::CCC_ClassStructUnion:
1606 case CodeCompletionContext::CCC_Statement:
1607 case CodeCompletionContext::CCC_Expression:
1608 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1609 case CodeCompletionContext::CCC_MemberAccess:
1610 case CodeCompletionContext::CCC_Namespace:
1611 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001612 case CodeCompletionContext::CCC_Name:
1613 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001614 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001615 break;
1616
1617 case CodeCompletionContext::CCC_EnumTag:
1618 case CodeCompletionContext::CCC_UnionTag:
1619 case CodeCompletionContext::CCC_ClassOrStructTag:
1620 OnlyTagNames = true;
1621 break;
1622
1623 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001624 case CodeCompletionContext::CCC_MacroName:
1625 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001626 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001627 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001628 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001629 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001630 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001631 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001632 // We're looking for nothing, or we're looking for names that cannot
1633 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001634 return;
1635 }
1636
John McCall276321a2010-08-25 06:19:51 +00001637 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001638 for (unsigned I = 0; I != NumResults; ++I) {
1639 if (Results[I].Kind != Result::RK_Declaration)
1640 continue;
1641
1642 unsigned IDNS
1643 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1644
1645 bool Hiding = false;
1646 if (OnlyTagNames)
1647 Hiding = (IDNS & Decl::IDNS_Tag);
1648 else {
1649 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001650 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1651 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001652 if (Ctx.getLangOptions().CPlusPlus)
1653 HiddenIDNS |= Decl::IDNS_Tag;
1654 Hiding = (IDNS & HiddenIDNS);
1655 }
1656
1657 if (!Hiding)
1658 continue;
1659
1660 DeclarationName Name = Results[I].Declaration->getDeclName();
1661 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1662 HiddenNames.insert(Identifier->getName());
1663 else
1664 HiddenNames.insert(Name.getAsString());
1665 }
1666}
1667
1668
Douglas Gregord46cf182010-08-16 20:01:48 +00001669void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1670 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001671 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001672 unsigned NumResults) {
1673 // Merge the results we were given with the results we cached.
1674 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001675 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001676 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001677 : (1 << (Context.getKind() - 1)));
1678
1679 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001680 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001681 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001682 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001683 llvm::SmallVector<Result, 8> AllResults;
1684 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001685 C = AST.cached_completion_begin(),
1686 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001687 C != CEnd; ++C) {
1688 // If the context we are in matches any of the contexts we are
1689 // interested in, we'll add this result.
1690 if ((C->ShowInContexts & InContexts) == 0)
1691 continue;
1692
1693 // If we haven't added any results previously, do so now.
1694 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001695 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1696 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001697 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1698 AddedResult = true;
1699 }
1700
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001701 // Determine whether this global completion result is hidden by a local
1702 // completion result. If so, skip it.
1703 if (C->Kind != CXCursor_MacroDefinition &&
1704 HiddenNames.count(C->Completion->getTypedText()))
1705 continue;
1706
Douglas Gregord46cf182010-08-16 20:01:48 +00001707 // Adjust priority based on similar type classes.
1708 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001709 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001710 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001711 if (!Context.getPreferredType().isNull()) {
1712 if (C->Kind == CXCursor_MacroDefinition) {
1713 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001714 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001715 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001716 } else if (C->Type) {
1717 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001718 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001719 Context.getPreferredType().getUnqualifiedType());
1720 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1721 if (ExpectedSTC == C->TypeClass) {
1722 // We know this type is similar; check for an exact match.
1723 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001724 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001725 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001726 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001727 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1728 Priority /= CCF_ExactTypeMatch;
1729 else
1730 Priority /= CCF_SimilarTypeMatch;
1731 }
1732 }
1733 }
1734
Douglas Gregor12785102010-08-24 20:21:13 +00001735 // Adjust the completion string, if required.
1736 if (C->Kind == CXCursor_MacroDefinition &&
1737 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1738 // Create a new code-completion string that just contains the
1739 // macro name, without its arguments.
1740 Completion = new CodeCompletionString;
1741 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1742 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001743 CursorKind = CXCursor_NotImplemented;
1744 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001745 }
1746
Douglas Gregor8850aa32010-08-25 18:03:13 +00001747 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001748 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001749 }
1750
1751 // If we did not add any cached completion results, just forward the
1752 // results we were given to the next consumer.
1753 if (!AddedResult) {
1754 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1755 return;
1756 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001757
Douglas Gregord46cf182010-08-16 20:01:48 +00001758 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1759 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001760
1761 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1762 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001763}
1764
1765
1766
Douglas Gregor8e984da2010-08-04 16:47:14 +00001767void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1768 RemappedFile *RemappedFiles,
1769 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001770 bool IncludeMacros,
1771 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001772 CodeCompleteConsumer &Consumer,
1773 Diagnostic &Diag, LangOptions &LangOpts,
1774 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001775 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1776 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001777 if (!Invocation.get())
1778 return;
1779
Douglas Gregor16896c42010-10-28 15:44:59 +00001780 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001781 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1782 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00001783
Douglas Gregor8e984da2010-08-04 16:47:14 +00001784 CompilerInvocation CCInvocation(*Invocation);
1785 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1786 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001787
Douglas Gregorb14904c2010-08-13 22:48:40 +00001788 FrontendOpts.ShowMacrosInCodeCompletion
1789 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001790 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001791 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1792 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001793 FrontendOpts.CodeCompletionAt.FileName = File;
1794 FrontendOpts.CodeCompletionAt.Line = Line;
1795 FrontendOpts.CodeCompletionAt.Column = Column;
1796
1797 // Set the language options appropriately.
1798 LangOpts = CCInvocation.getLangOpts();
1799
1800 CompilerInstance Clang;
1801 Clang.setInvocation(&CCInvocation);
1802 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1803
1804 // Set up diagnostics, capturing any diagnostics produced.
1805 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001806 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001807 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001808 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00001809 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001810
1811 // Create the target instance.
1812 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1813 Clang.getTargetOpts()));
1814 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001815 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001816 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001817 }
1818
1819 // Inform the target of the language options.
1820 //
1821 // FIXME: We shouldn't need to do this, the target should be immutable once
1822 // created. This complexity should be lifted elsewhere.
1823 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1824
1825 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1826 "Invocation must have exactly one source file!");
1827 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1828 "FIXME: AST inputs not yet supported here!");
1829 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1830 "IR inputs not support here!");
1831
1832
1833 // Use the source and file managers that we were given.
1834 Clang.setFileManager(&FileMgr);
1835 Clang.setSourceManager(&SourceMgr);
1836
1837 // Remap files.
1838 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001839 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001840 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001841 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1842 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001843 OwnedBuffers.push_back(RemappedFiles[I].second);
1844 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001845
Douglas Gregorb14904c2010-08-13 22:48:40 +00001846 // Use the code completion consumer we were given, but adding any cached
1847 // code-completion results.
1848 AugmentedCodeCompleteConsumer
1849 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001850 FrontendOpts.ShowCodePatternsInCodeCompletion,
1851 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001852 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001853
Douglas Gregor028d3e42010-08-09 20:45:32 +00001854 // If we have a precompiled preamble, try to use it. We only allow
1855 // the use of the precompiled preamble if we're if the completion
1856 // point is within the main file, after the end of the precompiled
1857 // preamble.
1858 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1859 if (!PreambleFile.empty()) {
1860 using llvm::sys::FileStatus;
1861 llvm::sys::PathWithStatus CompleteFilePath(File);
1862 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1863 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1864 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1865 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001866 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001867 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1868 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001869 }
1870
1871 // If the main file has been overridden due to the use of a preamble,
1872 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001873 StoredDiagnostics.insert(StoredDiagnostics.end(),
1874 this->StoredDiagnostics.begin(),
1875 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001876 if (OverrideMainBuffer) {
1877 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1878 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1879 PreprocessorOpts.PrecompiledPreambleBytes.second
1880 = PreambleEndsAtStartOfLine;
1881 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1882 PreprocessorOpts.DisablePCHValidation = true;
1883
1884 // The stored diagnostics have the old source manager. Copy them
1885 // to our output set of stored diagnostics, updating the source
1886 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001887 for (unsigned I = NumStoredDiagnosticsFromDriver,
1888 N = this->StoredDiagnostics.size();
1889 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001890 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1891 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1892 StoredDiagnostics[I].setLocation(Loc);
1893 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001894
Douglas Gregorb97b6662010-08-20 00:59:43 +00001895 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001896 } else {
1897 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1898 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001899 }
1900
Douglas Gregor8e984da2010-08-04 16:47:14 +00001901 llvm::OwningPtr<SyntaxOnlyAction> Act;
1902 Act.reset(new SyntaxOnlyAction);
1903 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1904 Clang.getFrontendOpts().Inputs[0].first)) {
1905 Act->Execute();
1906 Act->EndSourceFile();
1907 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001908
Douglas Gregor8e984da2010-08-04 16:47:14 +00001909 // Steal back our resources.
1910 Clang.takeFileManager();
1911 Clang.takeSourceManager();
1912 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001913 Clang.takeCodeCompletionConsumer();
1914}
Douglas Gregore9386682010-08-13 05:36:37 +00001915
1916bool ASTUnit::Save(llvm::StringRef File) {
1917 if (getDiagnostics().hasErrorOccurred())
1918 return true;
1919
1920 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1921 // unconditionally create a stat cache when we parse the file?
1922 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001923 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1924 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001925 if (!ErrorInfo.empty() || Out.has_error())
1926 return true;
1927
1928 std::vector<unsigned char> Buffer;
1929 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001930 ASTWriter Writer(Stream);
1931 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001932
1933 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001934 if (!Buffer.empty())
1935 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001936 Out.close();
1937 return Out.has_error();
1938}