blob: f19acd093a6e9f5de62945ff32689f144a7f4469 [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"
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Douglas Gregorf88e35b2010-11-30 06:16:57 +000032#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000049#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000050#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000051#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000052#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000053using namespace clang;
54
Douglas Gregor16896c42010-10-28 15:44:59 +000055using llvm::TimeRecord;
56
57namespace {
58 class SimpleTimer {
59 bool WantTiming;
60 TimeRecord Start;
61 std::string Output;
62
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000064 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000065 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000066 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000067 }
68
Chris Lattner0e62c1c2011-07-23 10:55:15 +000069 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000070 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000071 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000072 }
73
Douglas Gregor16896c42010-10-28 15:44:59 +000074 ~SimpleTimer() {
75 if (WantTiming) {
76 TimeRecord Elapsed = TimeRecord::getCurrentTime();
77 Elapsed -= Start;
78 llvm::errs() << Output << ':';
79 Elapsed.print(Elapsed, llvm::errs());
80 llvm::errs() << '\n';
81 }
82 }
83 };
84}
85
Douglas Gregorbb420ab2010-08-04 05:53:38 +000086/// \brief After failing to build a precompiled preamble (due to
87/// errors in the source that occurs in the preamble), the number of
88/// reparses during which we'll skip even trying to precompile the
89/// preamble.
90const unsigned DefaultPreambleRebuildInterval = 5;
91
Douglas Gregor68dbaea2010-11-17 00:13:31 +000092/// \brief Tracks the number of ASTUnit objects that are currently active.
93///
94/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000095static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +000096
Douglas Gregord03e8232010-04-05 21:10:19 +000097ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +000098 : OnlyLocalDecls(false), CaptureDiagnostics(false),
99 MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +0000100 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000101 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000102 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000103 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +0000104 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000105 ShouldCacheCodeCompletionResults(false),
Chandler Carruthde81fc82011-07-14 09:02:10 +0000106 NestedMacroExpansions(true),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000107 CompletionCacheTopLevelHashValue(0),
108 PreambleTopLevelHashValue(0),
109 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000110 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000111 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000112 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000113 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
114 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000115}
Douglas Gregord03e8232010-04-05 21:10:19 +0000116
Daniel Dunbar764c0822009-12-01 09:51:01 +0000117ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000118 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000119 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000120 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000121 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000122
123 // Free the buffers associated with remapped files. We are required to
124 // perform this operation here because we explicitly request that the
125 // compiler instance *not* free these buffers for each invocation of the
126 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000127 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000128 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
129 for (PreprocessorOptions::remapped_file_buffer_iterator
130 FB = PPOpts.remapped_file_buffer_begin(),
131 FBEnd = PPOpts.remapped_file_buffer_end();
132 FB != FBEnd;
133 ++FB)
134 delete FB->second;
135 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000136
137 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000138 delete PreambleBuffer;
139
Douglas Gregor16896c42010-10-28 15:44:59 +0000140 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000141
142 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000143 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000144 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
145 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000146}
147
148void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000149 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
150 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000151 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000152}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000153
Douglas Gregor39982192010-08-15 06:18:01 +0000154/// \brief Determine the set of code-completion contexts in which this
155/// declaration should be shown.
156static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000157 const LangOptions &LangOpts,
158 bool &IsNestedNameSpecifier) {
159 IsNestedNameSpecifier = false;
160
Douglas Gregor39982192010-08-15 06:18:01 +0000161 if (isa<UsingShadowDecl>(ND))
162 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
163 if (!ND)
164 return 0;
165
166 unsigned Contexts = 0;
167 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
168 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
169 // Types can appear in these contexts.
170 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
171 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
172 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
173 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
174 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000175 | (1 << (CodeCompletionContext::CCC_Type - 1))
176 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000177
178 // In C++, types can appear in expressions contexts (for functional casts).
179 if (LangOpts.CPlusPlus)
180 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
181
182 // In Objective-C, message sends can send interfaces. In Objective-C++,
183 // all types are available due to functional casts.
184 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
185 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000186
187 // In Objective-C, you can only be a subclass of another Objective-C class
188 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor2c595ad2011-07-30 06:55:39 +0000189 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000190
191 // Deal with tag names.
192 if (isa<EnumDecl>(ND)) {
193 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
194
Douglas Gregor59cab552010-08-16 23:05:20 +0000195 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000196 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000197 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000198 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
199 if (Record->isUnion())
200 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
201 else
202 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
203
Douglas Gregor39982192010-08-15 06:18:01 +0000204 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000205 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000206 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000207 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000208 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
209 // Values can appear in these contexts.
210 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
211 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000212 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000213 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
214 } else if (isa<ObjCProtocolDecl>(ND)) {
215 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000216 } else if (isa<ObjCCategoryDecl>(ND)) {
217 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000218 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000219 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000220
221 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000222 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000223 }
224
225 return Contexts;
226}
227
Douglas Gregorb14904c2010-08-13 22:48:40 +0000228void ASTUnit::CacheCodeCompletionResults() {
229 if (!TheSema)
230 return;
231
Douglas Gregor16896c42010-10-28 15:44:59 +0000232 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000233 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000234
235 // Clear out the previous results.
236 ClearCachedCompletionResults();
237
238 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000239 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000240 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000241 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
242 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000243
244 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000245 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
246
Douglas Gregorb14904c2010-08-13 22:48:40 +0000247 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
248 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000249 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000250 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000251 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000252 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000253 *CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000254 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000255 Ctx->getLangOptions(),
256 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000257 CachedResult.Priority = Results[I].Priority;
258 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000259 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000260
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000261 // Keep track of the type of this completion in an ASTContext-agnostic
262 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000263 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000264 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000265 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000266 CachedResult.Type = 0;
267 } else {
268 CanQualType CanUsageType
269 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
270 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
271
272 // Determine whether we have already seen this type. If so, we save
273 // ourselves the work of formatting the type string by using the
274 // temporary, CanQualType-based hash table to find the associated value.
275 unsigned &TypeValue = CompletionTypes[CanUsageType];
276 if (TypeValue == 0) {
277 TypeValue = CompletionTypes.size();
278 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
279 = TypeValue;
280 }
281
282 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000283 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000284
Douglas Gregor39982192010-08-15 06:18:01 +0000285 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000286
287 /// Handle nested-name-specifiers in C++.
288 if (TheSema->Context.getLangOptions().CPlusPlus &&
289 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
290 // The contexts in which a nested-name-specifier can appear in C++.
291 unsigned NNSContexts
292 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
293 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
294 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
295 | (1 << (CodeCompletionContext::CCC_Statement - 1))
296 | (1 << (CodeCompletionContext::CCC_Expression - 1))
297 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
298 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
299 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
300 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000301 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000302 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
303 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000304
305 if (isa<NamespaceDecl>(Results[I].Declaration) ||
306 isa<NamespaceAliasDecl>(Results[I].Declaration))
307 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
308
309 if (unsigned RemainingContexts
310 = NNSContexts & ~CachedResult.ShowInContexts) {
311 // If there any contexts where this completion can be a
312 // nested-name-specifier but isn't already an option, create a
313 // nested-name-specifier completion.
314 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000315 CachedResult.Completion
316 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000317 *CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000318 CachedResult.ShowInContexts = RemainingContexts;
319 CachedResult.Priority = CCP_NestedNameSpecifier;
320 CachedResult.TypeClass = STC_Void;
321 CachedResult.Type = 0;
322 CachedCompletionResults.push_back(CachedResult);
323 }
324 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000325 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000326 }
327
Douglas Gregorb14904c2010-08-13 22:48:40 +0000328 case Result::RK_Keyword:
329 case Result::RK_Pattern:
330 // Ignore keywords and patterns; we don't care, since they are so
331 // easily regenerated.
332 break;
333
334 case Result::RK_Macro: {
335 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000336 CachedResult.Completion
337 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000338 *CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000339 CachedResult.ShowInContexts
340 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
341 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
342 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
343 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
344 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
345 | (1 << (CodeCompletionContext::CCC_Statement - 1))
346 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000347 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000348 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000349 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000350 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
351 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000352
Douglas Gregorb14904c2010-08-13 22:48:40 +0000353 CachedResult.Priority = Results[I].Priority;
354 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000355 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000356 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000357 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000358 CachedCompletionResults.push_back(CachedResult);
359 break;
360 }
361 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000362 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000363
364 // Save the current top-level hash value.
365 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000366}
367
368void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000369 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000370 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000371 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000372}
373
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000374namespace {
375
Sebastian Redl2c499f62010-08-18 23:56:43 +0000376/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000377/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000378class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000379 LangOptions &LangOpt;
380 HeaderSearch &HSI;
381 std::string &TargetTriple;
382 std::string &Predefines;
383 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000384
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000385 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000386
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000387public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000388 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000389 std::string &TargetTriple, std::string &Predefines,
390 unsigned &Counter)
391 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
392 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000393
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000394 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
395 LangOpt = LangOpts;
396 return false;
397 }
Mike Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000399 virtual bool ReadTargetTriple(StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000400 TargetTriple = Triple;
401 return false;
402 }
Mike Stump11289f42009-09-09 15:08:12 +0000403
Sebastian Redl8b41f302010-07-14 23:29:55 +0000404 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000405 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000406 std::string &SuggestedPredefines,
407 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000408 Predefines = Buffers[0].Data;
409 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
410 Predefines += Buffers[I].Data;
411 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000412 return false;
413 }
Mike Stump11289f42009-09-09 15:08:12 +0000414
Douglas Gregora2f49452010-03-16 19:09:18 +0000415 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000416 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
417 }
Mike Stump11289f42009-09-09 15:08:12 +0000418
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000419 virtual void ReadCounter(unsigned Value) {
420 Counter = Value;
421 }
422};
423
Douglas Gregor33cdd812010-02-18 18:08:43 +0000424class StoredDiagnosticClient : public DiagnosticClient {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000425 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000426
427public:
428 explicit StoredDiagnosticClient(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000430 : StoredDiags(StoredDiags) { }
431
432 virtual void HandleDiagnostic(Diagnostic::Level Level,
433 const DiagnosticInfo &Info);
434};
435
436/// \brief RAII object that optionally captures diagnostics, if
437/// there is no diagnostic client to capture them already.
438class CaptureDroppedDiagnostics {
439 Diagnostic &Diags;
440 StoredDiagnosticClient Client;
441 DiagnosticClient *PreviousClient;
442
443public:
444 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000445 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000446 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000447 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000448 if (RequestCapture || Diags.getClient() == 0) {
449 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000450 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000451 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000452 }
453
454 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000455 if (Diags.getClient() == &Client) {
456 Diags.takeClient();
457 Diags.setClient(PreviousClient);
458 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000459 }
460};
461
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000462} // anonymous namespace
463
Douglas Gregor33cdd812010-02-18 18:08:43 +0000464void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
465 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000466 // Default implementation (Warnings/errors count).
467 DiagnosticClient::HandleDiagnostic(Level, Info);
468
Douglas Gregor33cdd812010-02-18 18:08:43 +0000469 StoredDiags.push_back(StoredDiagnostic(Level, Info));
470}
471
Steve Naroffc0683b92009-09-03 18:19:54 +0000472const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000473 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000474}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000475
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000476const std::string &ASTUnit::getASTFileName() {
477 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000478 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000479}
480
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000481llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000482 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000483 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000484 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000485}
486
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000487/// \brief Configure the diagnostics object for use with ASTUnit.
488void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000489 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000490 ASTUnit &AST, bool CaptureDiagnostics) {
491 if (!Diags.getPtr()) {
492 // No diagnostics engine was provided, so create our own diagnostics object
493 // with the default options.
494 DiagnosticOptions DiagOpts;
495 DiagnosticClient *Client = 0;
496 if (CaptureDiagnostics)
497 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000498 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
499 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000500 } else if (CaptureDiagnostics) {
501 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
502 }
503}
504
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000505ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000506 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000507 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000508 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000509 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000510 unsigned NumRemappedFiles,
511 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000512 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000513
514 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000515 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
516 ASTUnitCleanup(AST.get());
517 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
518 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
519 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000520
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000521 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000522
Douglas Gregor16bef852009-10-16 20:01:17 +0000523 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000524 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000525 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000526 AST->FileMgr = new FileManager(FileSystemOpts);
527 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
528 AST->getFileManager());
Chris Lattner5159f612010-11-23 08:35:12 +0000529 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000530
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000531 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000532 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
533 if (const llvm::MemoryBuffer *
534 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
535 // Create the file entry for the file that we're mapping from.
536 const FileEntry *FromFile
537 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
538 memBuf->getBufferSize(),
539 0);
540 if (!FromFile) {
541 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
542 << RemappedFiles[I].first;
543 delete memBuf;
544 continue;
545 }
546
547 // Override the contents of the "from" file with the contents of
548 // the "to" file.
549 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
550
551 } else {
552 const char *fname = fileOrBuf.get<const char *>();
553 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
554 if (!ToFile) {
555 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
556 << RemappedFiles[I].first << fname;
557 continue;
558 }
559
560 // Create the file entry for the file that we're mapping from.
561 const FileEntry *FromFile
562 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
563 ToFile->getSize(),
564 0);
565 if (!FromFile) {
566 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
567 << RemappedFiles[I].first;
568 delete memBuf;
569 continue;
570 }
571
572 // Override the contents of the "from" file with the contents of
573 // the "to" file.
574 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000575 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000576 }
577
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000578 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000579
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000580 LangOptions LangInfo;
581 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
582 std::string TargetTriple;
583 std::string Predefines;
584 unsigned Counter;
585
Sebastian Redl2c499f62010-08-18 23:56:43 +0000586 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000587
Sebastian Redl2c499f62010-08-18 23:56:43 +0000588 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000589 AST->getDiagnostics()));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000590
591 // Recover resources if we crash before exiting this method.
592 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
593 ReaderCleanup(Reader.get());
594
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000595 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000596 Predefines, Counter));
597
Douglas Gregora6895d82011-07-22 16:00:58 +0000598 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000599 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000600 break;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Sebastian Redl2c499f62010-08-18 23:56:43 +0000602 case ASTReader::Failure:
603 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000604 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000605 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000606 }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Daniel Dunbara8a50932009-12-02 08:44:16 +0000608 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
609
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000610 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000611
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000612 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000613 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000614 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000615 TargetOptions TargetOpts;
616 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000617 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000618 TargetOpts.CPU = "";
619 TargetOpts.Features.clear();
620 TargetOpts.Triple = TargetTriple;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000621 AST->Target = TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
622 TargetOpts);
623 AST->PP = new Preprocessor(AST->getDiagnostics(), LangInfo, *AST->Target,
624 AST->getSourceManager(), HeaderInfo);
625 Preprocessor &PP = *AST->PP;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000626
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000627 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000628 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000629 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000630
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000631 // Create and initialize the ASTContext.
632
Ted Kremenek5e14d392011-03-21 18:40:17 +0000633 AST->Ctx = new ASTContext(LangInfo,
634 AST->getSourceManager(),
635 *AST->Target,
636 PP.getIdentifierTable(),
637 PP.getSelectorTable(),
638 PP.getBuiltinInfo(),
639 /* size_reserve = */0);
640 ASTContext &Context = *AST->Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000641
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000642 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Sebastian Redl2c499f62010-08-18 23:56:43 +0000644 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000645 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000646 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000647 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000648 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000649
650 // Unregister the cleanup for ASTReader. It will get cleaned up
651 // by the ASTUnit cleanup.
652 ReaderCleanup.unregister();
653
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000654 Context.setExternalSource(Source);
655
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000656 // Create an AST consumer, even though it isn't used.
657 AST->Consumer.reset(new ASTConsumer);
658
Sebastian Redl2c499f62010-08-18 23:56:43 +0000659 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000660 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
661 AST->TheSema->Initialize();
662 ReaderPtr->InitializeSema(*AST->TheSema);
663
Mike Stump11289f42009-09-09 15:08:12 +0000664 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000665}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000666
667namespace {
668
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000669/// \brief Preprocessor callback class that updates a hash value with the names
670/// of all macros that have been defined by the translation unit.
671class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
672 unsigned &Hash;
673
674public:
675 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
676
677 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
678 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
679 }
680};
681
682/// \brief Add the given declaration to the hash of all top-level entities.
683void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
684 if (!D)
685 return;
686
687 DeclContext *DC = D->getDeclContext();
688 if (!DC)
689 return;
690
691 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
692 return;
693
694 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
695 if (ND->getIdentifier())
696 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
697 else if (DeclarationName Name = ND->getDeclName()) {
698 std::string NameStr = Name.getAsString();
699 Hash = llvm::HashString(NameStr, Hash);
700 }
701 return;
702 }
703
704 if (ObjCForwardProtocolDecl *Forward
705 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
706 for (ObjCForwardProtocolDecl::protocol_iterator
707 P = Forward->protocol_begin(),
708 PEnd = Forward->protocol_end();
709 P != PEnd; ++P)
710 AddTopLevelDeclarationToHash(*P, Hash);
711 return;
712 }
713
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000714 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000715 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
716 I != IEnd; ++I)
717 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
718 return;
719 }
720}
721
Daniel Dunbar644dca02009-12-04 08:17:33 +0000722class TopLevelDeclTrackerConsumer : public ASTConsumer {
723 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000724 unsigned &Hash;
725
Daniel Dunbar644dca02009-12-04 08:17:33 +0000726public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000727 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
728 : Unit(_Unit), Hash(Hash) {
729 Hash = 0;
730 }
731
Daniel Dunbar644dca02009-12-04 08:17:33 +0000732 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000733 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
734 Decl *D = *it;
735 // FIXME: Currently ObjC method declarations are incorrectly being
736 // reported as top-level declarations, even though their DeclContext
737 // is the containing ObjC @interface/@implementation. This is a
738 // fundamental problem in the parser right now.
739 if (isa<ObjCMethodDecl>(D))
740 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000741
742 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000743 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000744 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000745 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000746
747 // We're not interested in "interesting" decls.
748 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000749};
750
751class TopLevelDeclTrackerAction : public ASTFrontendAction {
752public:
753 ASTUnit &Unit;
754
Daniel Dunbar764c0822009-12-01 09:51:01 +0000755 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000756 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000757 CI.getPreprocessor().addPPCallbacks(
758 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
759 return new TopLevelDeclTrackerConsumer(Unit,
760 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000761 }
762
763public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000764 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
765
Daniel Dunbar764c0822009-12-01 09:51:01 +0000766 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000767 virtual bool usesCompleteTranslationUnit() {
768 return Unit.isCompleteTranslationUnit();
769 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000770};
771
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000772class PrecompilePreambleConsumer : public PCHGenerator,
773 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000774 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000775 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000776 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000777
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000778public:
779 PrecompilePreambleConsumer(ASTUnit &Unit,
780 const Preprocessor &PP, bool Chaining,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000781 StringRef isysroot, raw_ostream *Out)
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000782 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
783 Hash(Unit.getCurrentTopLevelHashValue()) {
784 Hash = 0;
785 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000786
Douglas Gregore9db88f2010-08-03 19:06:41 +0000787 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000788 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
789 Decl *D = *it;
790 // FIXME: Currently ObjC method declarations are incorrectly being
791 // reported as top-level declarations, even though their DeclContext
792 // is the containing ObjC @interface/@implementation. This is a
793 // fundamental problem in the parser right now.
794 if (isa<ObjCMethodDecl>(D))
795 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000796 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000797 TopLevelDecls.push_back(D);
798 }
799 }
800
801 virtual void HandleTranslationUnit(ASTContext &Ctx) {
802 PCHGenerator::HandleTranslationUnit(Ctx);
803 if (!Unit.getDiagnostics().hasErrorOccurred()) {
804 // Translate the top-level declarations we captured during
805 // parsing into declaration IDs in the precompiled
806 // preamble. This will allow us to deserialize those top-level
807 // declarations when requested.
808 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
809 Unit.addTopLevelDeclFromPreamble(
810 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000811 }
812 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000813
814 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
815 uint64_t Offset) {
816 Unit.addPreprocessedEntityFromPreamble(Offset);
817 }
818
819 virtual ASTSerializationListener *GetASTSerializationListener() {
820 return this;
821 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000822};
823
824class PrecompilePreambleAction : public ASTFrontendAction {
825 ASTUnit &Unit;
826
827public:
828 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
829
830 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000831 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000832 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000833 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000834 raw_ostream *OS = 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000835 bool Chaining;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000836 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
837 OutputFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000838 OS, Chaining))
839 return 0;
840
Douglas Gregorc567ba22011-07-22 16:35:34 +0000841 if (!CI.getFrontendOpts().RelocatablePCH)
842 Sysroot.clear();
843
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000844 CI.getPreprocessor().addPPCallbacks(
845 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000846 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
Douglas Gregorc567ba22011-07-22 16:35:34 +0000847 Sysroot, OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000848 }
849
850 virtual bool hasCodeCompletionSupport() const { return false; }
851 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000852 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000853};
854
Daniel Dunbar764c0822009-12-01 09:51:01 +0000855}
856
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000857/// Parse the source file into a translation unit using the given compiler
858/// invocation, replacing the current translation unit.
859///
860/// \returns True if a failure occurred that causes the ASTUnit not to
861/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000862bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000863 delete SavedMainFileBuffer;
864 SavedMainFileBuffer = 0;
865
Ted Kremenek5e14d392011-03-21 18:40:17 +0000866 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000867 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000868 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000869 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000870
Daniel Dunbar764c0822009-12-01 09:51:01 +0000871 // Create the compiler instance to use for building the AST.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000872 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
873
874 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000875 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
876 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +0000877
Ted Kremenek5e14d392011-03-21 18:40:17 +0000878 Clang->setInvocation(&*Invocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +0000879 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000880
Douglas Gregor8e984da2010-08-04 16:47:14 +0000881 // Set up diagnostics, capturing any diagnostics that would
882 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000883 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000884
Daniel Dunbar764c0822009-12-01 09:51:01 +0000885 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000886 Clang->getTargetOpts().Features = TargetFeatures;
887 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +0000888 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +0000889 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000890 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000891 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000892 }
893
Daniel Dunbar764c0822009-12-01 09:51:01 +0000894 // Inform the target of the language options.
895 //
896 // FIXME: We shouldn't need to do this, the target should be immutable once
897 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000898 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000899
Ted Kremenek84de4a12011-03-21 18:40:07 +0000900 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000901 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000902 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000903 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000904 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000905 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000906
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000907 // Configure the various subsystems.
908 // FIXME: Should we retain the previous file manager?
Ted Kremenek84de4a12011-03-21 18:40:07 +0000909 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000910 FileMgr = new FileManager(FileSystemOpts);
911 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000912 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000913 Ctx = 0;
914 PP = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000915
916 // Clear out old caches and data.
917 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000918 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000919 CleanTemporaryFiles();
920 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000921
Douglas Gregor7b02b582010-08-20 00:02:33 +0000922 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000923 StoredDiagnostics.erase(
924 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
925 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000926 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000927 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000928 }
929
Daniel Dunbar764c0822009-12-01 09:51:01 +0000930 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000931 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000932
Daniel Dunbar764c0822009-12-01 09:51:01 +0000933 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000934 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000935
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000936 // If the main file has been overridden due to the use of a preamble,
937 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000938 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthde81fc82011-07-14 09:02:10 +0000939 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
940 = NestedMacroExpansions;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000941 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000942 if (OverrideMainBuffer) {
943 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
944 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
945 PreprocessorOpts.PrecompiledPreambleBytes.second
946 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000947 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000948 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000949 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000950
Douglas Gregord9a30af2010-08-02 20:51:39 +0000951 // The stored diagnostic has the old source manager in it; update
952 // the locations to refer into the new source manager. Since we've
953 // been careful to make sure that the source manager's state
954 // before and after are identical, so that we can reuse the source
955 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000956 for (unsigned I = NumStoredDiagnosticsFromDriver,
957 N = StoredDiagnostics.size();
958 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000959 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
960 getSourceManager());
961 StoredDiagnostics[I].setLocation(Loc);
962 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000963
964 // Keep track of the override buffer;
965 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000966 } else {
967 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
968 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000969 }
970
Ted Kremenek022a4902011-03-22 01:15:24 +0000971 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
972 new TopLevelDeclTrackerAction(*this));
973
974 // Recover resources if we crash before exiting this method.
975 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
976 ActCleanup(Act.get());
977
Ted Kremenek84de4a12011-03-21 18:40:07 +0000978 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
979 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000980 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +0000981
982 if (OverrideMainBuffer) {
Jonathan D. Turner2214acd2011-07-22 17:25:03 +0000983 std::string ModName = PreambleFile;
Douglas Gregor925296b2011-07-19 16:10:42 +0000984 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
985 getSourceManager(), PreambleDiagnostics,
986 StoredDiagnostics);
987 }
988
Daniel Dunbar644dca02009-12-04 08:17:33 +0000989 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000990
Ted Kremenek5e14d392011-03-21 18:40:17 +0000991 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000992 TheSema.reset(Clang->takeSema());
993 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +0000994 Ctx = &Clang->getASTContext();
995 PP = &Clang->getPreprocessor();
996 Clang->setSourceManager(0);
997 Clang->setFileManager(0);
998 Target = &Clang->getTarget();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000999
Daniel Dunbar644dca02009-12-04 08:17:33 +00001000 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001001
1002 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +00001003 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001004 PreprocessorOpts.eraseRemappedFile(
1005 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001006 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
1007 }
1008
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001009 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001010
Daniel Dunbar764c0822009-12-01 09:51:01 +00001011error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001012 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001013 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001014 PreprocessorOpts.eraseRemappedFile(
1015 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001016 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +00001017 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001018 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001019 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001020
Douglas Gregorefc46952010-10-12 16:25:54 +00001021 StoredDiagnostics.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001022 return true;
1023}
1024
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001025/// \brief Simple function to retrieve a path for a preamble precompiled header.
1026static std::string GetPreamblePCHPath() {
1027 // FIXME: This is lame; sys::Path should provide this function (in particular,
1028 // it should know how to find the temporary files dir).
1029 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001030 // FIXME: This is a hack so that we can override the preamble file during
1031 // crash-recovery testing, which is the only case where the preamble files
1032 // are not necessarily cleaned up.
1033 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1034 if (TmpFile)
1035 return TmpFile;
1036
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001037 std::string Error;
1038 const char *TmpDir = ::getenv("TMPDIR");
1039 if (!TmpDir)
1040 TmpDir = ::getenv("TEMP");
1041 if (!TmpDir)
1042 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001043#ifdef LLVM_ON_WIN32
1044 if (!TmpDir)
1045 TmpDir = ::getenv("USERPROFILE");
1046#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001047 if (!TmpDir)
1048 TmpDir = "/tmp";
1049 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001050 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001051 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001052 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001053 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001054 return std::string();
1055
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001056 return P.str();
1057}
1058
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001059/// \brief Compute the preamble for the main file, providing the source buffer
1060/// that corresponds to the main file along with a pair (bytes, start-of-line)
1061/// that describes the preamble.
1062std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001063ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1064 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001065 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001066 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001067 CreatedBuffer = false;
1068
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001069 // Try to determine if the main file has been remapped, either from the
1070 // command line (to another file) or directly through the compiler invocation
1071 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001072 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001073 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1074 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1075 // Check whether there is a file-file remapping of the main file
1076 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001077 M = PreprocessorOpts.remapped_file_begin(),
1078 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001079 M != E;
1080 ++M) {
1081 llvm::sys::PathWithStatus MPath(M->first);
1082 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1083 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1084 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001085 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001086 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001087 CreatedBuffer = false;
1088 }
1089
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001090 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001091 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001092 return std::make_pair((llvm::MemoryBuffer*)0,
1093 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001094 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001095 }
1096 }
1097 }
1098
1099 // Check whether there is a file-buffer remapping. It supercedes the
1100 // file-file remapping.
1101 for (PreprocessorOptions::remapped_file_buffer_iterator
1102 M = PreprocessorOpts.remapped_file_buffer_begin(),
1103 E = PreprocessorOpts.remapped_file_buffer_end();
1104 M != E;
1105 ++M) {
1106 llvm::sys::PathWithStatus MPath(M->first);
1107 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1108 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1109 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001110 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001111 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001112 CreatedBuffer = false;
1113 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001114
Douglas Gregor4dde7492010-07-23 23:58:40 +00001115 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001116 }
1117 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001118 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001119 }
1120
1121 // If the main source file was not remapped, load it now.
1122 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001123 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001124 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001125 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001126
1127 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001128 }
1129
Douglas Gregor028d3e42010-08-09 20:45:32 +00001130 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001131}
1132
Douglas Gregor6481ef12010-07-24 00:38:13 +00001133static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001134 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001135 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001136 llvm::MemoryBuffer *Result
1137 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1138 memcpy(const_cast<char*>(Result->getBufferStart()),
1139 Old->getBufferStart(), Old->getBufferSize());
1140 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001141 ' ', NewSize - Old->getBufferSize() - 1);
1142 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001143
Douglas Gregor6481ef12010-07-24 00:38:13 +00001144 return Result;
1145}
1146
Douglas Gregor4dde7492010-07-23 23:58:40 +00001147/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1148/// the source file.
1149///
1150/// This routine will compute the preamble of the main source file. If a
1151/// non-trivial preamble is found, it will precompile that preamble into a
1152/// precompiled header so that the precompiled preamble can be used to reduce
1153/// reparsing time. If a precompiled preamble has already been constructed,
1154/// this routine will determine if it is still valid and, if so, avoid
1155/// rebuilding the precompiled preamble.
1156///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001157/// \param AllowRebuild When true (the default), this routine is
1158/// allowed to rebuild the precompiled preamble if it is found to be
1159/// out-of-date.
1160///
1161/// \param MaxLines When non-zero, the maximum number of lines that
1162/// can occur within the preamble.
1163///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001164/// \returns If the precompiled preamble can be used, returns a newly-allocated
1165/// buffer that should be used in place of the main file when doing so.
1166/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001167llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001168 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001169 bool AllowRebuild,
1170 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001171
1172 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1173 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1174 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001175 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001176 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001177
1178 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001179 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001180 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001181
Douglas Gregor925296b2011-07-19 16:10:42 +00001182 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor3edb1672010-11-16 20:45:51 +00001183 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1184 if (CreatedPreambleBuffer)
1185 OwnedPreambleBuffer.reset(NewPreamble.first);
1186
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001187 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001188 // We couldn't find a preamble in the main source. Clear out the current
1189 // preamble, if we have one. It's obviously no good any more.
1190 Preamble.clear();
1191 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001192 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001193 PreambleFile.clear();
1194 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001195
1196 // The next time we actually see a preamble, precompile it.
1197 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001198 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001199 }
1200
1201 if (!Preamble.empty()) {
1202 // We've previously computed a preamble. Check whether we have the same
1203 // preamble now that we did before, and that there's enough space in
1204 // the main-file buffer within the precompiled preamble to fit the
1205 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001206 if (Preamble.size() == NewPreamble.second.first &&
1207 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001208 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001209 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001210 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211 // The preamble has not changed. We may be able to re-use the precompiled
1212 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001213
Douglas Gregor0e119552010-07-31 00:40:00 +00001214 // Check that none of the files used by the preamble have changed.
1215 bool AnyFileChanged = false;
1216
1217 // First, make a record of those files that have been overridden via
1218 // remapping or unsaved_files.
1219 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1220 for (PreprocessorOptions::remapped_file_iterator
1221 R = PreprocessorOpts.remapped_file_begin(),
1222 REnd = PreprocessorOpts.remapped_file_end();
1223 !AnyFileChanged && R != REnd;
1224 ++R) {
1225 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001226 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001227 // If we can't stat the file we're remapping to, assume that something
1228 // horrible happened.
1229 AnyFileChanged = true;
1230 break;
1231 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001232
Douglas Gregor0e119552010-07-31 00:40:00 +00001233 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1234 StatBuf.st_mtime);
1235 }
1236 for (PreprocessorOptions::remapped_file_buffer_iterator
1237 R = PreprocessorOpts.remapped_file_buffer_begin(),
1238 REnd = PreprocessorOpts.remapped_file_buffer_end();
1239 !AnyFileChanged && R != REnd;
1240 ++R) {
1241 // FIXME: Should we actually compare the contents of file->buffer
1242 // remappings?
1243 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1244 0);
1245 }
1246
1247 // Check whether anything has changed.
1248 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1249 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1250 !AnyFileChanged && F != FEnd;
1251 ++F) {
1252 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1253 = OverriddenFiles.find(F->first());
1254 if (Overridden != OverriddenFiles.end()) {
1255 // This file was remapped; check whether the newly-mapped file
1256 // matches up with the previous mapping.
1257 if (Overridden->second != F->second)
1258 AnyFileChanged = true;
1259 continue;
1260 }
1261
1262 // The file was not remapped; check whether it has changed on disk.
1263 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001264 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001265 // If we can't stat the file, assume that something horrible happened.
1266 AnyFileChanged = true;
1267 } else if (StatBuf.st_size != F->second.first ||
1268 StatBuf.st_mtime != F->second.second)
1269 AnyFileChanged = true;
1270 }
1271
1272 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001273 // Okay! We can re-use the precompiled preamble.
1274
1275 // Set the state of the diagnostic object to mimic its state
1276 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001277 // FIXME: This won't catch any #pragma push warning changes that
1278 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001279 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001280 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001281 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001282 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001283
1284 // Create a version of the main file buffer that is padded to
1285 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001286 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001287 PreambleReservedSize,
1288 FrontendOpts.Inputs[0].second);
1289 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001290 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001291
1292 // If we aren't allowed to rebuild the precompiled preamble, just
1293 // return now.
1294 if (!AllowRebuild)
1295 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001296
Douglas Gregor4dde7492010-07-23 23:58:40 +00001297 // We can't reuse the previously-computed preamble. Build a new one.
1298 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001299 PreambleDiagnostics.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001300 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001301 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001302 } else if (!AllowRebuild) {
1303 // We aren't allowed to rebuild the precompiled preamble; just
1304 // return now.
1305 return 0;
1306 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001307
1308 // If the preamble rebuild counter > 1, it's because we previously
1309 // failed to build a preamble and we're not yet ready to try
1310 // again. Decrement the counter and return a failure.
1311 if (PreambleRebuildCounter > 1) {
1312 --PreambleRebuildCounter;
1313 return 0;
1314 }
1315
Douglas Gregore10f0e52010-09-11 17:56:52 +00001316 // Create a temporary file for the precompiled preamble. In rare
1317 // circumstances, this can fail.
1318 std::string PreamblePCHPath = GetPreamblePCHPath();
1319 if (PreamblePCHPath.empty()) {
1320 // Try again next time.
1321 PreambleRebuildCounter = 1;
1322 return 0;
1323 }
1324
Douglas Gregor4dde7492010-07-23 23:58:40 +00001325 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001326 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001327 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001328
1329 // Create a new buffer that stores the preamble. The buffer also contains
1330 // extra space for the original contents of the file (which will be present
1331 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001332 // grows.
1333 PreambleReservedSize = NewPreamble.first->getBufferSize();
1334 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001335 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001336 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001337 PreambleReservedSize *= 2;
1338
Douglas Gregord9a30af2010-08-02 20:51:39 +00001339 // Save the preamble text for later; we'll need to compare against it for
1340 // subsequent reparses.
1341 Preamble.assign(NewPreamble.first->getBufferStart(),
1342 NewPreamble.first->getBufferStart()
1343 + NewPreamble.second.first);
1344 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1345
Douglas Gregora0734c52010-08-19 01:33:06 +00001346 delete PreambleBuffer;
1347 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001348 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001349 FrontendOpts.Inputs[0].second);
1350 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001351 NewPreamble.first->getBufferStart(), Preamble.size());
1352 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001353 ' ', PreambleReservedSize - Preamble.size() - 1);
1354 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001355
1356 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001357 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001358 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1359
1360 // Tell the compiler invocation to generate a temporary precompiled header.
1361 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001362 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001363 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001364 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001365 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1366 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001367
1368 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001369 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1370
1371 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001372 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1373 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001374
Douglas Gregor3cc15812011-07-01 18:22:13 +00001375 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00001376 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001377
Douglas Gregor8e984da2010-08-04 16:47:14 +00001378 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001379 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001380
1381 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001382 Clang->getTargetOpts().Features = TargetFeatures;
1383 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1384 Clang->getTargetOpts()));
1385 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001386 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1387 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001388 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001389 PreprocessorOpts.eraseRemappedFile(
1390 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001391 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001392 }
1393
1394 // Inform the target of the language options.
1395 //
1396 // FIXME: We shouldn't need to do this, the target should be immutable once
1397 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001398 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001399
Ted Kremenek84de4a12011-03-21 18:40:07 +00001400 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001401 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001402 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001403 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001404 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001405 "IR inputs not support here!");
1406
1407 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001408 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001409 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001410 StoredDiagnostics.erase(
1411 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1412 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001413 TopLevelDecls.clear();
1414 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001415 PreprocessedEntities.clear();
1416 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001417
1418 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001419 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001420
1421 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001422 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001423 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001424
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001425 llvm::OwningPtr<PrecompilePreambleAction> Act;
1426 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001427 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1428 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001429 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1430 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001431 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001432 PreprocessorOpts.eraseRemappedFile(
1433 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001434 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001435 }
1436
1437 Act->Execute();
1438 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001439
Douglas Gregore9db88f2010-08-03 19:06:41 +00001440 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001441 // There were errors parsing the preamble, so no precompiled header was
1442 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001443 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001444 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1445 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001446 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001447 PreprocessedEntities.clear();
1448 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001449 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001450 PreprocessorOpts.eraseRemappedFile(
1451 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001452 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001453 }
1454
Douglas Gregor925296b2011-07-19 16:10:42 +00001455 // Transfer any diagnostics generated when parsing the preamble into the set
1456 // of preamble diagnostics.
1457 PreambleDiagnostics.clear();
1458 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1459 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1460 StoredDiagnostics.end());
1461 StoredDiagnostics.erase(
1462 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1463 StoredDiagnostics.end());
1464
Douglas Gregor4dde7492010-07-23 23:58:40 +00001465 // Keep track of the preamble we precompiled.
1466 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001467 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001468
1469 // Keep track of all of the files that the source manager knows about,
1470 // so we can verify whether they have changed or not.
1471 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001472 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001473 const llvm::MemoryBuffer *MainFileBuffer
1474 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1475 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1476 FEnd = SourceMgr.fileinfo_end();
1477 F != FEnd;
1478 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001479 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001480 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1481 continue;
1482
1483 FilesInPreamble[File->getName()]
1484 = std::make_pair(F->second->getSize(), File->getModificationTime());
1485 }
1486
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001487 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001488 PreprocessorOpts.eraseRemappedFile(
1489 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001490
1491 // If the hash of top-level entities differs from the hash of the top-level
1492 // entities the last time we rebuilt the preamble, clear out the completion
1493 // cache.
1494 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1495 CompletionCacheTopLevelHashValue = 0;
1496 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1497 }
1498
Douglas Gregor6481ef12010-07-24 00:38:13 +00001499 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001500 PreambleReservedSize,
1501 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001502}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001503
Douglas Gregore9db88f2010-08-03 19:06:41 +00001504void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1505 std::vector<Decl *> Resolved;
1506 Resolved.reserve(TopLevelDeclsInPreamble.size());
1507 ExternalASTSource &Source = *getASTContext().getExternalSource();
1508 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1509 // Resolve the declaration ID to an actual declaration, possibly
1510 // deserializing the declaration in the process.
1511 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1512 if (D)
1513 Resolved.push_back(D);
1514 }
1515 TopLevelDeclsInPreamble.clear();
1516 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1517}
1518
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001519void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1520 if (!PP)
1521 return;
1522
1523 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1524 if (!PPRec)
1525 return;
1526
1527 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1528 if (!External)
1529 return;
1530
1531 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1532 if (PreprocessedEntity *PE
Douglas Gregor46c50012011-02-11 19:46:30 +00001533 = External->ReadPreprocessedEntityAtOffset(
1534 PreprocessedEntitiesInPreamble[I]))
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001535 PreprocessedEntities.push_back(PE);
1536 }
1537
1538 if (PreprocessedEntities.empty())
1539 return;
1540
1541 PreprocessedEntities.insert(PreprocessedEntities.end(),
1542 PPRec->begin(true), PPRec->end(true));
1543}
1544
1545ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1546 if (!PreprocessedEntitiesInPreamble.empty() &&
1547 PreprocessedEntities.empty())
1548 RealizePreprocessedEntitiesFromPreamble();
1549
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001550 return PreprocessedEntities.begin();
1551}
1552
1553ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1554 if (!PreprocessedEntitiesInPreamble.empty() &&
1555 PreprocessedEntities.empty())
1556 RealizePreprocessedEntitiesFromPreamble();
Douglas Gregor4a9c39a2011-07-21 00:47:40 +00001557
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001558 return PreprocessedEntities.end();
1559}
1560
Douglas Gregore9db88f2010-08-03 19:06:41 +00001561unsigned ASTUnit::getMaxPCHLevel() const {
1562 if (!getOnlyLocalDecls())
1563 return Decl::MaxPCHLevel;
1564
Sebastian Redl009e7f22010-10-05 16:15:19 +00001565 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001566}
1567
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001568StringRef ASTUnit::getMainFileName() const {
Douglas Gregor16896c42010-10-28 15:44:59 +00001569 return Invocation->getFrontendOpts().Inputs[0].second;
1570}
1571
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001572ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1573 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1574 llvm::OwningPtr<ASTUnit> AST;
1575 AST.reset(new ASTUnit(false));
1576 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1577 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001578 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001579 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001580 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1581 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001582
1583 return AST.take();
1584}
1585
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001586ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1587 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1588 ASTFrontendAction *Action) {
1589 assert(CI && "A CompilerInvocation is required");
1590
1591 // Create the AST unit.
1592 llvm::OwningPtr<ASTUnit> AST;
1593 AST.reset(new ASTUnit(false));
1594 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1595 AST->Diagnostics = Diags;
1596 AST->OnlyLocalDecls = false;
1597 AST->CaptureDiagnostics = false;
1598 AST->CompleteTranslationUnit = Action ? Action->usesCompleteTranslationUnit()
1599 : true;
1600 AST->ShouldCacheCodeCompletionResults = false;
1601 AST->Invocation = CI;
1602
1603 // Recover resources if we crash before exiting this method.
1604 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1605 ASTUnitCleanup(AST.get());
1606 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1607 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1608 DiagCleanup(Diags.getPtr());
1609
1610 // We'll manage file buffers ourselves.
1611 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1612 CI->getFrontendOpts().DisableFree = false;
1613 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1614
1615 // Save the target features.
1616 AST->TargetFeatures = CI->getTargetOpts().Features;
1617
1618 // Create the compiler instance to use for building the AST.
1619 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1620
1621 // Recover resources if we crash before exiting this method.
1622 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1623 CICleanup(Clang.get());
1624
1625 Clang->setInvocation(CI);
1626 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1627
1628 // Set up diagnostics, capturing any diagnostics that would
1629 // otherwise be dropped.
1630 Clang->setDiagnostics(&AST->getDiagnostics());
1631
1632 // Create the target instance.
1633 Clang->getTargetOpts().Features = AST->TargetFeatures;
1634 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1635 Clang->getTargetOpts()));
1636 if (!Clang->hasTarget())
1637 return 0;
1638
1639 // Inform the target of the language options.
1640 //
1641 // FIXME: We shouldn't need to do this, the target should be immutable once
1642 // created. This complexity should be lifted elsewhere.
1643 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1644
1645 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1646 "Invocation must have exactly one source file!");
1647 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1648 "FIXME: AST inputs not yet supported here!");
1649 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1650 "IR inputs not supported here!");
1651
1652 // Configure the various subsystems.
1653 AST->FileSystemOpts = Clang->getFileSystemOpts();
1654 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1655 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1656 AST->TheSema.reset();
1657 AST->Ctx = 0;
1658 AST->PP = 0;
1659
1660 // Create a file manager object to provide access to and cache the filesystem.
1661 Clang->setFileManager(&AST->getFileManager());
1662
1663 // Create the source manager.
1664 Clang->setSourceManager(&AST->getSourceManager());
1665
1666 ASTFrontendAction *Act = Action;
1667
1668 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1669 if (!Act) {
1670 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1671 Act = TrackerAct.get();
1672 }
1673
1674 // Recover resources if we crash before exiting this method.
1675 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1676 ActCleanup(TrackerAct.get());
1677
1678 if (!Act->BeginSourceFile(*Clang.get(),
1679 Clang->getFrontendOpts().Inputs[0].second,
1680 Clang->getFrontendOpts().Inputs[0].first))
1681 return 0;
1682
1683 Act->Execute();
1684
1685 // Steal the created target, context, and preprocessor.
1686 AST->TheSema.reset(Clang->takeSema());
1687 AST->Consumer.reset(Clang->takeASTConsumer());
1688 AST->Ctx = &Clang->getASTContext();
1689 AST->PP = &Clang->getPreprocessor();
1690 Clang->setSourceManager(0);
1691 Clang->setFileManager(0);
1692 AST->Target = &Clang->getTarget();
1693
1694 Act->EndSourceFile();
1695
1696 return AST.take();
1697}
1698
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001699bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1700 if (!Invocation)
1701 return true;
1702
1703 // We'll manage file buffers ourselves.
1704 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1705 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001706 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001707
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001708 // Save the target features.
1709 TargetFeatures = Invocation->getTargetOpts().Features;
1710
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001711 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001712 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001713 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001714 OverrideMainBuffer
1715 = getMainBufferWithPrecompiledPreamble(*Invocation);
1716 }
1717
Douglas Gregor16896c42010-10-28 15:44:59 +00001718 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001719 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001720
Ted Kremenek022a4902011-03-22 01:15:24 +00001721 // Recover resources if we crash before exiting this method.
1722 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1723 MemBufferCleanup(OverrideMainBuffer);
1724
Douglas Gregor16896c42010-10-28 15:44:59 +00001725 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001726}
1727
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001728ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1729 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1730 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001731 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001732 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001733 bool CompleteTranslationUnit,
Douglas Gregor998caea2011-05-06 16:33:08 +00001734 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001735 bool NestedMacroExpansions) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001736 // Create the AST unit.
1737 llvm::OwningPtr<ASTUnit> AST;
1738 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001739 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001740 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001741 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001742 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001743 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001744 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001745 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001746 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001747
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001748 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001749 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1750 ASTUnitCleanup(AST.get());
1751 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1752 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1753 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001754
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001755 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001756}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001757
1758ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1759 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001760 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001761 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001762 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001763 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001764 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001765 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001766 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001767 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001768 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001769 bool CacheCodeCompletionResults,
1770 bool CXXPrecompilePreamble,
Douglas Gregor998caea2011-05-06 16:33:08 +00001771 bool CXXChainedPCH,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001772 bool NestedMacroExpansions) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001773 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001774 // No diagnostics engine was provided, so create our own diagnostics object
1775 // with the default options.
1776 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001777 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1778 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001779 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001780
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001781 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001782
Ted Kremenek5e14d392011-03-21 18:40:17 +00001783 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001784
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001785 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001786
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001787 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001788 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001789
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001790 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001791 llvm::makeArrayRef(ArgBegin, ArgEnd),
1792 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001793 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001794 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001795 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001796
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001797 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001798 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1799 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1800 if (const llvm::MemoryBuffer *
1801 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1802 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1803 } else {
1804 const char *fname = fileOrBuf.get<const char *>();
1805 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1806 }
1807 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001808 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1809 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001810
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001811 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001812 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001813
Douglas Gregorf5a18542010-10-27 17:24:53 +00001814 // Check whether we should precompile the preamble and/or use chained PCH.
1815 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1816 if (CI->getLangOpts().CPlusPlus) {
1817 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1818
1819 if (PrecompilePreamble && !CXXChainedPCH &&
1820 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1821 PrecompilePreamble = false;
1822 }
1823
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001824 // Create the AST unit.
1825 llvm::OwningPtr<ASTUnit> AST;
1826 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001827 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001828 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001829
1830 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001831 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001832 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001833 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001834 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1835 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1836 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001837 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001838 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001839 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001840
1841 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001842 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1843 ASTUnitCleanup(AST.get());
1844 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1845 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1846 CICleanup(CI.getPtr());
1847 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1848 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1849 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001850
Chris Lattner5159f612010-11-23 08:35:12 +00001851 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001852}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001853
1854bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001855 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001856 return true;
1857
Douglas Gregor16896c42010-10-28 15:44:59 +00001858 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001859 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001860
Douglas Gregor0e119552010-07-31 00:40:00 +00001861 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001862 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001863 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001864 for (PreprocessorOptions::remapped_file_buffer_iterator
1865 R = PPOpts.remapped_file_buffer_begin(),
1866 REnd = PPOpts.remapped_file_buffer_end();
1867 R != REnd;
1868 ++R) {
1869 delete R->second;
1870 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001871 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001872 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1873 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1874 if (const llvm::MemoryBuffer *
1875 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1876 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1877 memBuf);
1878 } else {
1879 const char *fname = fileOrBuf.get<const char *>();
1880 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1881 fname);
1882 }
1883 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001884
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001885 // If we have a preamble file lying around, or if we might try to
1886 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001887 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001888 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001889 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001890
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001891 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001892 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001893 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001894 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1895 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001896
Douglas Gregor4dde7492010-07-23 23:58:40 +00001897 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001898 bool Result = Parse(OverrideMainBuffer);
1899
1900 // If we're caching global code-completion results, and the top-level
1901 // declarations have changed, clear out the code-completion cache.
1902 if (!Result && ShouldCacheCodeCompletionResults &&
1903 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1904 CacheCodeCompletionResults();
1905
Douglas Gregor4dde7492010-07-23 23:58:40 +00001906 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001907}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001908
Douglas Gregorb14904c2010-08-13 22:48:40 +00001909//----------------------------------------------------------------------------//
1910// Code completion
1911//----------------------------------------------------------------------------//
1912
1913namespace {
1914 /// \brief Code completion consumer that combines the cached code-completion
1915 /// results from an ASTUnit with the code-completion results provided to it,
1916 /// then passes the result on to
1917 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00001918 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001919 ASTUnit &AST;
1920 CodeCompleteConsumer &Next;
1921
1922 public:
1923 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001924 bool IncludeMacros, bool IncludeCodePatterns,
1925 bool IncludeGlobals)
1926 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001927 Next.isOutputBinary()), AST(AST), Next(Next)
1928 {
1929 // Compute the set of contexts in which we will look when we don't have
1930 // any information about the specific context.
1931 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00001932 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1933 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1934 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1935 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1936 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1937 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1938 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1939 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1940 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1941 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1942 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1943 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1944 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001945
Douglas Gregorb14904c2010-08-13 22:48:40 +00001946 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00001947 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1948 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1949 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00001950 }
1951
1952 virtual void ProcessCodeCompleteResults(Sema &S,
1953 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001954 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001955 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001956
1957 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1958 OverloadCandidate *Candidates,
1959 unsigned NumCandidates) {
1960 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1961 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001962
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001963 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001964 return Next.getAllocator();
1965 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001966 };
1967}
Douglas Gregord46cf182010-08-16 20:01:48 +00001968
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001969/// \brief Helper function that computes which global names are hidden by the
1970/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001971static void CalculateHiddenNames(const CodeCompletionContext &Context,
1972 CodeCompletionResult *Results,
1973 unsigned NumResults,
1974 ASTContext &Ctx,
1975 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001976 bool OnlyTagNames = false;
1977 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001978 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001979 case CodeCompletionContext::CCC_TopLevel:
1980 case CodeCompletionContext::CCC_ObjCInterface:
1981 case CodeCompletionContext::CCC_ObjCImplementation:
1982 case CodeCompletionContext::CCC_ObjCIvarList:
1983 case CodeCompletionContext::CCC_ClassStructUnion:
1984 case CodeCompletionContext::CCC_Statement:
1985 case CodeCompletionContext::CCC_Expression:
1986 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001987 case CodeCompletionContext::CCC_DotMemberAccess:
1988 case CodeCompletionContext::CCC_ArrowMemberAccess:
1989 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001990 case CodeCompletionContext::CCC_Namespace:
1991 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001992 case CodeCompletionContext::CCC_Name:
1993 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001994 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001995 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001996 break;
1997
1998 case CodeCompletionContext::CCC_EnumTag:
1999 case CodeCompletionContext::CCC_UnionTag:
2000 case CodeCompletionContext::CCC_ClassOrStructTag:
2001 OnlyTagNames = true;
2002 break;
2003
2004 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002005 case CodeCompletionContext::CCC_MacroName:
2006 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002007 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002008 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002009 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002010 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002011 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002012 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002013 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002014 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2015 case CodeCompletionContext::CCC_ObjCClassMessage:
2016 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002017 // We're looking for nothing, or we're looking for names that cannot
2018 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002019 return;
2020 }
2021
John McCall276321a2010-08-25 06:19:51 +00002022 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002023 for (unsigned I = 0; I != NumResults; ++I) {
2024 if (Results[I].Kind != Result::RK_Declaration)
2025 continue;
2026
2027 unsigned IDNS
2028 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2029
2030 bool Hiding = false;
2031 if (OnlyTagNames)
2032 Hiding = (IDNS & Decl::IDNS_Tag);
2033 else {
2034 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002035 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2036 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002037 if (Ctx.getLangOptions().CPlusPlus)
2038 HiddenIDNS |= Decl::IDNS_Tag;
2039 Hiding = (IDNS & HiddenIDNS);
2040 }
2041
2042 if (!Hiding)
2043 continue;
2044
2045 DeclarationName Name = Results[I].Declaration->getDeclName();
2046 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2047 HiddenNames.insert(Identifier->getName());
2048 else
2049 HiddenNames.insert(Name.getAsString());
2050 }
2051}
2052
2053
Douglas Gregord46cf182010-08-16 20:01:48 +00002054void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2055 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002056 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002057 unsigned NumResults) {
2058 // Merge the results we were given with the results we cached.
2059 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002060 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00002061 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002062 : (1 << (Context.getKind() - 1)));
2063
2064 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002065 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002066 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002067 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002068 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002069 C = AST.cached_completion_begin(),
2070 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002071 C != CEnd; ++C) {
2072 // If the context we are in matches any of the contexts we are
2073 // interested in, we'll add this result.
2074 if ((C->ShowInContexts & InContexts) == 0)
2075 continue;
2076
2077 // If we haven't added any results previously, do so now.
2078 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002079 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2080 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002081 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2082 AddedResult = true;
2083 }
2084
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002085 // Determine whether this global completion result is hidden by a local
2086 // completion result. If so, skip it.
2087 if (C->Kind != CXCursor_MacroDefinition &&
2088 HiddenNames.count(C->Completion->getTypedText()))
2089 continue;
2090
Douglas Gregord46cf182010-08-16 20:01:48 +00002091 // Adjust priority based on similar type classes.
2092 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002093 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002094 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002095 if (!Context.getPreferredType().isNull()) {
2096 if (C->Kind == CXCursor_MacroDefinition) {
2097 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002098 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00002099 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002100 } else if (C->Type) {
2101 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002102 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002103 Context.getPreferredType().getUnqualifiedType());
2104 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2105 if (ExpectedSTC == C->TypeClass) {
2106 // We know this type is similar; check for an exact match.
2107 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002108 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002109 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002110 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002111 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2112 Priority /= CCF_ExactTypeMatch;
2113 else
2114 Priority /= CCF_SimilarTypeMatch;
2115 }
2116 }
2117 }
2118
Douglas Gregor12785102010-08-24 20:21:13 +00002119 // Adjust the completion string, if required.
2120 if (C->Kind == CXCursor_MacroDefinition &&
2121 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2122 // Create a new code-completion string that just contains the
2123 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002124 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2125 C->Availability);
2126 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002127 CursorKind = CXCursor_NotImplemented;
2128 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002129 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002130 }
2131
Douglas Gregor8850aa32010-08-25 18:03:13 +00002132 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002133 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002134 }
2135
2136 // If we did not add any cached completion results, just forward the
2137 // results we were given to the next consumer.
2138 if (!AddedResult) {
2139 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2140 return;
2141 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002142
Douglas Gregord46cf182010-08-16 20:01:48 +00002143 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2144 AllResults.size());
2145}
2146
2147
2148
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002149void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002150 RemappedFile *RemappedFiles,
2151 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002152 bool IncludeMacros,
2153 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002154 CodeCompleteConsumer &Consumer,
2155 Diagnostic &Diag, LangOptions &LangOpts,
2156 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002157 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2158 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002159 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002160 return;
2161
Douglas Gregor16896c42010-10-28 15:44:59 +00002162 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002163 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002164 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002165
Ted Kremenek5e14d392011-03-21 18:40:17 +00002166 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2167 CCInvocation(new CompilerInvocation(*Invocation));
2168
2169 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2170 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002171
Douglas Gregorb14904c2010-08-13 22:48:40 +00002172 FrontendOpts.ShowMacrosInCodeCompletion
2173 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002174 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002175 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2176 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002177 FrontendOpts.CodeCompletionAt.FileName = File;
2178 FrontendOpts.CodeCompletionAt.Line = Line;
2179 FrontendOpts.CodeCompletionAt.Column = Column;
2180
2181 // Set the language options appropriately.
Ted Kremenek5e14d392011-03-21 18:40:17 +00002182 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002183
Ted Kremenek84de4a12011-03-21 18:40:07 +00002184 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2185
2186 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002187 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2188 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002189
Ted Kremenek5e14d392011-03-21 18:40:17 +00002190 Clang->setInvocation(&*CCInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002191 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002192
2193 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002194 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002195 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002196 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002197 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002198 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002199
2200 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002201 Clang->getTargetOpts().Features = TargetFeatures;
2202 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2203 Clang->getTargetOpts()));
2204 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002205 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002206 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002207 }
2208
2209 // Inform the target of the language options.
2210 //
2211 // FIXME: We shouldn't need to do this, the target should be immutable once
2212 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002213 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002214
Ted Kremenek84de4a12011-03-21 18:40:07 +00002215 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002216 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002217 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002218 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002219 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002220 "IR inputs not support here!");
2221
2222
2223 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002224 Clang->setFileManager(&FileMgr);
2225 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002226
2227 // Remap files.
2228 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002229 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002230 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002231 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2232 if (const llvm::MemoryBuffer *
2233 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2234 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2235 OwnedBuffers.push_back(memBuf);
2236 } else {
2237 const char *fname = fileOrBuf.get<const char *>();
2238 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2239 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002240 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002241
Douglas Gregorb14904c2010-08-13 22:48:40 +00002242 // Use the code completion consumer we were given, but adding any cached
2243 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002244 AugmentedCodeCompleteConsumer *AugmentedConsumer
2245 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2246 FrontendOpts.ShowMacrosInCodeCompletion,
2247 FrontendOpts.ShowCodePatternsInCodeCompletion,
2248 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002249 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002250
Douglas Gregor028d3e42010-08-09 20:45:32 +00002251 // If we have a precompiled preamble, try to use it. We only allow
2252 // the use of the precompiled preamble if we're if the completion
2253 // point is within the main file, after the end of the precompiled
2254 // preamble.
2255 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2256 if (!PreambleFile.empty()) {
2257 using llvm::sys::FileStatus;
2258 llvm::sys::PathWithStatus CompleteFilePath(File);
2259 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2260 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2261 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2262 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00002263 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002264 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002265 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002266 }
2267
2268 // If the main file has been overridden due to the use of a preamble,
2269 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002270 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002271 StoredDiagnostics.insert(StoredDiagnostics.end(),
2272 this->StoredDiagnostics.begin(),
2273 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002274 if (OverrideMainBuffer) {
2275 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2276 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2277 PreprocessorOpts.PrecompiledPreambleBytes.second
2278 = PreambleEndsAtStartOfLine;
2279 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2280 PreprocessorOpts.DisablePCHValidation = true;
2281
Douglas Gregorb97b6662010-08-20 00:59:43 +00002282 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002283 } else {
2284 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2285 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002286 }
2287
Douglas Gregor998caea2011-05-06 16:33:08 +00002288 // Disable the preprocessing record
2289 PreprocessorOpts.DetailedRecord = false;
2290
Douglas Gregor8e984da2010-08-04 16:47:14 +00002291 llvm::OwningPtr<SyntaxOnlyAction> Act;
2292 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002293 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2294 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002295 if (OverrideMainBuffer) {
Jonathan D. Turner2214acd2011-07-22 17:25:03 +00002296 std::string ModName = PreambleFile;
Douglas Gregor925296b2011-07-19 16:10:42 +00002297 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2298 getSourceManager(), PreambleDiagnostics,
2299 StoredDiagnostics);
2300 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002301 Act->Execute();
2302 Act->EndSourceFile();
2303 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002304}
Douglas Gregore9386682010-08-13 05:36:37 +00002305
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002306CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor8a60bbe2011-07-06 17:40:26 +00002307 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor30c80fa2011-07-06 16:43:36 +00002308 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002309
2310 // Write to a temporary file and later rename it to the actual file, to avoid
2311 // possible race conditions.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002312 llvm::SmallString<128> TempPath;
2313 TempPath = File;
2314 TempPath += "-%%%%%%%%";
2315 int fd;
2316 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2317 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002318 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002319
Douglas Gregore9386682010-08-13 05:36:37 +00002320 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2321 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002322 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002323
2324 serialize(Out);
2325 Out.close();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002326 if (Out.has_error())
2327 return CXSaveError_Unknown;
2328
2329 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2330 bool exists;
2331 llvm::sys::fs::remove(TempPath.str(), exists);
2332 return CXSaveError_Unknown;
2333 }
2334
2335 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002336}
2337
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002338bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002339 if (getDiagnostics().hasErrorOccurred())
2340 return true;
2341
Douglas Gregore9386682010-08-13 05:36:37 +00002342 std::vector<unsigned char> Buffer;
2343 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002344 ASTWriter Writer(Stream);
Douglas Gregorc567ba22011-07-22 16:35:34 +00002345 Writer.WriteAST(getSema(), 0, std::string(), "");
Douglas Gregore9386682010-08-13 05:36:37 +00002346
2347 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002348 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002349 OS.write((char *)&Buffer.front(), Buffer.size());
2350
2351 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002352}
Douglas Gregor925296b2011-07-19 16:10:42 +00002353
2354typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2355
2356static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2357 unsigned Raw = L.getRawEncoding();
2358 const unsigned MacroBit = 1U << 31;
2359 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2360 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2361}
2362
2363void ASTUnit::TranslateStoredDiagnostics(
2364 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002365 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002366 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002367 const SmallVectorImpl<StoredDiagnostic> &Diags,
2368 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002369 // The stored diagnostic has the old source manager in it; update
2370 // the locations to refer into the new source manager. We also need to remap
2371 // all the locations to the new view. This includes the diag location, any
2372 // associated source ranges, and the source ranges of associated fix-its.
2373 // FIXME: There should be a cleaner way to do this.
2374
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002375 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002376 Result.reserve(Diags.size());
2377 assert(MMan && "Don't have a module manager");
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00002378 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002379 assert(Mod && "Don't have preamble module");
2380 SLocRemap &Remap = Mod->SLocRemap;
2381 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2382 // Rebuild the StoredDiagnostic.
2383 const StoredDiagnostic &SD = Diags[I];
2384 SourceLocation L = SD.getLocation();
2385 TranslateSLoc(L, Remap);
2386 FullSourceLoc Loc(L, SrcMgr);
2387
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002388 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002389 Ranges.reserve(SD.range_size());
2390 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2391 E = SD.range_end();
2392 I != E; ++I) {
2393 SourceLocation BL = I->getBegin();
2394 TranslateSLoc(BL, Remap);
2395 SourceLocation EL = I->getEnd();
2396 TranslateSLoc(EL, Remap);
2397 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2398 }
2399
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002400 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002401 FixIts.reserve(SD.fixit_size());
2402 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2403 E = SD.fixit_end();
2404 I != E; ++I) {
2405 FixIts.push_back(FixItHint());
2406 FixItHint &FH = FixIts.back();
2407 FH.CodeToInsert = I->CodeToInsert;
2408 SourceLocation BL = I->RemoveRange.getBegin();
2409 TranslateSLoc(BL, Remap);
2410 SourceLocation EL = I->RemoveRange.getEnd();
2411 TranslateSLoc(EL, Remap);
2412 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2413 I->RemoveRange.isTokenRange());
2414 }
2415
2416 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2417 SD.getMessage(), Loc, Ranges, FixIts));
2418 }
2419 Result.swap(Out);
2420}