blob: 6f9b43781419f7a55caf83e3237107f6f7a030da [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-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 Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Douglas Gregor89d99802010-11-30 06:16:57 +000032#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000049#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000050#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000051#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000052#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000053using namespace clang;
54
Douglas Gregor213f18b2010-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 Krameredfb7ec2010-11-09 20:00:56 +000063 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000064 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000065 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000066 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 }
68
Chris Lattner5f9e2722011-07-23 10:55:15 +000069 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000071 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000072 }
73
Douglas Gregor213f18b2010-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 Gregoreababfb2010-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 Gregore3c60a72010-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 Gregor1fd9e0d2010-12-07 00:05:48 +000095static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000096
Douglas Gregor3687e9d2010-04-05 21:10:19 +000097ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +000098 : OnlyLocalDecls(false), CaptureDiagnostics(false),
99 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000100 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000101 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000102 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000103 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +0000104 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000105 ShouldCacheCodeCompletionResults(false),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000106 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000107 CompletionCacheTopLevelHashValue(0),
108 PreambleTopLevelHashValue(0),
109 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000110 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000111 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000112 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000113 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
114 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000115}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000116
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000117ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000118 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000119 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000120 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000121 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-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 Kremenek4f327862011-03-21 18:40:17 +0000127 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-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 Gregor28233422010-07-27 14:52:07 +0000136
137 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000138 delete PreambleBuffer;
139
Douglas Gregor213f18b2010-10-28 15:44:59 +0000140 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000141
142 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000143 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000144 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
145 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000146}
147
148void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000149 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
150 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000151 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000152}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000153
Douglas Gregor8071e422010-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 Gregora5fb7c32010-08-16 23:05:20 +0000157 const LangOptions &LangOpts,
158 bool &IsNestedNameSpecifier) {
159 IsNestedNameSpecifier = false;
160
Douglas Gregor8071e422010-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 Gregor02688102010-09-14 23:59:36 +0000175 | (1 << (CodeCompletionContext::CCC_Type - 1))
176 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-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 Gregor3da626b2011-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 Gregor0f91c8c2011-07-30 06:55:39 +0000189 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-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 Gregora5fb7c32010-08-16 23:05:20 +0000195 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000196 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000197 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-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 Gregor8071e422010-08-15 06:18:01 +0000204 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000205 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000206 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000207 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-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 Gregor02688102010-09-14 23:59:36 +0000212 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-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 Gregor3da626b2011-07-07 16:03:39 +0000216 } else if (isa<ObjCCategoryDecl>(ND)) {
217 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000218 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000219 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000220
221 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000222 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000223 }
224
225 return Contexts;
226}
227
Douglas Gregor87c08a52010-08-13 22:48:40 +0000228void ASTUnit::CacheCodeCompletionResults() {
229 if (!TheSema)
230 return;
231
Douglas Gregor213f18b2010-10-28 15:44:59 +0000232 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000233 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000234
235 // Clear out the previous results.
236 ClearCachedCompletionResults();
237
238 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000239 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000240 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000241 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
242 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000243
244 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000245 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
246
Douglas Gregor87c08a52010-08-13 22:48:40 +0000247 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
248 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000249 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000250 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000251 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000252 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000253 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000254 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000255 Ctx->getLangOptions(),
256 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000257 CachedResult.Priority = Results[I].Priority;
258 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000259 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000260
Douglas Gregorf5586f62010-08-16 18:08:11 +0000261 // Keep track of the type of this completion in an ASTContext-agnostic
262 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000263 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000264 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000265 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-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 Gregorc4421e92010-08-16 16:46:30 +0000283 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000284
Douglas Gregor8071e422010-08-15 06:18:01 +0000285 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-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 Gregor2ccccb32010-08-23 18:23:48 +0000301 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000302 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
303 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-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 Gregor218937c2011-02-01 19:23:04 +0000315 CachedResult.Completion
316 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000317 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-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 Gregor87c08a52010-08-13 22:48:40 +0000325 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 }
327
Douglas Gregor87c08a52010-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 Gregor218937c2011-02-01 19:23:04 +0000336 CachedResult.Completion
337 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000338 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-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 Gregor1fbb4472010-08-24 20:21:13 +0000347 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000348 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000349 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000350 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
351 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000352
Douglas Gregor87c08a52010-08-13 22:48:40 +0000353 CachedResult.Priority = Results[I].Priority;
354 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000355 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000356 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000357 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358 CachedCompletionResults.push_back(CachedResult);
359 break;
360 }
361 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000362 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000363
364 // Save the current top-level hash value.
365 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000366}
367
368void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000369 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000370 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000371 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000372}
373
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000374namespace {
375
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000376/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000377/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000378class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000379 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000380 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000381 LangOptions &LangOpt;
382 HeaderSearch &HSI;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000383 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000384 std::string &Predefines;
385 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000387 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000389 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000390public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000391 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
392 HeaderSearch &HSI,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000393 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
394 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000395 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000396 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000397 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000398 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000400 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000401 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000402 return false;
403
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000404 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000405
406 // Initialize the preprocessor.
407 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000408
409 // Initialize the ASTContext
410 Context.InitBuiltinTypes(*Target);
411
412 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000413 return false;
414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner5f9e2722011-07-23 10:55:15 +0000416 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000417 // If we've already initialized the target, don't do it again.
418 if (Target)
419 return false;
420
421 // FIXME: This is broken, we should store the TargetOptions in the AST file.
422 TargetOptions TargetOpts;
423 TargetOpts.ABI = "";
424 TargetOpts.CXXABI = "";
425 TargetOpts.CPU = "";
426 TargetOpts.Features.clear();
427 TargetOpts.Triple = Triple;
428 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000429 return false;
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000432 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000433 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000434 std::string &SuggestedPredefines,
435 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000436 Predefines = Buffers[0].Data;
437 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
438 Predefines += Buffers[I].Data;
439 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000440 return false;
441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000443 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000444 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000447 virtual void ReadCounter(unsigned Value) {
448 Counter = Value;
449 }
450};
451
Douglas Gregora88084b2010-02-18 18:08:43 +0000452class StoredDiagnosticClient : public DiagnosticClient {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000453 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000454
455public:
456 explicit StoredDiagnosticClient(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000458 : StoredDiags(StoredDiags) { }
459
460 virtual void HandleDiagnostic(Diagnostic::Level Level,
461 const DiagnosticInfo &Info);
462};
463
464/// \brief RAII object that optionally captures diagnostics, if
465/// there is no diagnostic client to capture them already.
466class CaptureDroppedDiagnostics {
467 Diagnostic &Diags;
468 StoredDiagnosticClient Client;
469 DiagnosticClient *PreviousClient;
470
471public:
472 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000473 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000474 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000475 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000476 if (RequestCapture || Diags.getClient() == 0) {
477 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000478 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000479 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000480 }
481
482 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000483 if (Diags.getClient() == &Client) {
484 Diags.takeClient();
485 Diags.setClient(PreviousClient);
486 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000487 }
488};
489
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000490} // anonymous namespace
491
Douglas Gregora88084b2010-02-18 18:08:43 +0000492void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
493 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000494 // Default implementation (Warnings/errors count).
495 DiagnosticClient::HandleDiagnostic(Level, Info);
496
Douglas Gregora88084b2010-02-18 18:08:43 +0000497 StoredDiags.push_back(StoredDiagnostic(Level, Info));
498}
499
Steve Naroff77accc12009-09-03 18:19:54 +0000500const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000501 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000502}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000503
Chris Lattner5f9e2722011-07-23 10:55:15 +0000504llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000505 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000506 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000507 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000508}
509
Douglas Gregore47be3e2010-11-11 00:39:14 +0000510/// \brief Configure the diagnostics object for use with ASTUnit.
511void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000512 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000513 ASTUnit &AST, bool CaptureDiagnostics) {
514 if (!Diags.getPtr()) {
515 // No diagnostics engine was provided, so create our own diagnostics object
516 // with the default options.
517 DiagnosticOptions DiagOpts;
518 DiagnosticClient *Client = 0;
519 if (CaptureDiagnostics)
520 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000521 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
522 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000523 } else if (CaptureDiagnostics) {
524 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
525 }
526}
527
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000528ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000529 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000530 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000531 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000532 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000533 unsigned NumRemappedFiles,
534 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000535 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000536
537 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000538 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
539 ASTUnitCleanup(AST.get());
540 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
541 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
542 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000543
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000544 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000545
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000546 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000547 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000548 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000549 AST->FileMgr = new FileManager(FileSystemOpts);
550 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
551 AST->getFileManager());
Chris Lattner39b49bc2010-11-23 08:35:12 +0000552 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000553
Douglas Gregor4db64a42010-01-23 00:14:00 +0000554 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000555 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
556 if (const llvm::MemoryBuffer *
557 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
558 // Create the file entry for the file that we're mapping from.
559 const FileEntry *FromFile
560 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
561 memBuf->getBufferSize(),
562 0);
563 if (!FromFile) {
564 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
565 << RemappedFiles[I].first;
566 delete memBuf;
567 continue;
568 }
569
570 // Override the contents of the "from" file with the contents of
571 // the "to" file.
572 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
573
574 } else {
575 const char *fname = fileOrBuf.get<const char *>();
576 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
577 if (!ToFile) {
578 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
579 << RemappedFiles[I].first << fname;
580 continue;
581 }
582
583 // Create the file entry for the file that we're mapping from.
584 const FileEntry *FromFile
585 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
586 ToFile->getSize(),
587 0);
588 if (!FromFile) {
589 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
590 << RemappedFiles[I].first;
591 delete memBuf;
592 continue;
593 }
594
595 // Override the contents of the "from" file with the contents of
596 // the "to" file.
597 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000598 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000599 }
600
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000601 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000603 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000604 std::string Predefines;
605 unsigned Counter;
606
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000607 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000608
Douglas Gregor998b3d32011-09-01 23:39:15 +0000609 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
610 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
611 *AST,
612 /*IILookup=*/0,
613 /*OwnsHeaderSearch=*/false,
614 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000615 Preprocessor &PP = *AST->PP;
616
617 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
618 AST->getSourceManager(),
619 /*Target=*/0,
620 PP.getIdentifierTable(),
621 PP.getSelectorTable(),
622 PP.getBuiltinInfo(),
623 /* size_reserve = */0,
624 /*DelayInitialization=*/true);
625 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000626
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000627 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000628
629 // Recover resources if we crash before exiting this method.
630 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
631 ReaderCleanup(Reader.get());
632
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000633 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000634 AST->ASTFileLangOpts, HeaderInfo,
635 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000636
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000637 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000638 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000639 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000641 case ASTReader::Failure:
642 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000643 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000644 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000647 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
648
Daniel Dunbard5b61262009-09-21 03:03:47 +0000649 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000650 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000652 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000653 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000654 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000655 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000656 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000657
658 // Unregister the cleanup for ASTReader. It will get cleaned up
659 // by the ASTUnit cleanup.
660 ReaderCleanup.unregister();
661
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000662 Context.setExternalSource(Source);
663
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000664 // Create an AST consumer, even though it isn't used.
665 AST->Consumer.reset(new ASTConsumer);
666
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000667 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000668 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
669 AST->TheSema->Initialize();
670 ReaderPtr->InitializeSema(*AST->TheSema);
671
Mike Stump1eb44332009-09-09 15:08:12 +0000672 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000673}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000674
675namespace {
676
Douglas Gregor9b7db622011-02-16 18:16:54 +0000677/// \brief Preprocessor callback class that updates a hash value with the names
678/// of all macros that have been defined by the translation unit.
679class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
680 unsigned &Hash;
681
682public:
683 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
684
685 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
686 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
687 }
688};
689
690/// \brief Add the given declaration to the hash of all top-level entities.
691void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
692 if (!D)
693 return;
694
695 DeclContext *DC = D->getDeclContext();
696 if (!DC)
697 return;
698
699 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
700 return;
701
702 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
703 if (ND->getIdentifier())
704 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
705 else if (DeclarationName Name = ND->getDeclName()) {
706 std::string NameStr = Name.getAsString();
707 Hash = llvm::HashString(NameStr, Hash);
708 }
709 return;
710 }
711
712 if (ObjCForwardProtocolDecl *Forward
713 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
714 for (ObjCForwardProtocolDecl::protocol_iterator
715 P = Forward->protocol_begin(),
716 PEnd = Forward->protocol_end();
717 P != PEnd; ++P)
718 AddTopLevelDeclarationToHash(*P, Hash);
719 return;
720 }
721
Chris Lattner5f9e2722011-07-23 10:55:15 +0000722 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000723 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregor9b7db622011-02-16 18:16:54 +0000724 return;
725 }
726}
727
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000728class TopLevelDeclTrackerConsumer : public ASTConsumer {
729 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000730 unsigned &Hash;
731
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000732public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000733 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
734 : Unit(_Unit), Hash(Hash) {
735 Hash = 0;
736 }
737
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000738 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000739 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
740 Decl *D = *it;
741 // FIXME: Currently ObjC method declarations are incorrectly being
742 // reported as top-level declarations, even though their DeclContext
743 // is the containing ObjC @interface/@implementation. This is a
744 // fundamental problem in the parser right now.
745 if (isa<ObjCMethodDecl>(D))
746 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000747
748 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000749 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000750 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000751 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000752
753 // We're not interested in "interesting" decls.
754 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000755};
756
757class TopLevelDeclTrackerAction : public ASTFrontendAction {
758public:
759 ASTUnit &Unit;
760
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000761 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000762 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000763 CI.getPreprocessor().addPPCallbacks(
764 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
765 return new TopLevelDeclTrackerConsumer(Unit,
766 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000767 }
768
769public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000770 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
771
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000772 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000773 virtual TranslationUnitKind getTranslationUnitKind() {
774 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000775 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000776};
777
Douglas Gregor89d99802010-11-30 06:16:57 +0000778class PrecompilePreambleConsumer : public PCHGenerator,
779 public ASTSerializationListener {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000780 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000781 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000782 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000783
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000784public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000785 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000786 StringRef isysroot, raw_ostream *Out)
Douglas Gregor7143aab2011-09-01 17:04:32 +0000787 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000788 Hash(Unit.getCurrentTopLevelHashValue()) {
789 Hash = 0;
790 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000791
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000792 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000793 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
794 Decl *D = *it;
795 // FIXME: Currently ObjC method declarations are incorrectly being
796 // reported as top-level declarations, even though their DeclContext
797 // is the containing ObjC @interface/@implementation. This is a
798 // fundamental problem in the parser right now.
799 if (isa<ObjCMethodDecl>(D))
800 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000801 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000802 TopLevelDecls.push_back(D);
803 }
804 }
805
806 virtual void HandleTranslationUnit(ASTContext &Ctx) {
807 PCHGenerator::HandleTranslationUnit(Ctx);
808 if (!Unit.getDiagnostics().hasErrorOccurred()) {
809 // Translate the top-level declarations we captured during
810 // parsing into declaration IDs in the precompiled
811 // preamble. This will allow us to deserialize those top-level
812 // declarations when requested.
813 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
814 Unit.addTopLevelDeclFromPreamble(
815 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000816 }
817 }
Douglas Gregor89d99802010-11-30 06:16:57 +0000818
819 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
820 uint64_t Offset) {
821 Unit.addPreprocessedEntityFromPreamble(Offset);
822 }
823
824 virtual ASTSerializationListener *GetASTSerializationListener() {
825 return this;
826 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000827};
828
829class PrecompilePreambleAction : public ASTFrontendAction {
830 ASTUnit &Unit;
831
832public:
833 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
834
835 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000836 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000837 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000838 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000839 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000840 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
841 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000842 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000843 return 0;
844
Douglas Gregor832d6202011-07-22 16:35:34 +0000845 if (!CI.getFrontendOpts().RelocatablePCH)
846 Sysroot.clear();
847
Douglas Gregor9b7db622011-02-16 18:16:54 +0000848 CI.getPreprocessor().addPPCallbacks(
849 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000850 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
851 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000852 }
853
854 virtual bool hasCodeCompletionSupport() const { return false; }
855 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000856 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000857};
858
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000859}
860
Douglas Gregorabc563f2010-07-19 21:46:24 +0000861/// Parse the source file into a translation unit using the given compiler
862/// invocation, replacing the current translation unit.
863///
864/// \returns True if a failure occurred that causes the ASTUnit not to
865/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000866bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000867 delete SavedMainFileBuffer;
868 SavedMainFileBuffer = 0;
869
Ted Kremenek4f327862011-03-21 18:40:17 +0000870 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000871 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000872 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000873 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000874
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000875 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000876 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
877
878 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000879 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
880 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000881
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +0000882 llvm::IntrusiveRefCntPtr<CompilerInvocation>
883 CCInvocation(new CompilerInvocation(*Invocation));
884
885 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000886 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000887
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000888 // Set up diagnostics, capturing any diagnostics that would
889 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000890 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000891
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000892 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000893 Clang->getTargetOpts().Features = TargetFeatures;
894 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000895 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +0000896 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000897 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000898 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000899 }
900
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000901 // Inform the target of the language options.
902 //
903 // FIXME: We shouldn't need to do this, the target should be immutable once
904 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000905 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000906
Ted Kremenek03201fb2011-03-21 18:40:07 +0000907 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000908 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000909 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000910 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000911 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000912 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000913
Douglas Gregorabc563f2010-07-19 21:46:24 +0000914 // Configure the various subsystems.
915 // FIXME: Should we retain the previous file manager?
Ted Kremenek03201fb2011-03-21 18:40:07 +0000916 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +0000917 FileMgr = new FileManager(FileSystemOpts);
918 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000919 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +0000920 Ctx = 0;
921 PP = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000922
923 // Clear out old caches and data.
924 TopLevelDecls.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000925 PreprocessedEntities.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000926 CleanTemporaryFiles();
927 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000928
Douglas Gregorf128fed2010-08-20 00:02:33 +0000929 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000930 StoredDiagnostics.erase(
931 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
932 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000933 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000934 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000935 }
936
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000937 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000938 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000939
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000940 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000941 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000942
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000943 // If the main file has been overridden due to the use of a preamble,
944 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000945 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +0000946 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
947 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000948 if (OverrideMainBuffer) {
949 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
950 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
951 PreprocessorOpts.PrecompiledPreambleBytes.second
952 = PreambleEndsAtStartOfLine;
Douglas Gregor385103b2010-07-30 20:58:08 +0000953 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000954 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000955
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000956 // The stored diagnostic has the old source manager in it; update
957 // the locations to refer into the new source manager. Since we've
958 // been careful to make sure that the source manager's state
959 // before and after are identical, so that we can reuse the source
960 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000961 for (unsigned I = NumStoredDiagnosticsFromDriver,
962 N = StoredDiagnostics.size();
963 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000964 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
965 getSourceManager());
966 StoredDiagnostics[I].setLocation(Loc);
967 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000968
969 // Keep track of the override buffer;
970 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000971 }
972
Ted Kremenek25a11e12011-03-22 01:15:24 +0000973 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
974 new TopLevelDeclTrackerAction(*this));
975
976 // Recover resources if we crash before exiting this method.
977 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
978 ActCleanup(Act.get());
979
Ted Kremenek03201fb2011-03-21 18:40:07 +0000980 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
981 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000982 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000983
984 if (OverrideMainBuffer) {
Jonathan D. Turner9461fcc2011-07-22 17:25:03 +0000985 std::string ModName = PreambleFile;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000986 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
987 getSourceManager(), PreambleDiagnostics,
988 StoredDiagnostics);
989 }
990
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000991 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000992
Ted Kremenek4f327862011-03-21 18:40:17 +0000993 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000994 TheSema.reset(Clang->takeSema());
995 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +0000996 Ctx = &Clang->getASTContext();
997 PP = &Clang->getPreprocessor();
998 Clang->setSourceManager(0);
999 Clang->setFileManager(0);
1000 Target = &Clang->getTarget();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001001
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001002 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001003
Douglas Gregorabc563f2010-07-19 21:46:24 +00001004 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001005
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001006error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001007 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001008 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001009 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001010 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001011 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001012
Douglas Gregord54eb442010-10-12 16:25:54 +00001013 StoredDiagnostics.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001014 return true;
1015}
1016
Douglas Gregor44c181a2010-07-23 00:33:23 +00001017/// \brief Simple function to retrieve a path for a preamble precompiled header.
1018static std::string GetPreamblePCHPath() {
1019 // FIXME: This is lame; sys::Path should provide this function (in particular,
1020 // it should know how to find the temporary files dir).
1021 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001022 // FIXME: This is a hack so that we can override the preamble file during
1023 // crash-recovery testing, which is the only case where the preamble files
1024 // are not necessarily cleaned up.
1025 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1026 if (TmpFile)
1027 return TmpFile;
1028
Douglas Gregor44c181a2010-07-23 00:33:23 +00001029 std::string Error;
1030 const char *TmpDir = ::getenv("TMPDIR");
1031 if (!TmpDir)
1032 TmpDir = ::getenv("TEMP");
1033 if (!TmpDir)
1034 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001035#ifdef LLVM_ON_WIN32
1036 if (!TmpDir)
1037 TmpDir = ::getenv("USERPROFILE");
1038#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001039 if (!TmpDir)
1040 TmpDir = "/tmp";
1041 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001042 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001043 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001044 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001045 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001046 return std::string();
1047
Douglas Gregor44c181a2010-07-23 00:33:23 +00001048 return P.str();
1049}
1050
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001051/// \brief Compute the preamble for the main file, providing the source buffer
1052/// that corresponds to the main file along with a pair (bytes, start-of-line)
1053/// that describes the preamble.
1054std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001055ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1056 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001057 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001058 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001059 CreatedBuffer = false;
1060
Douglas Gregor44c181a2010-07-23 00:33:23 +00001061 // Try to determine if the main file has been remapped, either from the
1062 // command line (to another file) or directly through the compiler invocation
1063 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001064 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001065 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1066 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1067 // Check whether there is a file-file remapping of the main file
1068 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001069 M = PreprocessorOpts.remapped_file_begin(),
1070 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001071 M != E;
1072 ++M) {
1073 llvm::sys::PathWithStatus MPath(M->first);
1074 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1075 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1076 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001077 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001078 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001079 CreatedBuffer = false;
1080 }
1081
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001082 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001083 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001084 return std::make_pair((llvm::MemoryBuffer*)0,
1085 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001086 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001087 }
1088 }
1089 }
1090
1091 // Check whether there is a file-buffer remapping. It supercedes the
1092 // file-file remapping.
1093 for (PreprocessorOptions::remapped_file_buffer_iterator
1094 M = PreprocessorOpts.remapped_file_buffer_begin(),
1095 E = PreprocessorOpts.remapped_file_buffer_end();
1096 M != E;
1097 ++M) {
1098 llvm::sys::PathWithStatus MPath(M->first);
1099 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1100 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1101 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001102 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001103 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001104 CreatedBuffer = false;
1105 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001106
Douglas Gregor175c4a92010-07-23 23:58:40 +00001107 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001108 }
1109 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001110 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001111 }
1112
1113 // If the main source file was not remapped, load it now.
1114 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001115 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001116 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001117 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001118
1119 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001120 }
1121
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001122 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1123 Invocation.getLangOpts(),
1124 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001125}
1126
Douglas Gregor754f3492010-07-24 00:38:13 +00001127static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001128 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001129 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001130 llvm::MemoryBuffer *Result
1131 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1132 memcpy(const_cast<char*>(Result->getBufferStart()),
1133 Old->getBufferStart(), Old->getBufferSize());
1134 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001135 ' ', NewSize - Old->getBufferSize() - 1);
1136 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001137
Douglas Gregor754f3492010-07-24 00:38:13 +00001138 return Result;
1139}
1140
Douglas Gregor175c4a92010-07-23 23:58:40 +00001141/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1142/// the source file.
1143///
1144/// This routine will compute the preamble of the main source file. If a
1145/// non-trivial preamble is found, it will precompile that preamble into a
1146/// precompiled header so that the precompiled preamble can be used to reduce
1147/// reparsing time. If a precompiled preamble has already been constructed,
1148/// this routine will determine if it is still valid and, if so, avoid
1149/// rebuilding the precompiled preamble.
1150///
Douglas Gregordf95a132010-08-09 20:45:32 +00001151/// \param AllowRebuild When true (the default), this routine is
1152/// allowed to rebuild the precompiled preamble if it is found to be
1153/// out-of-date.
1154///
1155/// \param MaxLines When non-zero, the maximum number of lines that
1156/// can occur within the preamble.
1157///
Douglas Gregor754f3492010-07-24 00:38:13 +00001158/// \returns If the precompiled preamble can be used, returns a newly-allocated
1159/// buffer that should be used in place of the main file when doing so.
1160/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001161llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001162 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001163 bool AllowRebuild,
1164 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001165
1166 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1167 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1168 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001169 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001170 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001171
1172 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001173 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001174 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001175
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001176 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001177 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1178 if (CreatedPreambleBuffer)
1179 OwnedPreambleBuffer.reset(NewPreamble.first);
1180
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001181 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001182 // We couldn't find a preamble in the main source. Clear out the current
1183 // preamble, if we have one. It's obviously no good any more.
1184 Preamble.clear();
1185 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001186 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001187 PreambleFile.clear();
1188 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001189
1190 // The next time we actually see a preamble, precompile it.
1191 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001192 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001193 }
1194
1195 if (!Preamble.empty()) {
1196 // We've previously computed a preamble. Check whether we have the same
1197 // preamble now that we did before, and that there's enough space in
1198 // the main-file buffer within the precompiled preamble to fit the
1199 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001200 if (Preamble.size() == NewPreamble.second.first &&
1201 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001202 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001203 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001204 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001205 // The preamble has not changed. We may be able to re-use the precompiled
1206 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001207
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001208 // Check that none of the files used by the preamble have changed.
1209 bool AnyFileChanged = false;
1210
1211 // First, make a record of those files that have been overridden via
1212 // remapping or unsaved_files.
1213 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1214 for (PreprocessorOptions::remapped_file_iterator
1215 R = PreprocessorOpts.remapped_file_begin(),
1216 REnd = PreprocessorOpts.remapped_file_end();
1217 !AnyFileChanged && R != REnd;
1218 ++R) {
1219 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001220 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001221 // If we can't stat the file we're remapping to, assume that something
1222 // horrible happened.
1223 AnyFileChanged = true;
1224 break;
1225 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001226
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001227 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1228 StatBuf.st_mtime);
1229 }
1230 for (PreprocessorOptions::remapped_file_buffer_iterator
1231 R = PreprocessorOpts.remapped_file_buffer_begin(),
1232 REnd = PreprocessorOpts.remapped_file_buffer_end();
1233 !AnyFileChanged && R != REnd;
1234 ++R) {
1235 // FIXME: Should we actually compare the contents of file->buffer
1236 // remappings?
1237 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1238 0);
1239 }
1240
1241 // Check whether anything has changed.
1242 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1243 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1244 !AnyFileChanged && F != FEnd;
1245 ++F) {
1246 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1247 = OverriddenFiles.find(F->first());
1248 if (Overridden != OverriddenFiles.end()) {
1249 // This file was remapped; check whether the newly-mapped file
1250 // matches up with the previous mapping.
1251 if (Overridden->second != F->second)
1252 AnyFileChanged = true;
1253 continue;
1254 }
1255
1256 // The file was not remapped; check whether it has changed on disk.
1257 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001258 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001259 // If we can't stat the file, assume that something horrible happened.
1260 AnyFileChanged = true;
1261 } else if (StatBuf.st_size != F->second.first ||
1262 StatBuf.st_mtime != F->second.second)
1263 AnyFileChanged = true;
1264 }
1265
1266 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001267 // Okay! We can re-use the precompiled preamble.
1268
1269 // Set the state of the diagnostic object to mimic its state
1270 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001271 // FIXME: This won't catch any #pragma push warning changes that
1272 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001273 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001274 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001275 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001276 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001277
1278 // Create a version of the main file buffer that is padded to
1279 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001280 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001281 PreambleReservedSize,
1282 FrontendOpts.Inputs[0].second);
1283 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001284 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001285
1286 // If we aren't allowed to rebuild the precompiled preamble, just
1287 // return now.
1288 if (!AllowRebuild)
1289 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001290
Douglas Gregor175c4a92010-07-23 23:58:40 +00001291 // We can't reuse the previously-computed preamble. Build a new one.
1292 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001293 PreambleDiagnostics.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001294 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001295 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001296 } else if (!AllowRebuild) {
1297 // We aren't allowed to rebuild the precompiled preamble; just
1298 // return now.
1299 return 0;
1300 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001301
1302 // If the preamble rebuild counter > 1, it's because we previously
1303 // failed to build a preamble and we're not yet ready to try
1304 // again. Decrement the counter and return a failure.
1305 if (PreambleRebuildCounter > 1) {
1306 --PreambleRebuildCounter;
1307 return 0;
1308 }
1309
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001310 // Create a temporary file for the precompiled preamble. In rare
1311 // circumstances, this can fail.
1312 std::string PreamblePCHPath = GetPreamblePCHPath();
1313 if (PreamblePCHPath.empty()) {
1314 // Try again next time.
1315 PreambleRebuildCounter = 1;
1316 return 0;
1317 }
1318
Douglas Gregor175c4a92010-07-23 23:58:40 +00001319 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001320 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001321 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001322
1323 // Create a new buffer that stores the preamble. The buffer also contains
1324 // extra space for the original contents of the file (which will be present
1325 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001326 // grows.
1327 PreambleReservedSize = NewPreamble.first->getBufferSize();
1328 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001329 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001330 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001331 PreambleReservedSize *= 2;
1332
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001333 // Save the preamble text for later; we'll need to compare against it for
1334 // subsequent reparses.
1335 Preamble.assign(NewPreamble.first->getBufferStart(),
1336 NewPreamble.first->getBufferStart()
1337 + NewPreamble.second.first);
1338 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1339
Douglas Gregor671947b2010-08-19 01:33:06 +00001340 delete PreambleBuffer;
1341 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001342 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001343 FrontendOpts.Inputs[0].second);
1344 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001345 NewPreamble.first->getBufferStart(), Preamble.size());
1346 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001347 ' ', PreambleReservedSize - Preamble.size() - 1);
1348 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001349
1350 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001351 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001352 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1353
1354 // Tell the compiler invocation to generate a temporary precompiled header.
1355 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001356 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001357 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001358 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1359 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001360
1361 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001362 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1363
1364 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001365 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1366 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001367
Douglas Gregor01b6e312011-07-01 18:22:13 +00001368 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001369 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001370
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001371 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001372 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001373
1374 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001375 Clang->getTargetOpts().Features = TargetFeatures;
1376 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1377 Clang->getTargetOpts()));
1378 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001379 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1380 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001381 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001382 PreprocessorOpts.eraseRemappedFile(
1383 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001384 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001385 }
1386
1387 // Inform the target of the language options.
1388 //
1389 // FIXME: We shouldn't need to do this, the target should be immutable once
1390 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001391 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001392
Ted Kremenek03201fb2011-03-21 18:40:07 +00001393 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001394 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001395 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001396 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001397 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001398 "IR inputs not support here!");
1399
1400 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001401 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001402 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001403 StoredDiagnostics.erase(
1404 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1405 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001406 TopLevelDecls.clear();
1407 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001408 PreprocessedEntities.clear();
1409 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001410
1411 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001412 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001413
1414 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001415 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001416 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001417
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001418 llvm::OwningPtr<PrecompilePreambleAction> Act;
1419 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001420 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1421 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001422 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1423 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001424 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001425 PreprocessorOpts.eraseRemappedFile(
1426 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001427 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001428 }
1429
1430 Act->Execute();
1431 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001432
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001433 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001434 // There were errors parsing the preamble, so no precompiled header was
1435 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001436 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001437 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1438 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001439 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001440 PreprocessedEntities.clear();
1441 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001442 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001443 PreprocessorOpts.eraseRemappedFile(
1444 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001445 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001446 }
1447
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001448 // Transfer any diagnostics generated when parsing the preamble into the set
1449 // of preamble diagnostics.
1450 PreambleDiagnostics.clear();
1451 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1452 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1453 StoredDiagnostics.end());
1454 StoredDiagnostics.erase(
1455 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1456 StoredDiagnostics.end());
1457
Douglas Gregor175c4a92010-07-23 23:58:40 +00001458 // Keep track of the preamble we precompiled.
1459 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001460 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001461
1462 // Keep track of all of the files that the source manager knows about,
1463 // so we can verify whether they have changed or not.
1464 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001465 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001466 const llvm::MemoryBuffer *MainFileBuffer
1467 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1468 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1469 FEnd = SourceMgr.fileinfo_end();
1470 F != FEnd;
1471 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001472 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001473 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1474 continue;
1475
1476 FilesInPreamble[File->getName()]
1477 = std::make_pair(F->second->getSize(), File->getModificationTime());
1478 }
1479
Douglas Gregoreababfb2010-08-04 05:53:38 +00001480 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001481 PreprocessorOpts.eraseRemappedFile(
1482 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001483
1484 // If the hash of top-level entities differs from the hash of the top-level
1485 // entities the last time we rebuilt the preamble, clear out the completion
1486 // cache.
1487 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1488 CompletionCacheTopLevelHashValue = 0;
1489 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1490 }
1491
Douglas Gregor754f3492010-07-24 00:38:13 +00001492 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001493 PreambleReservedSize,
1494 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001496
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001497void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1498 std::vector<Decl *> Resolved;
1499 Resolved.reserve(TopLevelDeclsInPreamble.size());
1500 ExternalASTSource &Source = *getASTContext().getExternalSource();
1501 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1502 // Resolve the declaration ID to an actual declaration, possibly
1503 // deserializing the declaration in the process.
1504 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1505 if (D)
1506 Resolved.push_back(D);
1507 }
1508 TopLevelDeclsInPreamble.clear();
1509 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1510}
1511
Douglas Gregor89d99802010-11-30 06:16:57 +00001512void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1513 if (!PP)
1514 return;
1515
1516 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1517 if (!PPRec)
1518 return;
1519
1520 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1521 if (!External)
1522 return;
1523
1524 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1525 if (PreprocessedEntity *PE
Douglas Gregor0a480292011-02-11 19:46:30 +00001526 = External->ReadPreprocessedEntityAtOffset(
1527 PreprocessedEntitiesInPreamble[I]))
Douglas Gregor89d99802010-11-30 06:16:57 +00001528 PreprocessedEntities.push_back(PE);
1529 }
1530
1531 if (PreprocessedEntities.empty())
1532 return;
1533
1534 PreprocessedEntities.insert(PreprocessedEntities.end(),
1535 PPRec->begin(true), PPRec->end(true));
1536}
1537
1538ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1539 if (!PreprocessedEntitiesInPreamble.empty() &&
1540 PreprocessedEntities.empty())
1541 RealizePreprocessedEntitiesFromPreamble();
1542
Douglas Gregor89d99802010-11-30 06:16:57 +00001543 return PreprocessedEntities.begin();
1544}
1545
1546ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1547 if (!PreprocessedEntitiesInPreamble.empty() &&
1548 PreprocessedEntities.empty())
1549 RealizePreprocessedEntitiesFromPreamble();
Douglas Gregor4c30bb12011-07-21 00:47:40 +00001550
Douglas Gregor89d99802010-11-30 06:16:57 +00001551 return PreprocessedEntities.end();
1552}
1553
Chris Lattner5f9e2722011-07-23 10:55:15 +00001554StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001555 return Invocation->getFrontendOpts().Inputs[0].second;
1556}
1557
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001558ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1559 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1560 llvm::OwningPtr<ASTUnit> AST;
1561 AST.reset(new ASTUnit(false));
1562 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1563 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001564 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001565 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001566 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1567 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001568
1569 return AST.take();
1570}
1571
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001572ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1573 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1574 ASTFrontendAction *Action) {
1575 assert(CI && "A CompilerInvocation is required");
1576
1577 // Create the AST unit.
1578 llvm::OwningPtr<ASTUnit> AST;
1579 AST.reset(new ASTUnit(false));
1580 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1581 AST->Diagnostics = Diags;
1582 AST->OnlyLocalDecls = false;
1583 AST->CaptureDiagnostics = false;
Douglas Gregor467dc882011-08-25 22:30:56 +00001584 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001585 AST->ShouldCacheCodeCompletionResults = false;
1586 AST->Invocation = CI;
1587
1588 // Recover resources if we crash before exiting this method.
1589 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1590 ASTUnitCleanup(AST.get());
1591 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1592 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1593 DiagCleanup(Diags.getPtr());
1594
1595 // We'll manage file buffers ourselves.
1596 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1597 CI->getFrontendOpts().DisableFree = false;
1598 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1599
1600 // Save the target features.
1601 AST->TargetFeatures = CI->getTargetOpts().Features;
1602
1603 // Create the compiler instance to use for building the AST.
1604 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1605
1606 // Recover resources if we crash before exiting this method.
1607 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1608 CICleanup(Clang.get());
1609
1610 Clang->setInvocation(CI);
1611 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1612
1613 // Set up diagnostics, capturing any diagnostics that would
1614 // otherwise be dropped.
1615 Clang->setDiagnostics(&AST->getDiagnostics());
1616
1617 // Create the target instance.
1618 Clang->getTargetOpts().Features = AST->TargetFeatures;
1619 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1620 Clang->getTargetOpts()));
1621 if (!Clang->hasTarget())
1622 return 0;
1623
1624 // Inform the target of the language options.
1625 //
1626 // FIXME: We shouldn't need to do this, the target should be immutable once
1627 // created. This complexity should be lifted elsewhere.
1628 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1629
1630 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1631 "Invocation must have exactly one source file!");
1632 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1633 "FIXME: AST inputs not yet supported here!");
1634 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1635 "IR inputs not supported here!");
1636
1637 // Configure the various subsystems.
1638 AST->FileSystemOpts = Clang->getFileSystemOpts();
1639 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1640 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1641 AST->TheSema.reset();
1642 AST->Ctx = 0;
1643 AST->PP = 0;
1644
1645 // Create a file manager object to provide access to and cache the filesystem.
1646 Clang->setFileManager(&AST->getFileManager());
1647
1648 // Create the source manager.
1649 Clang->setSourceManager(&AST->getSourceManager());
1650
1651 ASTFrontendAction *Act = Action;
1652
1653 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1654 if (!Act) {
1655 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1656 Act = TrackerAct.get();
1657 }
1658
1659 // Recover resources if we crash before exiting this method.
1660 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1661 ActCleanup(TrackerAct.get());
1662
1663 if (!Act->BeginSourceFile(*Clang.get(),
1664 Clang->getFrontendOpts().Inputs[0].second,
1665 Clang->getFrontendOpts().Inputs[0].first))
1666 return 0;
1667
1668 Act->Execute();
1669
1670 // Steal the created target, context, and preprocessor.
1671 AST->TheSema.reset(Clang->takeSema());
1672 AST->Consumer.reset(Clang->takeASTConsumer());
1673 AST->Ctx = &Clang->getASTContext();
1674 AST->PP = &Clang->getPreprocessor();
1675 Clang->setSourceManager(0);
1676 Clang->setFileManager(0);
1677 AST->Target = &Clang->getTarget();
1678
1679 Act->EndSourceFile();
1680
1681 return AST.take();
1682}
1683
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001684bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1685 if (!Invocation)
1686 return true;
1687
1688 // We'll manage file buffers ourselves.
1689 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1690 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001691 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001692
Douglas Gregor1aa27302011-01-27 18:02:58 +00001693 // Save the target features.
1694 TargetFeatures = Invocation->getTargetOpts().Features;
1695
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001696 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001697 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001698 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001699 OverrideMainBuffer
1700 = getMainBufferWithPrecompiledPreamble(*Invocation);
1701 }
1702
Douglas Gregor213f18b2010-10-28 15:44:59 +00001703 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001704 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001705
Ted Kremenek25a11e12011-03-22 01:15:24 +00001706 // Recover resources if we crash before exiting this method.
1707 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1708 MemBufferCleanup(OverrideMainBuffer);
1709
Douglas Gregor213f18b2010-10-28 15:44:59 +00001710 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001711}
1712
Douglas Gregorabc563f2010-07-19 21:46:24 +00001713ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1714 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1715 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001716 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001717 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001718 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001719 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001720 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001721 // Create the AST unit.
1722 llvm::OwningPtr<ASTUnit> AST;
1723 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001724 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001725 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001726 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001727 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001728 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001729 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001730 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001731 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001732
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001733 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001734 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1735 ASTUnitCleanup(AST.get());
1736 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1737 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1738 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001739
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001740 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001741}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001742
1743ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1744 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001745 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001746 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001747 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001748 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001749 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001750 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001751 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001752 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001753 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001754 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001755 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001756 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001757 // No diagnostics engine was provided, so create our own diagnostics object
1758 // with the default options.
1759 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001760 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1761 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001762 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001763
Chris Lattner5f9e2722011-07-23 10:55:15 +00001764 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001765
Ted Kremenek4f327862011-03-21 18:40:17 +00001766 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001767
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001768 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001769
Douglas Gregore47be3e2010-11-11 00:39:14 +00001770 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001771 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001772
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001773 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001774 llvm::makeArrayRef(ArgBegin, ArgEnd),
1775 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001776 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001777 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001778 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001779
Douglas Gregor4db64a42010-01-23 00:14:00 +00001780 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001781 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1782 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1783 if (const llvm::MemoryBuffer *
1784 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1785 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1786 } else {
1787 const char *fname = fileOrBuf.get<const char *>();
1788 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1789 }
1790 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001791 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1792 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001793
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001794 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001795 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001796
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001797 // Create the AST unit.
1798 llvm::OwningPtr<ASTUnit> AST;
1799 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001800 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001801 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001802
1803 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001804 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001805 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001806 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001807 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001808 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1809 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001810 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001811 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001812 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001813
1814 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001815 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1816 ASTUnitCleanup(AST.get());
1817 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1818 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1819 CICleanup(CI.getPtr());
1820 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1821 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1822 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001823
Chris Lattner39b49bc2010-11-23 08:35:12 +00001824 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001825}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001826
1827bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001828 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001829 return true;
1830
Douglas Gregor213f18b2010-10-28 15:44:59 +00001831 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001832 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001833
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001834 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001835 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001836 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001837 for (PreprocessorOptions::remapped_file_buffer_iterator
1838 R = PPOpts.remapped_file_buffer_begin(),
1839 REnd = PPOpts.remapped_file_buffer_end();
1840 R != REnd;
1841 ++R) {
1842 delete R->second;
1843 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001844 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001845 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1846 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1847 if (const llvm::MemoryBuffer *
1848 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1849 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1850 memBuf);
1851 } else {
1852 const char *fname = fileOrBuf.get<const char *>();
1853 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1854 fname);
1855 }
1856 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001857
Douglas Gregoreababfb2010-08-04 05:53:38 +00001858 // If we have a preamble file lying around, or if we might try to
1859 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001860 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001861 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001862 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001863
Douglas Gregorabc563f2010-07-19 21:46:24 +00001864 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001865 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001866 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001867 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1868 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001869
Douglas Gregor175c4a92010-07-23 23:58:40 +00001870 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001871 bool Result = Parse(OverrideMainBuffer);
1872
1873 // If we're caching global code-completion results, and the top-level
1874 // declarations have changed, clear out the code-completion cache.
1875 if (!Result && ShouldCacheCodeCompletionResults &&
1876 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1877 CacheCodeCompletionResults();
1878
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001879 // We now need to clear out the completion allocator for
1880 // clang_getCursorCompletionString; it'll be recreated if necessary.
1881 CursorCompletionAllocator = 0;
1882
Douglas Gregor175c4a92010-07-23 23:58:40 +00001883 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001884}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001885
Douglas Gregor87c08a52010-08-13 22:48:40 +00001886//----------------------------------------------------------------------------//
1887// Code completion
1888//----------------------------------------------------------------------------//
1889
1890namespace {
1891 /// \brief Code completion consumer that combines the cached code-completion
1892 /// results from an ASTUnit with the code-completion results provided to it,
1893 /// then passes the result on to
1894 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001895 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001896 ASTUnit &AST;
1897 CodeCompleteConsumer &Next;
1898
1899 public:
1900 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001901 bool IncludeMacros, bool IncludeCodePatterns,
1902 bool IncludeGlobals)
1903 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001904 Next.isOutputBinary()), AST(AST), Next(Next)
1905 {
1906 // Compute the set of contexts in which we will look when we don't have
1907 // any information about the specific context.
1908 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00001909 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1910 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1911 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1912 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1913 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1914 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1915 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1916 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1917 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1918 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1919 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1920 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1921 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001922
Douglas Gregor87c08a52010-08-13 22:48:40 +00001923 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00001924 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1925 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1926 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00001927 }
1928
1929 virtual void ProcessCodeCompleteResults(Sema &S,
1930 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001931 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001932 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001933
1934 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1935 OverloadCandidate *Candidates,
1936 unsigned NumCandidates) {
1937 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1938 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001939
Douglas Gregordae68752011-02-01 22:57:45 +00001940 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00001941 return Next.getAllocator();
1942 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00001943 };
1944}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001945
Douglas Gregor5f808c22010-08-16 21:18:39 +00001946/// \brief Helper function that computes which global names are hidden by the
1947/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001948static void CalculateHiddenNames(const CodeCompletionContext &Context,
1949 CodeCompletionResult *Results,
1950 unsigned NumResults,
1951 ASTContext &Ctx,
1952 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001953 bool OnlyTagNames = false;
1954 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001955 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001956 case CodeCompletionContext::CCC_TopLevel:
1957 case CodeCompletionContext::CCC_ObjCInterface:
1958 case CodeCompletionContext::CCC_ObjCImplementation:
1959 case CodeCompletionContext::CCC_ObjCIvarList:
1960 case CodeCompletionContext::CCC_ClassStructUnion:
1961 case CodeCompletionContext::CCC_Statement:
1962 case CodeCompletionContext::CCC_Expression:
1963 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001964 case CodeCompletionContext::CCC_DotMemberAccess:
1965 case CodeCompletionContext::CCC_ArrowMemberAccess:
1966 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001967 case CodeCompletionContext::CCC_Namespace:
1968 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001969 case CodeCompletionContext::CCC_Name:
1970 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001971 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00001972 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001973 break;
1974
1975 case CodeCompletionContext::CCC_EnumTag:
1976 case CodeCompletionContext::CCC_UnionTag:
1977 case CodeCompletionContext::CCC_ClassOrStructTag:
1978 OnlyTagNames = true;
1979 break;
1980
1981 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001982 case CodeCompletionContext::CCC_MacroName:
1983 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001984 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001985 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001986 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001987 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001988 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001989 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00001990 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001991 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1992 case CodeCompletionContext::CCC_ObjCClassMessage:
1993 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00001994 // We're looking for nothing, or we're looking for names that cannot
1995 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001996 return;
1997 }
1998
John McCall0a2c5e22010-08-25 06:19:51 +00001999 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002000 for (unsigned I = 0; I != NumResults; ++I) {
2001 if (Results[I].Kind != Result::RK_Declaration)
2002 continue;
2003
2004 unsigned IDNS
2005 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2006
2007 bool Hiding = false;
2008 if (OnlyTagNames)
2009 Hiding = (IDNS & Decl::IDNS_Tag);
2010 else {
2011 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002012 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2013 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002014 if (Ctx.getLangOptions().CPlusPlus)
2015 HiddenIDNS |= Decl::IDNS_Tag;
2016 Hiding = (IDNS & HiddenIDNS);
2017 }
2018
2019 if (!Hiding)
2020 continue;
2021
2022 DeclarationName Name = Results[I].Declaration->getDeclName();
2023 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2024 HiddenNames.insert(Identifier->getName());
2025 else
2026 HiddenNames.insert(Name.getAsString());
2027 }
2028}
2029
2030
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002031void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2032 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002033 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002034 unsigned NumResults) {
2035 // Merge the results we were given with the results we cached.
2036 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002037 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002038 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002039 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002040 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002041 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002042 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002043 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002044 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002045 C = AST.cached_completion_begin(),
2046 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002047 C != CEnd; ++C) {
2048 // If the context we are in matches any of the contexts we are
2049 // interested in, we'll add this result.
2050 if ((C->ShowInContexts & InContexts) == 0)
2051 continue;
2052
2053 // If we haven't added any results previously, do so now.
2054 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002055 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2056 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002057 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2058 AddedResult = true;
2059 }
2060
Douglas Gregor5f808c22010-08-16 21:18:39 +00002061 // Determine whether this global completion result is hidden by a local
2062 // completion result. If so, skip it.
2063 if (C->Kind != CXCursor_MacroDefinition &&
2064 HiddenNames.count(C->Completion->getTypedText()))
2065 continue;
2066
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002067 // Adjust priority based on similar type classes.
2068 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002069 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002070 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002071 if (!Context.getPreferredType().isNull()) {
2072 if (C->Kind == CXCursor_MacroDefinition) {
2073 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002074 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002075 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002076 } else if (C->Type) {
2077 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002078 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002079 Context.getPreferredType().getUnqualifiedType());
2080 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2081 if (ExpectedSTC == C->TypeClass) {
2082 // We know this type is similar; check for an exact match.
2083 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002084 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002085 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002086 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002087 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2088 Priority /= CCF_ExactTypeMatch;
2089 else
2090 Priority /= CCF_SimilarTypeMatch;
2091 }
2092 }
2093 }
2094
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002095 // Adjust the completion string, if required.
2096 if (C->Kind == CXCursor_MacroDefinition &&
2097 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2098 // Create a new code-completion string that just contains the
2099 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002100 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2101 C->Availability);
2102 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002103 CursorKind = CXCursor_NotImplemented;
2104 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002105 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002106 }
2107
Douglas Gregor4125c372010-08-25 18:03:13 +00002108 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002109 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002110 }
2111
2112 // If we did not add any cached completion results, just forward the
2113 // results we were given to the next consumer.
2114 if (!AddedResult) {
2115 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2116 return;
2117 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002118
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002119 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2120 AllResults.size());
2121}
2122
2123
2124
Chris Lattner5f9e2722011-07-23 10:55:15 +00002125void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002126 RemappedFile *RemappedFiles,
2127 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002128 bool IncludeMacros,
2129 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002130 CodeCompleteConsumer &Consumer,
2131 Diagnostic &Diag, LangOptions &LangOpts,
2132 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002133 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2134 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002135 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002136 return;
2137
Douglas Gregor213f18b2010-10-28 15:44:59 +00002138 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002139 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002140 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002141
Ted Kremenek4f327862011-03-21 18:40:17 +00002142 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2143 CCInvocation(new CompilerInvocation(*Invocation));
2144
2145 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2146 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002147
Douglas Gregor87c08a52010-08-13 22:48:40 +00002148 FrontendOpts.ShowMacrosInCodeCompletion
2149 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002150 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002151 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2152 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002153 FrontendOpts.CodeCompletionAt.FileName = File;
2154 FrontendOpts.CodeCompletionAt.Line = Line;
2155 FrontendOpts.CodeCompletionAt.Column = Column;
2156
2157 // Set the language options appropriately.
Ted Kremenek4f327862011-03-21 18:40:17 +00002158 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002159
Ted Kremenek03201fb2011-03-21 18:40:07 +00002160 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2161
2162 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002163 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2164 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002165
Ted Kremenek4f327862011-03-21 18:40:17 +00002166 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002167 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002168
2169 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002170 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002171 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002172 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002173 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002174 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002175
2176 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002177 Clang->getTargetOpts().Features = TargetFeatures;
2178 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2179 Clang->getTargetOpts()));
2180 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002181 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002182 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002183 }
2184
2185 // Inform the target of the language options.
2186 //
2187 // FIXME: We shouldn't need to do this, the target should be immutable once
2188 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002189 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002190
Ted Kremenek03201fb2011-03-21 18:40:07 +00002191 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002192 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002193 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002194 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002195 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002196 "IR inputs not support here!");
2197
2198
2199 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002200 Clang->setFileManager(&FileMgr);
2201 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002202
2203 // Remap files.
2204 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002205 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002206 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002207 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2208 if (const llvm::MemoryBuffer *
2209 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2210 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2211 OwnedBuffers.push_back(memBuf);
2212 } else {
2213 const char *fname = fileOrBuf.get<const char *>();
2214 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2215 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002216 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002217
Douglas Gregor87c08a52010-08-13 22:48:40 +00002218 // Use the code completion consumer we were given, but adding any cached
2219 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002220 AugmentedCodeCompleteConsumer *AugmentedConsumer
2221 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2222 FrontendOpts.ShowMacrosInCodeCompletion,
2223 FrontendOpts.ShowCodePatternsInCodeCompletion,
2224 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002225 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002226
Douglas Gregordf95a132010-08-09 20:45:32 +00002227 // If we have a precompiled preamble, try to use it. We only allow
2228 // the use of the precompiled preamble if we're if the completion
2229 // point is within the main file, after the end of the precompiled
2230 // preamble.
2231 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2232 if (!PreambleFile.empty()) {
2233 using llvm::sys::FileStatus;
2234 llvm::sys::PathWithStatus CompleteFilePath(File);
2235 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2236 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2237 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002238 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2239 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002240 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002241 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002242 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002243 }
2244
2245 // If the main file has been overridden due to the use of a preamble,
2246 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002247 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002248 StoredDiagnostics.insert(StoredDiagnostics.end(),
2249 this->StoredDiagnostics.begin(),
2250 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00002251 if (OverrideMainBuffer) {
2252 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2253 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2254 PreprocessorOpts.PrecompiledPreambleBytes.second
2255 = PreambleEndsAtStartOfLine;
2256 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2257 PreprocessorOpts.DisablePCHValidation = true;
2258
Douglas Gregor2283d792010-08-20 00:59:43 +00002259 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002260 } else {
2261 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2262 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002263 }
2264
Douglas Gregordca8ee82011-05-06 16:33:08 +00002265 // Disable the preprocessing record
2266 PreprocessorOpts.DetailedRecord = false;
2267
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002268 llvm::OwningPtr<SyntaxOnlyAction> Act;
2269 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002270 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2271 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002272 if (OverrideMainBuffer) {
Jonathan D. Turner9461fcc2011-07-22 17:25:03 +00002273 std::string ModName = PreambleFile;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002274 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2275 getSourceManager(), PreambleDiagnostics,
2276 StoredDiagnostics);
2277 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002278 Act->Execute();
2279 Act->EndSourceFile();
2280 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002281}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002282
Chris Lattner5f9e2722011-07-23 10:55:15 +00002283CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002284 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002285 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002286
2287 // Write to a temporary file and later rename it to the actual file, to avoid
2288 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002289 llvm::SmallString<128> TempPath;
2290 TempPath = File;
2291 TempPath += "-%%%%%%%%";
2292 int fd;
2293 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2294 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002295 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002296
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002297 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2298 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002299 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002300
2301 serialize(Out);
2302 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002303 if (Out.has_error())
2304 return CXSaveError_Unknown;
2305
2306 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2307 bool exists;
2308 llvm::sys::fs::remove(TempPath.str(), exists);
2309 return CXSaveError_Unknown;
2310 }
2311
2312 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002313}
2314
Chris Lattner5f9e2722011-07-23 10:55:15 +00002315bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002316 if (getDiagnostics().hasErrorOccurred())
2317 return true;
2318
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002319 std::vector<unsigned char> Buffer;
2320 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002321 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002322 // FIXME: Handle modules
2323 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002324
2325 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002326 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002327 OS.write((char *)&Buffer.front(), Buffer.size());
2328
2329 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002330}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002331
2332typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2333
2334static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2335 unsigned Raw = L.getRawEncoding();
2336 const unsigned MacroBit = 1U << 31;
2337 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2338 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2339}
2340
2341void ASTUnit::TranslateStoredDiagnostics(
2342 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002343 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002344 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002345 const SmallVectorImpl<StoredDiagnostic> &Diags,
2346 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002347 // The stored diagnostic has the old source manager in it; update
2348 // the locations to refer into the new source manager. We also need to remap
2349 // all the locations to the new view. This includes the diag location, any
2350 // associated source ranges, and the source ranges of associated fix-its.
2351 // FIXME: There should be a cleaner way to do this.
2352
Chris Lattner5f9e2722011-07-23 10:55:15 +00002353 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002354 Result.reserve(Diags.size());
2355 assert(MMan && "Don't have a module manager");
Jonathan D. Turner48d2c3f2011-07-26 18:21:30 +00002356 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002357 assert(Mod && "Don't have preamble module");
2358 SLocRemap &Remap = Mod->SLocRemap;
2359 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2360 // Rebuild the StoredDiagnostic.
2361 const StoredDiagnostic &SD = Diags[I];
2362 SourceLocation L = SD.getLocation();
2363 TranslateSLoc(L, Remap);
2364 FullSourceLoc Loc(L, SrcMgr);
2365
Chris Lattner5f9e2722011-07-23 10:55:15 +00002366 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002367 Ranges.reserve(SD.range_size());
2368 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2369 E = SD.range_end();
2370 I != E; ++I) {
2371 SourceLocation BL = I->getBegin();
2372 TranslateSLoc(BL, Remap);
2373 SourceLocation EL = I->getEnd();
2374 TranslateSLoc(EL, Remap);
2375 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2376 }
2377
Chris Lattner5f9e2722011-07-23 10:55:15 +00002378 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002379 FixIts.reserve(SD.fixit_size());
2380 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2381 E = SD.fixit_end();
2382 I != E; ++I) {
2383 FixIts.push_back(FixItHint());
2384 FixItHint &FH = FixIts.back();
2385 FH.CodeToInsert = I->CodeToInsert;
2386 SourceLocation BL = I->RemoveRange.getBegin();
2387 TranslateSLoc(BL, Remap);
2388 SourceLocation EL = I->RemoveRange.getEnd();
2389 TranslateSLoc(EL, Remap);
2390 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2391 I->RemoveRange.isTokenRange());
2392 }
2393
2394 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2395 SD.getMessage(), Loc, Ranges, FixIts));
2396 }
2397 Result.swap(Out);
2398}