blob: 19b8ccb4c32626864beaa70e0068e1a6eb3f082e [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"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000032#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000035#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000036#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000038#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000039#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000040#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000041#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000046#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000047#include "llvm/Support/FileSystem.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000048#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000049#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000050#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000051#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000052using namespace clang;
53
Douglas Gregor213f18b2010-10-28 15:44:59 +000054using llvm::TimeRecord;
55
56namespace {
57 class SimpleTimer {
58 bool WantTiming;
59 TimeRecord Start;
60 std::string Output;
61
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000063 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 }
67
Chris Lattner5f9e2722011-07-23 10:55:15 +000068 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000070 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 }
72
Douglas Gregor213f18b2010-10-28 15:44:59 +000073 ~SimpleTimer() {
74 if (WantTiming) {
75 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 Elapsed -= Start;
77 llvm::errs() << Output << ':';
78 Elapsed.print(Elapsed, llvm::errs());
79 llvm::errs() << '\n';
80 }
81 }
82 };
83}
84
Douglas Gregoreababfb2010-08-04 05:53:38 +000085/// \brief After failing to build a precompiled preamble (due to
86/// errors in the source that occurs in the preamble), the number of
87/// reparses during which we'll skip even trying to precompile the
88/// preamble.
89const unsigned DefaultPreambleRebuildInterval = 5;
90
Douglas Gregore3c60a72010-11-17 00:13:31 +000091/// \brief Tracks the number of ASTUnit objects that are currently active.
92///
93/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000094static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000095
Douglas Gregor3687e9d2010-04-05 21:10:19 +000096ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +000097 : OnlyLocalDecls(false), CaptureDiagnostics(false),
98 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +000099 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000100 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000101 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000102 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +0000103 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000104 ShouldCacheCodeCompletionResults(false),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000105 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000106 CompletionCacheTopLevelHashValue(0),
107 PreambleTopLevelHashValue(0),
108 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000109 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000110 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000111 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000112 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
113 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000114}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000115
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000116ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000117 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000118 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000119 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000120 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000121
122 // Free the buffers associated with remapped files. We are required to
123 // perform this operation here because we explicitly request that the
124 // compiler instance *not* free these buffers for each invocation of the
125 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000126 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000127 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
128 for (PreprocessorOptions::remapped_file_buffer_iterator
129 FB = PPOpts.remapped_file_buffer_begin(),
130 FBEnd = PPOpts.remapped_file_buffer_end();
131 FB != FBEnd;
132 ++FB)
133 delete FB->second;
134 }
Douglas Gregor28233422010-07-27 14:52:07 +0000135
136 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000137 delete PreambleBuffer;
138
Douglas Gregor213f18b2010-10-28 15:44:59 +0000139 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000140
141 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000142 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000143 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
144 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000145}
146
147void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000148 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
149 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000150 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000151}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000152
Douglas Gregor8071e422010-08-15 06:18:01 +0000153/// \brief Determine the set of code-completion contexts in which this
154/// declaration should be shown.
155static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000156 const LangOptions &LangOpts,
157 bool &IsNestedNameSpecifier) {
158 IsNestedNameSpecifier = false;
159
Douglas Gregor8071e422010-08-15 06:18:01 +0000160 if (isa<UsingShadowDecl>(ND))
161 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
162 if (!ND)
163 return 0;
164
165 unsigned Contexts = 0;
166 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
167 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
168 // Types can appear in these contexts.
169 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
170 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
171 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
172 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
173 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000174 | (1 << (CodeCompletionContext::CCC_Type - 1))
175 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000176
177 // In C++, types can appear in expressions contexts (for functional casts).
178 if (LangOpts.CPlusPlus)
179 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
180
181 // In Objective-C, message sends can send interfaces. In Objective-C++,
182 // all types are available due to functional casts.
183 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
184 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000185
186 // In Objective-C, you can only be a subclass of another Objective-C class
187 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000188 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000189
190 // Deal with tag names.
191 if (isa<EnumDecl>(ND)) {
192 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
193
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000194 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000195 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000196 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000197 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
198 if (Record->isUnion())
199 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
200 else
201 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
202
Douglas Gregor8071e422010-08-15 06:18:01 +0000203 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000204 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000205 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000206 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000207 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
208 // Values can appear in these contexts.
209 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
210 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000211 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000212 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
213 } else if (isa<ObjCProtocolDecl>(ND)) {
214 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000215 } else if (isa<ObjCCategoryDecl>(ND)) {
216 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000217 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000218 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000219
220 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000221 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000222 }
223
224 return Contexts;
225}
226
Douglas Gregor87c08a52010-08-13 22:48:40 +0000227void ASTUnit::CacheCodeCompletionResults() {
228 if (!TheSema)
229 return;
230
Douglas Gregor213f18b2010-10-28 15:44:59 +0000231 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000232 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000233
234 // Clear out the previous results.
235 ClearCachedCompletionResults();
236
237 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000238 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000239 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000240 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
241 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000242
243 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000244 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
245
Douglas Gregor87c08a52010-08-13 22:48:40 +0000246 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
247 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000248 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000249 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000250 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000251 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000252 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000253 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000254 Ctx->getLangOptions(),
255 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000256 CachedResult.Priority = Results[I].Priority;
257 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000258 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000259
Douglas Gregorf5586f62010-08-16 18:08:11 +0000260 // Keep track of the type of this completion in an ASTContext-agnostic
261 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000262 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000263 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000264 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000265 CachedResult.Type = 0;
266 } else {
267 CanQualType CanUsageType
268 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
269 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
270
271 // Determine whether we have already seen this type. If so, we save
272 // ourselves the work of formatting the type string by using the
273 // temporary, CanQualType-based hash table to find the associated value.
274 unsigned &TypeValue = CompletionTypes[CanUsageType];
275 if (TypeValue == 0) {
276 TypeValue = CompletionTypes.size();
277 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
278 = TypeValue;
279 }
280
281 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000282 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000283
Douglas Gregor8071e422010-08-15 06:18:01 +0000284 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000285
286 /// Handle nested-name-specifiers in C++.
287 if (TheSema->Context.getLangOptions().CPlusPlus &&
288 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
289 // The contexts in which a nested-name-specifier can appear in C++.
290 unsigned NNSContexts
291 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
292 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
293 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
294 | (1 << (CodeCompletionContext::CCC_Statement - 1))
295 | (1 << (CodeCompletionContext::CCC_Expression - 1))
296 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
297 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
298 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
299 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000300 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000301 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
302 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000303
304 if (isa<NamespaceDecl>(Results[I].Declaration) ||
305 isa<NamespaceAliasDecl>(Results[I].Declaration))
306 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
307
308 if (unsigned RemainingContexts
309 = NNSContexts & ~CachedResult.ShowInContexts) {
310 // If there any contexts where this completion can be a
311 // nested-name-specifier but isn't already an option, create a
312 // nested-name-specifier completion.
313 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000314 CachedResult.Completion
315 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000316 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 CachedResult.ShowInContexts = RemainingContexts;
318 CachedResult.Priority = CCP_NestedNameSpecifier;
319 CachedResult.TypeClass = STC_Void;
320 CachedResult.Type = 0;
321 CachedCompletionResults.push_back(CachedResult);
322 }
323 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000324 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 }
326
Douglas Gregor87c08a52010-08-13 22:48:40 +0000327 case Result::RK_Keyword:
328 case Result::RK_Pattern:
329 // Ignore keywords and patterns; we don't care, since they are so
330 // easily regenerated.
331 break;
332
333 case Result::RK_Macro: {
334 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000335 CachedResult.Completion
336 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000337 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000338 CachedResult.ShowInContexts
339 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
340 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
341 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
342 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
343 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
344 | (1 << (CodeCompletionContext::CCC_Statement - 1))
345 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000346 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000347 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000348 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000349 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
350 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000351
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352 CachedResult.Priority = Results[I].Priority;
353 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000354 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000355 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000356 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000357 CachedCompletionResults.push_back(CachedResult);
358 break;
359 }
360 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000361 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000362
363 // Save the current top-level hash value.
364 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000365}
366
367void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000368 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000370 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000371}
372
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000373namespace {
374
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000375/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000376/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000377class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000378 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000379 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000380 LangOptions &LangOpt;
381 HeaderSearch &HSI;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000382 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000383 std::string &Predefines;
384 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000386 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000388 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000389public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000390 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
391 HeaderSearch &HSI,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000392 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
393 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000394 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000395 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000396 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000397 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000399 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000400 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000401 return false;
402
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000403 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000404
405 // Initialize the preprocessor.
406 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000407
408 // Initialize the ASTContext
409 Context.InitBuiltinTypes(*Target);
410
411 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000412 return false;
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5f9e2722011-07-23 10:55:15 +0000415 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000416 // If we've already initialized the target, don't do it again.
417 if (Target)
418 return false;
419
420 // FIXME: This is broken, we should store the TargetOptions in the AST file.
421 TargetOptions TargetOpts;
422 TargetOpts.ABI = "";
423 TargetOpts.CXXABI = "";
424 TargetOpts.CPU = "";
425 TargetOpts.Features.clear();
426 TargetOpts.Triple = Triple;
427 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000428 return false;
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000431 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000432 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000433 std::string &SuggestedPredefines,
434 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000435 Predefines = Buffers[0].Data;
436 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
437 Predefines += Buffers[I].Data;
438 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000439 return false;
440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000442 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000443 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000446 virtual void ReadCounter(unsigned Value) {
447 Counter = Value;
448 }
449};
450
Douglas Gregora88084b2010-02-18 18:08:43 +0000451class StoredDiagnosticClient : public DiagnosticClient {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000452 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000453
454public:
455 explicit StoredDiagnosticClient(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000456 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000457 : StoredDiags(StoredDiags) { }
458
459 virtual void HandleDiagnostic(Diagnostic::Level Level,
460 const DiagnosticInfo &Info);
461};
462
463/// \brief RAII object that optionally captures diagnostics, if
464/// there is no diagnostic client to capture them already.
465class CaptureDroppedDiagnostics {
466 Diagnostic &Diags;
467 StoredDiagnosticClient Client;
468 DiagnosticClient *PreviousClient;
469
470public:
471 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000472 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000473 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000474 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000475 if (RequestCapture || Diags.getClient() == 0) {
476 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000477 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000478 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000479 }
480
481 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000482 if (Diags.getClient() == &Client) {
483 Diags.takeClient();
484 Diags.setClient(PreviousClient);
485 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000486 }
487};
488
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000489} // anonymous namespace
490
Douglas Gregora88084b2010-02-18 18:08:43 +0000491void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
492 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000493 // Default implementation (Warnings/errors count).
494 DiagnosticClient::HandleDiagnostic(Level, Info);
495
Douglas Gregora88084b2010-02-18 18:08:43 +0000496 StoredDiags.push_back(StoredDiagnostic(Level, Info));
497}
498
Steve Naroff77accc12009-09-03 18:19:54 +0000499const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000500 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000501}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502
Chris Lattner5f9e2722011-07-23 10:55:15 +0000503llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000504 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000505 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000506 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000507}
508
Douglas Gregore47be3e2010-11-11 00:39:14 +0000509/// \brief Configure the diagnostics object for use with ASTUnit.
510void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000511 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000512 ASTUnit &AST, bool CaptureDiagnostics) {
513 if (!Diags.getPtr()) {
514 // No diagnostics engine was provided, so create our own diagnostics object
515 // with the default options.
516 DiagnosticOptions DiagOpts;
517 DiagnosticClient *Client = 0;
518 if (CaptureDiagnostics)
519 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000520 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
521 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000522 } else if (CaptureDiagnostics) {
523 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
524 }
525}
526
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000527ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000528 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000529 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000530 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000531 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000532 unsigned NumRemappedFiles,
533 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000534 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000535
536 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000537 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
538 ASTUnitCleanup(AST.get());
539 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
540 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
541 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000542
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000543 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000544
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000545 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000546 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000547 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000548 AST->FileMgr = new FileManager(FileSystemOpts);
549 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
550 AST->getFileManager());
Chris Lattner39b49bc2010-11-23 08:35:12 +0000551 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000552
Douglas Gregor4db64a42010-01-23 00:14:00 +0000553 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000554 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
555 if (const llvm::MemoryBuffer *
556 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
557 // Create the file entry for the file that we're mapping from.
558 const FileEntry *FromFile
559 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
560 memBuf->getBufferSize(),
561 0);
562 if (!FromFile) {
563 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
564 << RemappedFiles[I].first;
565 delete memBuf;
566 continue;
567 }
568
569 // Override the contents of the "from" file with the contents of
570 // the "to" file.
571 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
572
573 } else {
574 const char *fname = fileOrBuf.get<const char *>();
575 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
576 if (!ToFile) {
577 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
578 << RemappedFiles[I].first << fname;
579 continue;
580 }
581
582 // Create the file entry for the file that we're mapping from.
583 const FileEntry *FromFile
584 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
585 ToFile->getSize(),
586 0);
587 if (!FromFile) {
588 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
589 << RemappedFiles[I].first;
590 delete memBuf;
591 continue;
592 }
593
594 // Override the contents of the "from" file with the contents of
595 // the "to" file.
596 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000597 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000598 }
599
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000600 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000602 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000603 std::string Predefines;
604 unsigned Counter;
605
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000606 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000607
Douglas Gregor998b3d32011-09-01 23:39:15 +0000608 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
609 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
610 *AST,
611 /*IILookup=*/0,
612 /*OwnsHeaderSearch=*/false,
613 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000614 Preprocessor &PP = *AST->PP;
615
616 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
617 AST->getSourceManager(),
618 /*Target=*/0,
619 PP.getIdentifierTable(),
620 PP.getSelectorTable(),
621 PP.getBuiltinInfo(),
622 /* size_reserve = */0,
623 /*DelayInitialization=*/true);
624 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000625
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000626 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000627
628 // Recover resources if we crash before exiting this method.
629 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
630 ReaderCleanup(Reader.get());
631
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000632 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000633 AST->ASTFileLangOpts, HeaderInfo,
634 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000635
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000636 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000637 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000638 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000640 case ASTReader::Failure:
641 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000642 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000643 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000646 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
647
Daniel Dunbard5b61262009-09-21 03:03:47 +0000648 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000649 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000651 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000652 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000653 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000654 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000655 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000656
657 // Unregister the cleanup for ASTReader. It will get cleaned up
658 // by the ASTUnit cleanup.
659 ReaderCleanup.unregister();
660
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000661 Context.setExternalSource(Source);
662
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000663 // Create an AST consumer, even though it isn't used.
664 AST->Consumer.reset(new ASTConsumer);
665
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000666 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000667 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
668 AST->TheSema->Initialize();
669 ReaderPtr->InitializeSema(*AST->TheSema);
670
Mike Stump1eb44332009-09-09 15:08:12 +0000671 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000672}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000673
674namespace {
675
Douglas Gregor9b7db622011-02-16 18:16:54 +0000676/// \brief Preprocessor callback class that updates a hash value with the names
677/// of all macros that have been defined by the translation unit.
678class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
679 unsigned &Hash;
680
681public:
682 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
683
684 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
685 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
686 }
687};
688
689/// \brief Add the given declaration to the hash of all top-level entities.
690void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
691 if (!D)
692 return;
693
694 DeclContext *DC = D->getDeclContext();
695 if (!DC)
696 return;
697
698 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
699 return;
700
701 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
702 if (ND->getIdentifier())
703 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
704 else if (DeclarationName Name = ND->getDeclName()) {
705 std::string NameStr = Name.getAsString();
706 Hash = llvm::HashString(NameStr, Hash);
707 }
708 return;
709 }
710
711 if (ObjCForwardProtocolDecl *Forward
712 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
713 for (ObjCForwardProtocolDecl::protocol_iterator
714 P = Forward->protocol_begin(),
715 PEnd = Forward->protocol_end();
716 P != PEnd; ++P)
717 AddTopLevelDeclarationToHash(*P, Hash);
718 return;
719 }
720
Chris Lattner5f9e2722011-07-23 10:55:15 +0000721 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000722 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregor9b7db622011-02-16 18:16:54 +0000723 return;
724 }
725}
726
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000727class TopLevelDeclTrackerConsumer : public ASTConsumer {
728 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000729 unsigned &Hash;
730
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000731public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000732 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
733 : Unit(_Unit), Hash(Hash) {
734 Hash = 0;
735 }
736
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000737 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000738 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
739 Decl *D = *it;
740 // FIXME: Currently ObjC method declarations are incorrectly being
741 // reported as top-level declarations, even though their DeclContext
742 // is the containing ObjC @interface/@implementation. This is a
743 // fundamental problem in the parser right now.
744 if (isa<ObjCMethodDecl>(D))
745 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000746
747 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000748 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000749 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000750 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000751
752 // We're not interested in "interesting" decls.
753 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000754};
755
756class TopLevelDeclTrackerAction : public ASTFrontendAction {
757public:
758 ASTUnit &Unit;
759
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000760 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000761 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000762 CI.getPreprocessor().addPPCallbacks(
763 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
764 return new TopLevelDeclTrackerConsumer(Unit,
765 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000766 }
767
768public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000769 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
770
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000771 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000772 virtual TranslationUnitKind getTranslationUnitKind() {
773 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000774 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000775};
776
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000777class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000778 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000779 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000780 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000781
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000782public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000783 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000784 StringRef isysroot, raw_ostream *Out)
Douglas Gregor7143aab2011-09-01 17:04:32 +0000785 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000786 Hash(Unit.getCurrentTopLevelHashValue()) {
787 Hash = 0;
788 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000789
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000790 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000791 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
792 Decl *D = *it;
793 // FIXME: Currently ObjC method declarations are incorrectly being
794 // reported as top-level declarations, even though their DeclContext
795 // is the containing ObjC @interface/@implementation. This is a
796 // fundamental problem in the parser right now.
797 if (isa<ObjCMethodDecl>(D))
798 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000799 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000800 TopLevelDecls.push_back(D);
801 }
802 }
803
804 virtual void HandleTranslationUnit(ASTContext &Ctx) {
805 PCHGenerator::HandleTranslationUnit(Ctx);
806 if (!Unit.getDiagnostics().hasErrorOccurred()) {
807 // Translate the top-level declarations we captured during
808 // parsing into declaration IDs in the precompiled
809 // preamble. This will allow us to deserialize those top-level
810 // declarations when requested.
811 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
812 Unit.addTopLevelDeclFromPreamble(
813 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000814 }
815 }
816};
817
818class PrecompilePreambleAction : public ASTFrontendAction {
819 ASTUnit &Unit;
820
821public:
822 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
823
824 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000825 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000826 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000827 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000828 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000829 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
830 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000831 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000832 return 0;
833
Douglas Gregor832d6202011-07-22 16:35:34 +0000834 if (!CI.getFrontendOpts().RelocatablePCH)
835 Sysroot.clear();
836
Douglas Gregor9b7db622011-02-16 18:16:54 +0000837 CI.getPreprocessor().addPPCallbacks(
838 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000839 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
840 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000841 }
842
843 virtual bool hasCodeCompletionSupport() const { return false; }
844 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000845 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000846};
847
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000848}
849
Douglas Gregorabc563f2010-07-19 21:46:24 +0000850/// Parse the source file into a translation unit using the given compiler
851/// invocation, replacing the current translation unit.
852///
853/// \returns True if a failure occurred that causes the ASTUnit not to
854/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000855bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000856 delete SavedMainFileBuffer;
857 SavedMainFileBuffer = 0;
858
Ted Kremenek4f327862011-03-21 18:40:17 +0000859 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000860 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000861 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000862 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000863
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000864 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000865 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
866
867 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000868 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
869 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000870
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +0000871 llvm::IntrusiveRefCntPtr<CompilerInvocation>
872 CCInvocation(new CompilerInvocation(*Invocation));
873
874 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000875 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000876
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000877 // Set up diagnostics, capturing any diagnostics that would
878 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000879 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000880
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000881 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000882 Clang->getTargetOpts().Features = TargetFeatures;
883 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000884 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +0000885 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000886 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000887 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000888 }
889
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000890 // Inform the target of the language options.
891 //
892 // FIXME: We shouldn't need to do this, the target should be immutable once
893 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000894 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000895
Ted Kremenek03201fb2011-03-21 18:40:07 +0000896 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000897 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000898 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000899 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000900 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000901 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000902
Douglas Gregorabc563f2010-07-19 21:46:24 +0000903 // Configure the various subsystems.
904 // FIXME: Should we retain the previous file manager?
Ted Kremenek03201fb2011-03-21 18:40:07 +0000905 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +0000906 FileMgr = new FileManager(FileSystemOpts);
907 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000908 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +0000909 Ctx = 0;
910 PP = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000911
912 // Clear out old caches and data.
913 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000914 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000915
Douglas Gregorf128fed2010-08-20 00:02:33 +0000916 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000917 StoredDiagnostics.erase(
918 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
919 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000920 TopLevelDeclsInPreamble.clear();
921 }
922
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000923 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000924 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000925
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000926 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000927 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000928
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000929 // If the main file has been overridden due to the use of a preamble,
930 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000931 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +0000932 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
933 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000934 if (OverrideMainBuffer) {
935 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
936 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
937 PreprocessorOpts.PrecompiledPreambleBytes.second
938 = PreambleEndsAtStartOfLine;
Douglas Gregor385103b2010-07-30 20:58:08 +0000939 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000940 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000941
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000942 // The stored diagnostic has the old source manager in it; update
943 // the locations to refer into the new source manager. Since we've
944 // been careful to make sure that the source manager's state
945 // before and after are identical, so that we can reuse the source
946 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000947 for (unsigned I = NumStoredDiagnosticsFromDriver,
948 N = StoredDiagnostics.size();
949 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000950 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
951 getSourceManager());
952 StoredDiagnostics[I].setLocation(Loc);
953 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000954
955 // Keep track of the override buffer;
956 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000957 }
958
Ted Kremenek25a11e12011-03-22 01:15:24 +0000959 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
960 new TopLevelDeclTrackerAction(*this));
961
962 // Recover resources if we crash before exiting this method.
963 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
964 ActCleanup(Act.get());
965
Ted Kremenek03201fb2011-03-21 18:40:07 +0000966 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
967 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000968 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000969
970 if (OverrideMainBuffer) {
Jonathan D. Turner9461fcc2011-07-22 17:25:03 +0000971 std::string ModName = PreambleFile;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000972 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
973 getSourceManager(), PreambleDiagnostics,
974 StoredDiagnostics);
975 }
976
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000977 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000978
Ted Kremenek4f327862011-03-21 18:40:17 +0000979 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000980 TheSema.reset(Clang->takeSema());
981 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +0000982 Ctx = &Clang->getASTContext();
983 PP = &Clang->getPreprocessor();
984 Clang->setSourceManager(0);
985 Clang->setFileManager(0);
986 Target = &Clang->getTarget();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000987
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000988 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000989
Douglas Gregorabc563f2010-07-19 21:46:24 +0000990 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +0000991
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000992error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000993 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000994 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000995 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000996 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000997 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000998
Douglas Gregord54eb442010-10-12 16:25:54 +0000999 StoredDiagnostics.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001000 return true;
1001}
1002
Douglas Gregor44c181a2010-07-23 00:33:23 +00001003/// \brief Simple function to retrieve a path for a preamble precompiled header.
1004static std::string GetPreamblePCHPath() {
1005 // FIXME: This is lame; sys::Path should provide this function (in particular,
1006 // it should know how to find the temporary files dir).
1007 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001008 // FIXME: This is a hack so that we can override the preamble file during
1009 // crash-recovery testing, which is the only case where the preamble files
1010 // are not necessarily cleaned up.
1011 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1012 if (TmpFile)
1013 return TmpFile;
1014
Douglas Gregor44c181a2010-07-23 00:33:23 +00001015 std::string Error;
1016 const char *TmpDir = ::getenv("TMPDIR");
1017 if (!TmpDir)
1018 TmpDir = ::getenv("TEMP");
1019 if (!TmpDir)
1020 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001021#ifdef LLVM_ON_WIN32
1022 if (!TmpDir)
1023 TmpDir = ::getenv("USERPROFILE");
1024#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001025 if (!TmpDir)
1026 TmpDir = "/tmp";
1027 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001028 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001029 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001030 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001031 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001032 return std::string();
1033
Douglas Gregor44c181a2010-07-23 00:33:23 +00001034 return P.str();
1035}
1036
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001037/// \brief Compute the preamble for the main file, providing the source buffer
1038/// that corresponds to the main file along with a pair (bytes, start-of-line)
1039/// that describes the preamble.
1040std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001041ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1042 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001043 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001044 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001045 CreatedBuffer = false;
1046
Douglas Gregor44c181a2010-07-23 00:33:23 +00001047 // Try to determine if the main file has been remapped, either from the
1048 // command line (to another file) or directly through the compiler invocation
1049 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001050 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001051 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1052 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1053 // Check whether there is a file-file remapping of the main file
1054 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001055 M = PreprocessorOpts.remapped_file_begin(),
1056 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001057 M != E;
1058 ++M) {
1059 llvm::sys::PathWithStatus MPath(M->first);
1060 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1061 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1062 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001063 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001064 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001065 CreatedBuffer = false;
1066 }
1067
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001068 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001069 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001070 return std::make_pair((llvm::MemoryBuffer*)0,
1071 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001072 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001073 }
1074 }
1075 }
1076
1077 // Check whether there is a file-buffer remapping. It supercedes the
1078 // file-file remapping.
1079 for (PreprocessorOptions::remapped_file_buffer_iterator
1080 M = PreprocessorOpts.remapped_file_buffer_begin(),
1081 E = PreprocessorOpts.remapped_file_buffer_end();
1082 M != E;
1083 ++M) {
1084 llvm::sys::PathWithStatus MPath(M->first);
1085 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1086 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1087 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001088 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001089 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001090 CreatedBuffer = false;
1091 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001092
Douglas Gregor175c4a92010-07-23 23:58:40 +00001093 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001094 }
1095 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001096 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001097 }
1098
1099 // If the main source file was not remapped, load it now.
1100 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001101 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001102 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001103 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001104
1105 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001106 }
1107
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001108 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1109 Invocation.getLangOpts(),
1110 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001111}
1112
Douglas Gregor754f3492010-07-24 00:38:13 +00001113static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001114 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001115 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001116 llvm::MemoryBuffer *Result
1117 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1118 memcpy(const_cast<char*>(Result->getBufferStart()),
1119 Old->getBufferStart(), Old->getBufferSize());
1120 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001121 ' ', NewSize - Old->getBufferSize() - 1);
1122 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001123
Douglas Gregor754f3492010-07-24 00:38:13 +00001124 return Result;
1125}
1126
Douglas Gregor175c4a92010-07-23 23:58:40 +00001127/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1128/// the source file.
1129///
1130/// This routine will compute the preamble of the main source file. If a
1131/// non-trivial preamble is found, it will precompile that preamble into a
1132/// precompiled header so that the precompiled preamble can be used to reduce
1133/// reparsing time. If a precompiled preamble has already been constructed,
1134/// this routine will determine if it is still valid and, if so, avoid
1135/// rebuilding the precompiled preamble.
1136///
Douglas Gregordf95a132010-08-09 20:45:32 +00001137/// \param AllowRebuild When true (the default), this routine is
1138/// allowed to rebuild the precompiled preamble if it is found to be
1139/// out-of-date.
1140///
1141/// \param MaxLines When non-zero, the maximum number of lines that
1142/// can occur within the preamble.
1143///
Douglas Gregor754f3492010-07-24 00:38:13 +00001144/// \returns If the precompiled preamble can be used, returns a newly-allocated
1145/// buffer that should be used in place of the main file when doing so.
1146/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001147llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001148 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001149 bool AllowRebuild,
1150 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001151
1152 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1153 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1154 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001155 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001156 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001157
1158 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001159 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001160 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001161
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001162 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001163 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1164 if (CreatedPreambleBuffer)
1165 OwnedPreambleBuffer.reset(NewPreamble.first);
1166
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001167 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001168 // We couldn't find a preamble in the main source. Clear out the current
1169 // preamble, if we have one. It's obviously no good any more.
1170 Preamble.clear();
1171 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001172 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001173 PreambleFile.clear();
1174 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001175
1176 // The next time we actually see a preamble, precompile it.
1177 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001178 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001179 }
1180
1181 if (!Preamble.empty()) {
1182 // We've previously computed a preamble. Check whether we have the same
1183 // preamble now that we did before, and that there's enough space in
1184 // the main-file buffer within the precompiled preamble to fit the
1185 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001186 if (Preamble.size() == NewPreamble.second.first &&
1187 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001188 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001189 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001190 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001191 // The preamble has not changed. We may be able to re-use the precompiled
1192 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001193
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001194 // Check that none of the files used by the preamble have changed.
1195 bool AnyFileChanged = false;
1196
1197 // First, make a record of those files that have been overridden via
1198 // remapping or unsaved_files.
1199 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1200 for (PreprocessorOptions::remapped_file_iterator
1201 R = PreprocessorOpts.remapped_file_begin(),
1202 REnd = PreprocessorOpts.remapped_file_end();
1203 !AnyFileChanged && R != REnd;
1204 ++R) {
1205 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001206 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001207 // If we can't stat the file we're remapping to, assume that something
1208 // horrible happened.
1209 AnyFileChanged = true;
1210 break;
1211 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001212
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001213 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1214 StatBuf.st_mtime);
1215 }
1216 for (PreprocessorOptions::remapped_file_buffer_iterator
1217 R = PreprocessorOpts.remapped_file_buffer_begin(),
1218 REnd = PreprocessorOpts.remapped_file_buffer_end();
1219 !AnyFileChanged && R != REnd;
1220 ++R) {
1221 // FIXME: Should we actually compare the contents of file->buffer
1222 // remappings?
1223 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1224 0);
1225 }
1226
1227 // Check whether anything has changed.
1228 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1229 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1230 !AnyFileChanged && F != FEnd;
1231 ++F) {
1232 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1233 = OverriddenFiles.find(F->first());
1234 if (Overridden != OverriddenFiles.end()) {
1235 // This file was remapped; check whether the newly-mapped file
1236 // matches up with the previous mapping.
1237 if (Overridden->second != F->second)
1238 AnyFileChanged = true;
1239 continue;
1240 }
1241
1242 // The file was not remapped; check whether it has changed on disk.
1243 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001244 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001245 // If we can't stat the file, assume that something horrible happened.
1246 AnyFileChanged = true;
1247 } else if (StatBuf.st_size != F->second.first ||
1248 StatBuf.st_mtime != F->second.second)
1249 AnyFileChanged = true;
1250 }
1251
1252 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001253 // Okay! We can re-use the precompiled preamble.
1254
1255 // Set the state of the diagnostic object to mimic its state
1256 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001257 // FIXME: This won't catch any #pragma push warning changes that
1258 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001259 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001260 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001261 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001262 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001263
1264 // Create a version of the main file buffer that is padded to
1265 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001266 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001267 PreambleReservedSize,
1268 FrontendOpts.Inputs[0].second);
1269 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001270 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001271
1272 // If we aren't allowed to rebuild the precompiled preamble, just
1273 // return now.
1274 if (!AllowRebuild)
1275 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001276
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 // We can't reuse the previously-computed preamble. Build a new one.
1278 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001279 PreambleDiagnostics.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001280 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001281 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001282 } else if (!AllowRebuild) {
1283 // We aren't allowed to rebuild the precompiled preamble; just
1284 // return now.
1285 return 0;
1286 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001287
1288 // If the preamble rebuild counter > 1, it's because we previously
1289 // failed to build a preamble and we're not yet ready to try
1290 // again. Decrement the counter and return a failure.
1291 if (PreambleRebuildCounter > 1) {
1292 --PreambleRebuildCounter;
1293 return 0;
1294 }
1295
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001296 // Create a temporary file for the precompiled preamble. In rare
1297 // circumstances, this can fail.
1298 std::string PreamblePCHPath = GetPreamblePCHPath();
1299 if (PreamblePCHPath.empty()) {
1300 // Try again next time.
1301 PreambleRebuildCounter = 1;
1302 return 0;
1303 }
1304
Douglas Gregor175c4a92010-07-23 23:58:40 +00001305 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001306 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001307 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308
1309 // Create a new buffer that stores the preamble. The buffer also contains
1310 // extra space for the original contents of the file (which will be present
1311 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001312 // grows.
1313 PreambleReservedSize = NewPreamble.first->getBufferSize();
1314 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001315 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001316 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001317 PreambleReservedSize *= 2;
1318
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001319 // Save the preamble text for later; we'll need to compare against it for
1320 // subsequent reparses.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001321 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1322 Preamble.assign(FileMgr->getFile(MainFilename),
1323 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001324 NewPreamble.first->getBufferStart()
1325 + NewPreamble.second.first);
1326 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1327
Douglas Gregor671947b2010-08-19 01:33:06 +00001328 delete PreambleBuffer;
1329 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001330 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001331 FrontendOpts.Inputs[0].second);
1332 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001333 NewPreamble.first->getBufferStart(), Preamble.size());
1334 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001335 ' ', PreambleReservedSize - Preamble.size() - 1);
1336 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001337
1338 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001339 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001340 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1341
1342 // Tell the compiler invocation to generate a temporary precompiled header.
1343 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001344 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001345 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001346 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1347 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001348
1349 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001350 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1351
1352 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001353 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1354 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001355
Douglas Gregor01b6e312011-07-01 18:22:13 +00001356 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001357 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001358
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001359 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001360 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001361
1362 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001363 Clang->getTargetOpts().Features = TargetFeatures;
1364 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1365 Clang->getTargetOpts()));
1366 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001367 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1368 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001369 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001370 PreprocessorOpts.eraseRemappedFile(
1371 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001372 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001373 }
1374
1375 // Inform the target of the language options.
1376 //
1377 // FIXME: We shouldn't need to do this, the target should be immutable once
1378 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001379 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001380
Ted Kremenek03201fb2011-03-21 18:40:07 +00001381 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001382 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001383 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001384 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001385 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001386 "IR inputs not support here!");
1387
1388 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001389 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001390 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001391 StoredDiagnostics.erase(
1392 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1393 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001394 TopLevelDecls.clear();
1395 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001396
1397 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001398 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001399
1400 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001401 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001402 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001403
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001404 llvm::OwningPtr<PrecompilePreambleAction> Act;
1405 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001406 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1407 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001408 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1409 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001410 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001411 PreprocessorOpts.eraseRemappedFile(
1412 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001413 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001414 }
1415
1416 Act->Execute();
1417 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001418
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001419 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001420 // There were errors parsing the preamble, so no precompiled header was
1421 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001422 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001423 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1424 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001425 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001426 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001427 PreprocessorOpts.eraseRemappedFile(
1428 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001429 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001430 }
1431
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001432 // Transfer any diagnostics generated when parsing the preamble into the set
1433 // of preamble diagnostics.
1434 PreambleDiagnostics.clear();
1435 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1436 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1437 StoredDiagnostics.end());
1438 StoredDiagnostics.erase(
1439 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1440 StoredDiagnostics.end());
1441
Douglas Gregor175c4a92010-07-23 23:58:40 +00001442 // Keep track of the preamble we precompiled.
1443 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001444 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001445
1446 // Keep track of all of the files that the source manager knows about,
1447 // so we can verify whether they have changed or not.
1448 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001449 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001450 const llvm::MemoryBuffer *MainFileBuffer
1451 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1452 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1453 FEnd = SourceMgr.fileinfo_end();
1454 F != FEnd;
1455 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001456 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001457 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1458 continue;
1459
1460 FilesInPreamble[File->getName()]
1461 = std::make_pair(F->second->getSize(), File->getModificationTime());
1462 }
1463
Douglas Gregoreababfb2010-08-04 05:53:38 +00001464 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001465 PreprocessorOpts.eraseRemappedFile(
1466 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001467
1468 // If the hash of top-level entities differs from the hash of the top-level
1469 // entities the last time we rebuilt the preamble, clear out the completion
1470 // cache.
1471 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1472 CompletionCacheTopLevelHashValue = 0;
1473 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1474 }
1475
Douglas Gregor754f3492010-07-24 00:38:13 +00001476 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001477 PreambleReservedSize,
1478 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001479}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001480
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001481void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1482 std::vector<Decl *> Resolved;
1483 Resolved.reserve(TopLevelDeclsInPreamble.size());
1484 ExternalASTSource &Source = *getASTContext().getExternalSource();
1485 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1486 // Resolve the declaration ID to an actual declaration, possibly
1487 // deserializing the declaration in the process.
1488 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1489 if (D)
1490 Resolved.push_back(D);
1491 }
1492 TopLevelDeclsInPreamble.clear();
1493 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1494}
1495
Chris Lattner5f9e2722011-07-23 10:55:15 +00001496StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001497 return Invocation->getFrontendOpts().Inputs[0].second;
1498}
1499
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001500ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1501 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1502 llvm::OwningPtr<ASTUnit> AST;
1503 AST.reset(new ASTUnit(false));
1504 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1505 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001506 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001507 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001508 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1509 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001510
1511 return AST.take();
1512}
1513
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001514ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1515 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1516 ASTFrontendAction *Action) {
1517 assert(CI && "A CompilerInvocation is required");
1518
1519 // Create the AST unit.
1520 llvm::OwningPtr<ASTUnit> AST;
1521 AST.reset(new ASTUnit(false));
1522 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1523 AST->Diagnostics = Diags;
1524 AST->OnlyLocalDecls = false;
1525 AST->CaptureDiagnostics = false;
Douglas Gregor467dc882011-08-25 22:30:56 +00001526 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001527 AST->ShouldCacheCodeCompletionResults = false;
1528 AST->Invocation = CI;
1529
1530 // Recover resources if we crash before exiting this method.
1531 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1532 ASTUnitCleanup(AST.get());
1533 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1534 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1535 DiagCleanup(Diags.getPtr());
1536
1537 // We'll manage file buffers ourselves.
1538 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1539 CI->getFrontendOpts().DisableFree = false;
1540 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1541
1542 // Save the target features.
1543 AST->TargetFeatures = CI->getTargetOpts().Features;
1544
1545 // Create the compiler instance to use for building the AST.
1546 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1547
1548 // Recover resources if we crash before exiting this method.
1549 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1550 CICleanup(Clang.get());
1551
1552 Clang->setInvocation(CI);
1553 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1554
1555 // Set up diagnostics, capturing any diagnostics that would
1556 // otherwise be dropped.
1557 Clang->setDiagnostics(&AST->getDiagnostics());
1558
1559 // Create the target instance.
1560 Clang->getTargetOpts().Features = AST->TargetFeatures;
1561 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1562 Clang->getTargetOpts()));
1563 if (!Clang->hasTarget())
1564 return 0;
1565
1566 // Inform the target of the language options.
1567 //
1568 // FIXME: We shouldn't need to do this, the target should be immutable once
1569 // created. This complexity should be lifted elsewhere.
1570 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1571
1572 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1573 "Invocation must have exactly one source file!");
1574 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1575 "FIXME: AST inputs not yet supported here!");
1576 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1577 "IR inputs not supported here!");
1578
1579 // Configure the various subsystems.
1580 AST->FileSystemOpts = Clang->getFileSystemOpts();
1581 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1582 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1583 AST->TheSema.reset();
1584 AST->Ctx = 0;
1585 AST->PP = 0;
1586
1587 // Create a file manager object to provide access to and cache the filesystem.
1588 Clang->setFileManager(&AST->getFileManager());
1589
1590 // Create the source manager.
1591 Clang->setSourceManager(&AST->getSourceManager());
1592
1593 ASTFrontendAction *Act = Action;
1594
1595 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1596 if (!Act) {
1597 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1598 Act = TrackerAct.get();
1599 }
1600
1601 // Recover resources if we crash before exiting this method.
1602 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1603 ActCleanup(TrackerAct.get());
1604
1605 if (!Act->BeginSourceFile(*Clang.get(),
1606 Clang->getFrontendOpts().Inputs[0].second,
1607 Clang->getFrontendOpts().Inputs[0].first))
1608 return 0;
1609
1610 Act->Execute();
1611
1612 // Steal the created target, context, and preprocessor.
1613 AST->TheSema.reset(Clang->takeSema());
1614 AST->Consumer.reset(Clang->takeASTConsumer());
1615 AST->Ctx = &Clang->getASTContext();
1616 AST->PP = &Clang->getPreprocessor();
1617 Clang->setSourceManager(0);
1618 Clang->setFileManager(0);
1619 AST->Target = &Clang->getTarget();
1620
1621 Act->EndSourceFile();
1622
1623 return AST.take();
1624}
1625
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001626bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1627 if (!Invocation)
1628 return true;
1629
1630 // We'll manage file buffers ourselves.
1631 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1632 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001633 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001634
Douglas Gregor1aa27302011-01-27 18:02:58 +00001635 // Save the target features.
1636 TargetFeatures = Invocation->getTargetOpts().Features;
1637
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001638 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001639 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001640 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001641 OverrideMainBuffer
1642 = getMainBufferWithPrecompiledPreamble(*Invocation);
1643 }
1644
Douglas Gregor213f18b2010-10-28 15:44:59 +00001645 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001646 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001647
Ted Kremenek25a11e12011-03-22 01:15:24 +00001648 // Recover resources if we crash before exiting this method.
1649 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1650 MemBufferCleanup(OverrideMainBuffer);
1651
Douglas Gregor213f18b2010-10-28 15:44:59 +00001652 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001653}
1654
Douglas Gregorabc563f2010-07-19 21:46:24 +00001655ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1656 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1657 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001658 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001659 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001660 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001661 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001662 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001663 // Create the AST unit.
1664 llvm::OwningPtr<ASTUnit> AST;
1665 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001666 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001667 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001668 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001669 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001670 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001671 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001672 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001673 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001674
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001675 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001676 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1677 ASTUnitCleanup(AST.get());
1678 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1679 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1680 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001681
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001682 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001683}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001684
1685ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1686 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001687 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001688 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001689 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001690 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001691 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001692 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001693 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001694 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001695 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001696 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001697 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001698 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001699 // No diagnostics engine was provided, so create our own diagnostics object
1700 // with the default options.
1701 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001702 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1703 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001704 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001705
Chris Lattner5f9e2722011-07-23 10:55:15 +00001706 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001707
Ted Kremenek4f327862011-03-21 18:40:17 +00001708 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001709
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001710 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001711
Douglas Gregore47be3e2010-11-11 00:39:14 +00001712 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001713 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001714
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001715 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001716 llvm::makeArrayRef(ArgBegin, ArgEnd),
1717 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001718 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001719 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001720 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001721
Douglas Gregor4db64a42010-01-23 00:14:00 +00001722 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001723 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1724 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1725 if (const llvm::MemoryBuffer *
1726 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1727 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1728 } else {
1729 const char *fname = fileOrBuf.get<const char *>();
1730 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1731 }
1732 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001733 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1734 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001735
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001736 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001737 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001738
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001739 // Create the AST unit.
1740 llvm::OwningPtr<ASTUnit> AST;
1741 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001742 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001743 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001744
1745 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001746 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001747 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001748 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001749 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001750 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1751 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001752 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001753 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001754 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001755
1756 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001757 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1758 ASTUnitCleanup(AST.get());
1759 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1760 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1761 CICleanup(CI.getPtr());
1762 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1763 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1764 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001765
Chris Lattner39b49bc2010-11-23 08:35:12 +00001766 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001767}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001768
1769bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001770 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001771 return true;
1772
Douglas Gregor213f18b2010-10-28 15:44:59 +00001773 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001774 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001775
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001776 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001777 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001778 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001779 for (PreprocessorOptions::remapped_file_buffer_iterator
1780 R = PPOpts.remapped_file_buffer_begin(),
1781 REnd = PPOpts.remapped_file_buffer_end();
1782 R != REnd;
1783 ++R) {
1784 delete R->second;
1785 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001786 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001787 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1788 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1789 if (const llvm::MemoryBuffer *
1790 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1791 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1792 memBuf);
1793 } else {
1794 const char *fname = fileOrBuf.get<const char *>();
1795 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1796 fname);
1797 }
1798 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001799
Douglas Gregoreababfb2010-08-04 05:53:38 +00001800 // If we have a preamble file lying around, or if we might try to
1801 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001802 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001803 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001804 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001805
Douglas Gregorabc563f2010-07-19 21:46:24 +00001806 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001807 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001808 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001809 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1810 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001811
Douglas Gregor175c4a92010-07-23 23:58:40 +00001812 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001813 bool Result = Parse(OverrideMainBuffer);
1814
1815 // If we're caching global code-completion results, and the top-level
1816 // declarations have changed, clear out the code-completion cache.
1817 if (!Result && ShouldCacheCodeCompletionResults &&
1818 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1819 CacheCodeCompletionResults();
1820
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001821 // We now need to clear out the completion allocator for
1822 // clang_getCursorCompletionString; it'll be recreated if necessary.
1823 CursorCompletionAllocator = 0;
1824
Douglas Gregor175c4a92010-07-23 23:58:40 +00001825 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001826}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001827
Douglas Gregor87c08a52010-08-13 22:48:40 +00001828//----------------------------------------------------------------------------//
1829// Code completion
1830//----------------------------------------------------------------------------//
1831
1832namespace {
1833 /// \brief Code completion consumer that combines the cached code-completion
1834 /// results from an ASTUnit with the code-completion results provided to it,
1835 /// then passes the result on to
1836 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001837 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001838 ASTUnit &AST;
1839 CodeCompleteConsumer &Next;
1840
1841 public:
1842 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001843 bool IncludeMacros, bool IncludeCodePatterns,
1844 bool IncludeGlobals)
1845 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001846 Next.isOutputBinary()), AST(AST), Next(Next)
1847 {
1848 // Compute the set of contexts in which we will look when we don't have
1849 // any information about the specific context.
1850 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00001851 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1852 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1853 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1854 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1855 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1856 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1857 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1858 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1859 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1860 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1861 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1862 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1863 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001864
Douglas Gregor87c08a52010-08-13 22:48:40 +00001865 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00001866 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1867 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1868 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00001869 }
1870
1871 virtual void ProcessCodeCompleteResults(Sema &S,
1872 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001873 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001874 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001875
1876 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1877 OverloadCandidate *Candidates,
1878 unsigned NumCandidates) {
1879 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1880 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001881
Douglas Gregordae68752011-02-01 22:57:45 +00001882 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00001883 return Next.getAllocator();
1884 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00001885 };
1886}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001887
Douglas Gregor5f808c22010-08-16 21:18:39 +00001888/// \brief Helper function that computes which global names are hidden by the
1889/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001890static void CalculateHiddenNames(const CodeCompletionContext &Context,
1891 CodeCompletionResult *Results,
1892 unsigned NumResults,
1893 ASTContext &Ctx,
1894 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001895 bool OnlyTagNames = false;
1896 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001897 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001898 case CodeCompletionContext::CCC_TopLevel:
1899 case CodeCompletionContext::CCC_ObjCInterface:
1900 case CodeCompletionContext::CCC_ObjCImplementation:
1901 case CodeCompletionContext::CCC_ObjCIvarList:
1902 case CodeCompletionContext::CCC_ClassStructUnion:
1903 case CodeCompletionContext::CCC_Statement:
1904 case CodeCompletionContext::CCC_Expression:
1905 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001906 case CodeCompletionContext::CCC_DotMemberAccess:
1907 case CodeCompletionContext::CCC_ArrowMemberAccess:
1908 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001909 case CodeCompletionContext::CCC_Namespace:
1910 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001911 case CodeCompletionContext::CCC_Name:
1912 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001913 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00001914 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001915 break;
1916
1917 case CodeCompletionContext::CCC_EnumTag:
1918 case CodeCompletionContext::CCC_UnionTag:
1919 case CodeCompletionContext::CCC_ClassOrStructTag:
1920 OnlyTagNames = true;
1921 break;
1922
1923 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001924 case CodeCompletionContext::CCC_MacroName:
1925 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001926 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001927 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001928 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001929 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001930 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001931 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00001932 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001933 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1934 case CodeCompletionContext::CCC_ObjCClassMessage:
1935 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00001936 // We're looking for nothing, or we're looking for names that cannot
1937 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001938 return;
1939 }
1940
John McCall0a2c5e22010-08-25 06:19:51 +00001941 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001942 for (unsigned I = 0; I != NumResults; ++I) {
1943 if (Results[I].Kind != Result::RK_Declaration)
1944 continue;
1945
1946 unsigned IDNS
1947 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1948
1949 bool Hiding = false;
1950 if (OnlyTagNames)
1951 Hiding = (IDNS & Decl::IDNS_Tag);
1952 else {
1953 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001954 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1955 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001956 if (Ctx.getLangOptions().CPlusPlus)
1957 HiddenIDNS |= Decl::IDNS_Tag;
1958 Hiding = (IDNS & HiddenIDNS);
1959 }
1960
1961 if (!Hiding)
1962 continue;
1963
1964 DeclarationName Name = Results[I].Declaration->getDeclName();
1965 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1966 HiddenNames.insert(Identifier->getName());
1967 else
1968 HiddenNames.insert(Name.getAsString());
1969 }
1970}
1971
1972
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001973void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1974 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001975 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001976 unsigned NumResults) {
1977 // Merge the results we were given with the results we cached.
1978 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001979 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001980 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00001981 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00001982 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001983 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00001984 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001985 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001986 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001987 C = AST.cached_completion_begin(),
1988 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001989 C != CEnd; ++C) {
1990 // If the context we are in matches any of the contexts we are
1991 // interested in, we'll add this result.
1992 if ((C->ShowInContexts & InContexts) == 0)
1993 continue;
1994
1995 // If we haven't added any results previously, do so now.
1996 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001997 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1998 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001999 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2000 AddedResult = true;
2001 }
2002
Douglas Gregor5f808c22010-08-16 21:18:39 +00002003 // Determine whether this global completion result is hidden by a local
2004 // completion result. If so, skip it.
2005 if (C->Kind != CXCursor_MacroDefinition &&
2006 HiddenNames.count(C->Completion->getTypedText()))
2007 continue;
2008
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002009 // Adjust priority based on similar type classes.
2010 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002011 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002012 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002013 if (!Context.getPreferredType().isNull()) {
2014 if (C->Kind == CXCursor_MacroDefinition) {
2015 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002016 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002017 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002018 } else if (C->Type) {
2019 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002020 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002021 Context.getPreferredType().getUnqualifiedType());
2022 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2023 if (ExpectedSTC == C->TypeClass) {
2024 // We know this type is similar; check for an exact match.
2025 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002026 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002027 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002028 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002029 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2030 Priority /= CCF_ExactTypeMatch;
2031 else
2032 Priority /= CCF_SimilarTypeMatch;
2033 }
2034 }
2035 }
2036
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002037 // Adjust the completion string, if required.
2038 if (C->Kind == CXCursor_MacroDefinition &&
2039 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2040 // Create a new code-completion string that just contains the
2041 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002042 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2043 C->Availability);
2044 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002045 CursorKind = CXCursor_NotImplemented;
2046 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002047 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002048 }
2049
Douglas Gregor4125c372010-08-25 18:03:13 +00002050 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002051 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002052 }
2053
2054 // If we did not add any cached completion results, just forward the
2055 // results we were given to the next consumer.
2056 if (!AddedResult) {
2057 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2058 return;
2059 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002060
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002061 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2062 AllResults.size());
2063}
2064
2065
2066
Chris Lattner5f9e2722011-07-23 10:55:15 +00002067void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002068 RemappedFile *RemappedFiles,
2069 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002070 bool IncludeMacros,
2071 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002072 CodeCompleteConsumer &Consumer,
2073 Diagnostic &Diag, LangOptions &LangOpts,
2074 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002075 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2076 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002077 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002078 return;
2079
Douglas Gregor213f18b2010-10-28 15:44:59 +00002080 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002081 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002082 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002083
Ted Kremenek4f327862011-03-21 18:40:17 +00002084 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2085 CCInvocation(new CompilerInvocation(*Invocation));
2086
2087 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2088 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002089
Douglas Gregor87c08a52010-08-13 22:48:40 +00002090 FrontendOpts.ShowMacrosInCodeCompletion
2091 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002092 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002093 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2094 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002095 FrontendOpts.CodeCompletionAt.FileName = File;
2096 FrontendOpts.CodeCompletionAt.Line = Line;
2097 FrontendOpts.CodeCompletionAt.Column = Column;
2098
2099 // Set the language options appropriately.
Ted Kremenek4f327862011-03-21 18:40:17 +00002100 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002101
Ted Kremenek03201fb2011-03-21 18:40:07 +00002102 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2103
2104 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002105 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2106 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002107
Ted Kremenek4f327862011-03-21 18:40:17 +00002108 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002109 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002110
2111 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002112 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002113 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002114 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002115 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002116 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002117
2118 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002119 Clang->getTargetOpts().Features = TargetFeatures;
2120 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2121 Clang->getTargetOpts()));
2122 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002123 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002124 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002125 }
2126
2127 // Inform the target of the language options.
2128 //
2129 // FIXME: We shouldn't need to do this, the target should be immutable once
2130 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002131 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002132
Ted Kremenek03201fb2011-03-21 18:40:07 +00002133 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002134 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002135 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002136 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002137 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002138 "IR inputs not support here!");
2139
2140
2141 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002142 Clang->setFileManager(&FileMgr);
2143 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002144
2145 // Remap files.
2146 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002147 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002148 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002149 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2150 if (const llvm::MemoryBuffer *
2151 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2152 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2153 OwnedBuffers.push_back(memBuf);
2154 } else {
2155 const char *fname = fileOrBuf.get<const char *>();
2156 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2157 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002158 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002159
Douglas Gregor87c08a52010-08-13 22:48:40 +00002160 // Use the code completion consumer we were given, but adding any cached
2161 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002162 AugmentedCodeCompleteConsumer *AugmentedConsumer
2163 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2164 FrontendOpts.ShowMacrosInCodeCompletion,
2165 FrontendOpts.ShowCodePatternsInCodeCompletion,
2166 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002167 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002168
Douglas Gregordf95a132010-08-09 20:45:32 +00002169 // If we have a precompiled preamble, try to use it. We only allow
2170 // the use of the precompiled preamble if we're if the completion
2171 // point is within the main file, after the end of the precompiled
2172 // preamble.
2173 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2174 if (!PreambleFile.empty()) {
2175 using llvm::sys::FileStatus;
2176 llvm::sys::PathWithStatus CompleteFilePath(File);
2177 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2178 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2179 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002180 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2181 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002182 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002183 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002184 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002185 }
2186
2187 // If the main file has been overridden due to the use of a preamble,
2188 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002189 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002190 StoredDiagnostics.insert(StoredDiagnostics.end(),
2191 this->StoredDiagnostics.begin(),
2192 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00002193 if (OverrideMainBuffer) {
2194 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2195 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2196 PreprocessorOpts.PrecompiledPreambleBytes.second
2197 = PreambleEndsAtStartOfLine;
2198 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2199 PreprocessorOpts.DisablePCHValidation = true;
2200
Douglas Gregor2283d792010-08-20 00:59:43 +00002201 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002202 } else {
2203 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2204 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002205 }
2206
Douglas Gregordca8ee82011-05-06 16:33:08 +00002207 // Disable the preprocessing record
2208 PreprocessorOpts.DetailedRecord = false;
2209
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002210 llvm::OwningPtr<SyntaxOnlyAction> Act;
2211 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002212 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2213 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002214 if (OverrideMainBuffer) {
Jonathan D. Turner9461fcc2011-07-22 17:25:03 +00002215 std::string ModName = PreambleFile;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002216 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2217 getSourceManager(), PreambleDiagnostics,
2218 StoredDiagnostics);
2219 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002220 Act->Execute();
2221 Act->EndSourceFile();
2222 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002223}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002224
Chris Lattner5f9e2722011-07-23 10:55:15 +00002225CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002226 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002227 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002228
2229 // Write to a temporary file and later rename it to the actual file, to avoid
2230 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002231 llvm::SmallString<128> TempPath;
2232 TempPath = File;
2233 TempPath += "-%%%%%%%%";
2234 int fd;
2235 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2236 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002237 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002238
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002239 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2240 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002241 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002242
2243 serialize(Out);
2244 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002245 if (Out.has_error())
2246 return CXSaveError_Unknown;
2247
2248 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2249 bool exists;
2250 llvm::sys::fs::remove(TempPath.str(), exists);
2251 return CXSaveError_Unknown;
2252 }
2253
2254 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002255}
2256
Chris Lattner5f9e2722011-07-23 10:55:15 +00002257bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002258 if (getDiagnostics().hasErrorOccurred())
2259 return true;
2260
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002261 std::vector<unsigned char> Buffer;
2262 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002263 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002264 // FIXME: Handle modules
2265 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002266
2267 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002268 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002269 OS.write((char *)&Buffer.front(), Buffer.size());
2270
2271 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002272}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002273
2274typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2275
2276static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2277 unsigned Raw = L.getRawEncoding();
2278 const unsigned MacroBit = 1U << 31;
2279 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2280 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2281}
2282
2283void ASTUnit::TranslateStoredDiagnostics(
2284 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002285 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002286 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002287 const SmallVectorImpl<StoredDiagnostic> &Diags,
2288 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002289 // The stored diagnostic has the old source manager in it; update
2290 // the locations to refer into the new source manager. We also need to remap
2291 // all the locations to the new view. This includes the diag location, any
2292 // associated source ranges, and the source ranges of associated fix-its.
2293 // FIXME: There should be a cleaner way to do this.
2294
Chris Lattner5f9e2722011-07-23 10:55:15 +00002295 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002296 Result.reserve(Diags.size());
2297 assert(MMan && "Don't have a module manager");
Jonathan D. Turner48d2c3f2011-07-26 18:21:30 +00002298 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002299 assert(Mod && "Don't have preamble module");
2300 SLocRemap &Remap = Mod->SLocRemap;
2301 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2302 // Rebuild the StoredDiagnostic.
2303 const StoredDiagnostic &SD = Diags[I];
2304 SourceLocation L = SD.getLocation();
2305 TranslateSLoc(L, Remap);
2306 FullSourceLoc Loc(L, SrcMgr);
2307
Chris Lattner5f9e2722011-07-23 10:55:15 +00002308 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002309 Ranges.reserve(SD.range_size());
2310 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2311 E = SD.range_end();
2312 I != E; ++I) {
2313 SourceLocation BL = I->getBegin();
2314 TranslateSLoc(BL, Remap);
2315 SourceLocation EL = I->getEnd();
2316 TranslateSLoc(EL, Remap);
2317 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2318 }
2319
Chris Lattner5f9e2722011-07-23 10:55:15 +00002320 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002321 FixIts.reserve(SD.fixit_size());
2322 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2323 E = SD.fixit_end();
2324 I != E; ++I) {
2325 FixIts.push_back(FixItHint());
2326 FixItHint &FH = FixIts.back();
2327 FH.CodeToInsert = I->CodeToInsert;
2328 SourceLocation BL = I->RemoveRange.getBegin();
2329 TranslateSLoc(BL, Remap);
2330 SourceLocation EL = I->RemoveRange.getEnd();
2331 TranslateSLoc(EL, Remap);
2332 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2333 I->RemoveRange.isTokenRange());
2334 }
2335
2336 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2337 SD.getMessage(), Loc, Ranges, FixIts));
2338 }
2339 Result.swap(Out);
2340}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002341
2342SourceLocation ASTUnit::getLocation(const FileEntry *File,
2343 unsigned Line, unsigned Col) const {
2344 const SourceManager &SM = getSourceManager();
2345 SourceLocation Loc;
2346 if (!Preamble.empty() && Line <= Preamble.getNumLines())
2347 Loc = SM.translateLineCol(SM.getPreambleFileID(), Line, Col);
2348 else
2349 Loc = SM.translateFileLineCol(File, Line, Col);
2350
2351 return SM.getMacroArgExpandedLocation(Loc);
2352}
2353
2354SourceLocation ASTUnit::getLocation(const FileEntry *File,
2355 unsigned Offset) const {
2356 const SourceManager &SM = getSourceManager();
2357 SourceLocation FileLoc;
2358 if (!Preamble.empty() && Offset < Preamble.size())
2359 FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
2360 else
2361 FileLoc = SM.translateFileLineCol(File, 1, 1);
2362
2363 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2364}
2365
2366void ASTUnit::PreambleData::countLines() const {
2367 NumLines = 0;
2368 if (empty())
2369 return;
2370
2371 for (std::vector<char>::const_iterator
2372 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2373 if (*I == '\n')
2374 ++NumLines;
2375 }
2376 if (Buffer.back() != '\n')
2377 ++NumLines;
2378}