blob: c2c67c122912ab365f2265929563215d85d8675b [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000032#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000035#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000036#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000038#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000039#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000040#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000041#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000046#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000047#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000048#include "llvm/Support/Mutex.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000049#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000050#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000051#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000052#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000053using namespace clang;
54
Douglas Gregor16896c42010-10-28 15:44:59 +000055using llvm::TimeRecord;
56
57namespace {
58 class SimpleTimer {
59 bool WantTiming;
60 TimeRecord Start;
61 std::string Output;
62
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000064 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000065 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000066 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000067 }
68
Chris Lattner0e62c1c2011-07-23 10:55:15 +000069 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000070 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000071 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000072 }
73
Douglas Gregor16896c42010-10-28 15:44:59 +000074 ~SimpleTimer() {
75 if (WantTiming) {
76 TimeRecord Elapsed = TimeRecord::getCurrentTime();
77 Elapsed -= Start;
78 llvm::errs() << Output << ':';
79 Elapsed.print(Elapsed, llvm::errs());
80 llvm::errs() << '\n';
81 }
82 }
83 };
84}
85
Douglas Gregorbb420ab2010-08-04 05:53:38 +000086/// \brief After failing to build a precompiled preamble (due to
87/// errors in the source that occurs in the preamble), the number of
88/// reparses during which we'll skip even trying to precompile the
89/// preamble.
90const unsigned DefaultPreambleRebuildInterval = 5;
91
Douglas Gregor68dbaea2010-11-17 00:13:31 +000092/// \brief Tracks the number of ASTUnit objects that are currently active.
93///
94/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000095static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +000096
Douglas Gregord03e8232010-04-05 21:10:19 +000097ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +000098 : OnlyLocalDecls(false), CaptureDiagnostics(false),
99 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000100 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000101 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000102 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000103 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000104 ShouldCacheCodeCompletionResults(false),
Chandler Carruthde81fc82011-07-14 09:02:10 +0000105 NestedMacroExpansions(true),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000106 CompletionCacheTopLevelHashValue(0),
107 PreambleTopLevelHashValue(0),
108 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000109 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000110 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000111 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000112 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
113 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000114}
Douglas Gregord03e8232010-04-05 21:10:19 +0000115
Daniel Dunbar764c0822009-12-01 09:51:01 +0000116ASTUnit::~ASTUnit() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000117 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000118 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000119 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000120
121 // Free the buffers associated with remapped files. We are required to
122 // perform this operation here because we explicitly request that the
123 // compiler instance *not* free these buffers for each invocation of the
124 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000125 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000126 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
127 for (PreprocessorOptions::remapped_file_buffer_iterator
128 FB = PPOpts.remapped_file_buffer_begin(),
129 FBEnd = PPOpts.remapped_file_buffer_end();
130 FB != FBEnd;
131 ++FB)
132 delete FB->second;
133 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000134
135 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000136 delete PreambleBuffer;
137
Douglas Gregor16896c42010-10-28 15:44:59 +0000138 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000139
140 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000141 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000142 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
143 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000144}
145
146void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000147 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
148 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000149 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000150}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000151
Douglas Gregor39982192010-08-15 06:18:01 +0000152/// \brief Determine the set of code-completion contexts in which this
153/// declaration should be shown.
154static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000155 const LangOptions &LangOpts,
156 bool &IsNestedNameSpecifier) {
157 IsNestedNameSpecifier = false;
158
Douglas Gregor39982192010-08-15 06:18:01 +0000159 if (isa<UsingShadowDecl>(ND))
160 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
161 if (!ND)
162 return 0;
163
164 unsigned Contexts = 0;
165 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
166 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
167 // Types can appear in these contexts.
168 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
169 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
170 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
171 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
172 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000173 | (1 << (CodeCompletionContext::CCC_Type - 1))
174 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000175
176 // In C++, types can appear in expressions contexts (for functional casts).
177 if (LangOpts.CPlusPlus)
178 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
179
180 // In Objective-C, message sends can send interfaces. In Objective-C++,
181 // all types are available due to functional casts.
182 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
183 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000184
185 // In Objective-C, you can only be a subclass of another Objective-C class
186 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor2c595ad2011-07-30 06:55:39 +0000187 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000188
189 // Deal with tag names.
190 if (isa<EnumDecl>(ND)) {
191 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
192
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000194 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000195 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000196 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
197 if (Record->isUnion())
198 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
199 else
200 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
201
Douglas Gregor39982192010-08-15 06:18:01 +0000202 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000203 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000204 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000205 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000206 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
207 // Values can appear in these contexts.
208 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
209 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000210 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000211 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
212 } else if (isa<ObjCProtocolDecl>(ND)) {
213 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000214 } else if (isa<ObjCCategoryDecl>(ND)) {
215 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000216 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000217 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000218
219 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000220 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000221 }
222
223 return Contexts;
224}
225
Douglas Gregorb14904c2010-08-13 22:48:40 +0000226void ASTUnit::CacheCodeCompletionResults() {
227 if (!TheSema)
228 return;
229
Douglas Gregor16896c42010-10-28 15:44:59 +0000230 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000231 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000232
233 // Clear out the previous results.
234 ClearCachedCompletionResults();
235
236 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000237 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000238 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000239 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
240 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000241
242 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000243 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
244
Douglas Gregorb14904c2010-08-13 22:48:40 +0000245 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
246 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000247 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000248 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000249 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000250 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000251 *CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000252 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000253 Ctx->getLangOptions(),
254 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000255 CachedResult.Priority = Results[I].Priority;
256 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000257 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000258
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000259 // Keep track of the type of this completion in an ASTContext-agnostic
260 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000261 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000262 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000263 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000264 CachedResult.Type = 0;
265 } else {
266 CanQualType CanUsageType
267 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
268 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
269
270 // Determine whether we have already seen this type. If so, we save
271 // ourselves the work of formatting the type string by using the
272 // temporary, CanQualType-based hash table to find the associated value.
273 unsigned &TypeValue = CompletionTypes[CanUsageType];
274 if (TypeValue == 0) {
275 TypeValue = CompletionTypes.size();
276 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
277 = TypeValue;
278 }
279
280 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000281 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000282
Douglas Gregor39982192010-08-15 06:18:01 +0000283 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000284
285 /// Handle nested-name-specifiers in C++.
286 if (TheSema->Context.getLangOptions().CPlusPlus &&
287 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
288 // The contexts in which a nested-name-specifier can appear in C++.
289 unsigned NNSContexts
290 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
291 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
292 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
293 | (1 << (CodeCompletionContext::CCC_Statement - 1))
294 | (1 << (CodeCompletionContext::CCC_Expression - 1))
295 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
296 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
297 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
298 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000299 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000300 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
301 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000302
303 if (isa<NamespaceDecl>(Results[I].Declaration) ||
304 isa<NamespaceAliasDecl>(Results[I].Declaration))
305 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
306
307 if (unsigned RemainingContexts
308 = NNSContexts & ~CachedResult.ShowInContexts) {
309 // If there any contexts where this completion can be a
310 // nested-name-specifier but isn't already an option, create a
311 // nested-name-specifier completion.
312 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000313 CachedResult.Completion
314 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000315 *CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000316 CachedResult.ShowInContexts = RemainingContexts;
317 CachedResult.Priority = CCP_NestedNameSpecifier;
318 CachedResult.TypeClass = STC_Void;
319 CachedResult.Type = 0;
320 CachedCompletionResults.push_back(CachedResult);
321 }
322 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000323 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000324 }
325
Douglas Gregorb14904c2010-08-13 22:48:40 +0000326 case Result::RK_Keyword:
327 case Result::RK_Pattern:
328 // Ignore keywords and patterns; we don't care, since they are so
329 // easily regenerated.
330 break;
331
332 case Result::RK_Macro: {
333 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000334 CachedResult.Completion
335 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000336 *CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000337 CachedResult.ShowInContexts
338 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
339 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
340 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
341 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
342 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
343 | (1 << (CodeCompletionContext::CCC_Statement - 1))
344 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000345 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000346 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000347 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000348 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
349 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000350
Douglas Gregorb14904c2010-08-13 22:48:40 +0000351 CachedResult.Priority = Results[I].Priority;
352 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000353 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000354 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000355 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000356 CachedCompletionResults.push_back(CachedResult);
357 break;
358 }
359 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000360 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000361
362 // Save the current top-level hash value.
363 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000364}
365
366void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000367 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000368 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000369 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000370}
371
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000372namespace {
373
Sebastian Redl2c499f62010-08-18 23:56:43 +0000374/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000375/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000376class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000377 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000378 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000379 LangOptions &LangOpt;
380 HeaderSearch &HSI;
Douglas Gregor83297df2011-09-01 23:39:15 +0000381 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000382 std::string &Predefines;
383 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000384
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000385 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000386
Douglas Gregore8bbc122011-09-02 00:18:52 +0000387 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000388public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000389 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
390 HeaderSearch &HSI,
Douglas Gregor83297df2011-09-01 23:39:15 +0000391 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
392 std::string &Predefines,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000393 unsigned &Counter)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000394 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor83297df2011-09-01 23:39:15 +0000395 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000396 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000397
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000398 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000399 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000400 return false;
401
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000402 LangOpt = LangOpts;
Douglas Gregor83297df2011-09-01 23:39:15 +0000403
404 // Initialize the preprocessor.
405 PP.Initialize(*Target);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000406
407 // Initialize the ASTContext
408 Context.InitBuiltinTypes(*Target);
409
410 InitializedLanguage = true;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000411 return false;
412 }
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000414 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000415 // If we've already initialized the target, don't do it again.
416 if (Target)
417 return false;
418
419 // FIXME: This is broken, we should store the TargetOptions in the AST file.
420 TargetOptions TargetOpts;
421 TargetOpts.ABI = "";
422 TargetOpts.CXXABI = "";
423 TargetOpts.CPU = "";
424 TargetOpts.Features.clear();
425 TargetOpts.Triple = Triple;
426 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000427 return false;
428 }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Sebastian Redl8b41f302010-07-14 23:29:55 +0000430 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000431 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000432 std::string &SuggestedPredefines,
433 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000434 Predefines = Buffers[0].Data;
435 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
436 Predefines += Buffers[I].Data;
437 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000438 return false;
439 }
Mike Stump11289f42009-09-09 15:08:12 +0000440
Douglas Gregora2f49452010-03-16 19:09:18 +0000441 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000442 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
443 }
Mike Stump11289f42009-09-09 15:08:12 +0000444
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000445 virtual void ReadCounter(unsigned Value) {
446 Counter = Value;
447 }
448};
449
David Blaikief18d91a2011-09-26 00:01:39 +0000450class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000451 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000452
453public:
David Blaikief18d91a2011-09-26 00:01:39 +0000454 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000455 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000456 : StoredDiags(StoredDiags) { }
457
David Blaikie9c902b52011-09-25 23:23:43 +0000458 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000459 const Diagnostic &Info);
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000460
461 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
462 // Just drop any diagnostics that come from cloned consumers; they'll
463 // have different source managers anyway.
464 return new IgnoringDiagConsumer();
465 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000466};
467
468/// \brief RAII object that optionally captures diagnostics, if
469/// there is no diagnostic client to capture them already.
470class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000471 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000472 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000473 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000474
475public:
David Blaikie9c902b52011-09-25 23:23:43 +0000476 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000477 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000478 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000479 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000480 if (RequestCapture || Diags.getClient() == 0) {
481 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000482 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000483 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000484 }
485
486 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000487 if (Diags.getClient() == &Client) {
488 Diags.takeClient();
489 Diags.setClient(PreviousClient);
490 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000491 }
492};
493
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494} // anonymous namespace
495
David Blaikief18d91a2011-09-26 00:01:39 +0000496void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000497 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000498 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000499 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000500
Douglas Gregor33cdd812010-02-18 18:08:43 +0000501 StoredDiags.push_back(StoredDiagnostic(Level, Info));
502}
503
Steve Naroffc0683b92009-09-03 18:19:54 +0000504const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000505 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000506}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000507
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000509 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000510 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000511 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000512}
513
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000514/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikie9c902b52011-09-25 23:23:43 +0000515void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000516 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000517 ASTUnit &AST, bool CaptureDiagnostics) {
518 if (!Diags.getPtr()) {
519 // No diagnostics engine was provided, so create our own diagnostics object
520 // with the default options.
521 DiagnosticOptions DiagOpts;
David Blaikiee2eefae2011-09-25 23:39:51 +0000522 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000523 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000524 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000525 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
526 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000527 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000528 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000529 }
530}
531
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000532ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikie9c902b52011-09-25 23:23:43 +0000533 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000534 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000535 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000536 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000537 unsigned NumRemappedFiles,
538 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000539 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000540
541 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000542 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
543 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000544 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
545 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000546 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000547
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000548 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000549
Douglas Gregor16bef852009-10-16 20:01:17 +0000550 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000551 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000552 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000553 AST->FileMgr = new FileManager(FileSystemOpts);
554 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
555 AST->getFileManager());
Chris Lattner5159f612010-11-23 08:35:12 +0000556 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000557
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000558 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000559 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
560 if (const llvm::MemoryBuffer *
561 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
562 // Create the file entry for the file that we're mapping from.
563 const FileEntry *FromFile
564 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
565 memBuf->getBufferSize(),
566 0);
567 if (!FromFile) {
568 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
569 << RemappedFiles[I].first;
570 delete memBuf;
571 continue;
572 }
573
574 // Override the contents of the "from" file with the contents of
575 // the "to" file.
576 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
577
578 } else {
579 const char *fname = fileOrBuf.get<const char *>();
580 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
581 if (!ToFile) {
582 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
583 << RemappedFiles[I].first << fname;
584 continue;
585 }
586
587 // Create the file entry for the file that we're mapping from.
588 const FileEntry *FromFile
589 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
590 ToFile->getSize(),
591 0);
592 if (!FromFile) {
593 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
594 << RemappedFiles[I].first;
595 delete memBuf;
596 continue;
597 }
598
599 // Override the contents of the "from" file with the contents of
600 // the "to" file.
601 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000602 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000603 }
604
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000605 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000606
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000607 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000608 std::string Predefines;
609 unsigned Counter;
610
Sebastian Redl2c499f62010-08-18 23:56:43 +0000611 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000612
Douglas Gregor83297df2011-09-01 23:39:15 +0000613 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
614 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
615 *AST,
616 /*IILookup=*/0,
617 /*OwnsHeaderSearch=*/false,
618 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000619 Preprocessor &PP = *AST->PP;
620
621 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
622 AST->getSourceManager(),
623 /*Target=*/0,
624 PP.getIdentifierTable(),
625 PP.getSelectorTable(),
626 PP.getBuiltinInfo(),
627 /* size_reserve = */0,
628 /*DelayInitialization=*/true);
629 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000630
Douglas Gregor8835e032011-09-02 00:26:20 +0000631 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000632
633 // Recover resources if we crash before exiting this method.
634 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
635 ReaderCleanup(Reader.get());
636
Douglas Gregore8bbc122011-09-02 00:18:52 +0000637 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor83297df2011-09-01 23:39:15 +0000638 AST->ASTFileLangOpts, HeaderInfo,
639 AST->Target, Predefines, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000640
Douglas Gregora6895d82011-07-22 16:00:58 +0000641 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000642 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000643 break;
Mike Stump11289f42009-09-09 15:08:12 +0000644
Sebastian Redl2c499f62010-08-18 23:56:43 +0000645 case ASTReader::Failure:
646 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000647 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000648 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000649 }
Mike Stump11289f42009-09-09 15:08:12 +0000650
Daniel Dunbara8a50932009-12-02 08:44:16 +0000651 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
652
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000653 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000654 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000655
Sebastian Redl2c499f62010-08-18 23:56:43 +0000656 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000657 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000658 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000659 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000660 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000661
662 // Unregister the cleanup for ASTReader. It will get cleaned up
663 // by the ASTUnit cleanup.
664 ReaderCleanup.unregister();
665
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000666 Context.setExternalSource(Source);
667
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000668 // Create an AST consumer, even though it isn't used.
669 AST->Consumer.reset(new ASTConsumer);
670
Sebastian Redl2c499f62010-08-18 23:56:43 +0000671 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000672 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
673 AST->TheSema->Initialize();
674 ReaderPtr->InitializeSema(*AST->TheSema);
675
Mike Stump11289f42009-09-09 15:08:12 +0000676 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000677}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000678
679namespace {
680
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000681/// \brief Preprocessor callback class that updates a hash value with the names
682/// of all macros that have been defined by the translation unit.
683class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
684 unsigned &Hash;
685
686public:
687 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
688
689 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
690 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
691 }
692};
693
694/// \brief Add the given declaration to the hash of all top-level entities.
695void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
696 if (!D)
697 return;
698
699 DeclContext *DC = D->getDeclContext();
700 if (!DC)
701 return;
702
703 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
704 return;
705
706 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
707 if (ND->getIdentifier())
708 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
709 else if (DeclarationName Name = ND->getDeclName()) {
710 std::string NameStr = Name.getAsString();
711 Hash = llvm::HashString(NameStr, Hash);
712 }
713 return;
714 }
715
716 if (ObjCForwardProtocolDecl *Forward
717 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
718 for (ObjCForwardProtocolDecl::protocol_iterator
719 P = Forward->protocol_begin(),
720 PEnd = Forward->protocol_end();
721 P != PEnd; ++P)
722 AddTopLevelDeclarationToHash(*P, Hash);
723 return;
724 }
725
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000726 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000727 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000728 return;
729 }
730}
731
Daniel Dunbar644dca02009-12-04 08:17:33 +0000732class TopLevelDeclTrackerConsumer : public ASTConsumer {
733 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000734 unsigned &Hash;
735
Daniel Dunbar644dca02009-12-04 08:17:33 +0000736public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000737 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
738 : Unit(_Unit), Hash(Hash) {
739 Hash = 0;
740 }
741
Daniel Dunbar644dca02009-12-04 08:17:33 +0000742 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000743 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
744 Decl *D = *it;
745 // FIXME: Currently ObjC method declarations are incorrectly being
746 // reported as top-level declarations, even though their DeclContext
747 // is the containing ObjC @interface/@implementation. This is a
748 // fundamental problem in the parser right now.
749 if (isa<ObjCMethodDecl>(D))
750 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000751
752 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000753 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000754 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000755 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000756
757 // We're not interested in "interesting" decls.
758 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000759};
760
761class TopLevelDeclTrackerAction : public ASTFrontendAction {
762public:
763 ASTUnit &Unit;
764
Daniel Dunbar764c0822009-12-01 09:51:01 +0000765 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000766 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000767 CI.getPreprocessor().addPPCallbacks(
768 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
769 return new TopLevelDeclTrackerConsumer(Unit,
770 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000771 }
772
773public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000774 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
775
Daniel Dunbar764c0822009-12-01 09:51:01 +0000776 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000777 virtual TranslationUnitKind getTranslationUnitKind() {
778 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000779 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000780};
781
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000782class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000783 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000784 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000785 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000786
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000787public:
Douglas Gregor36db4f92011-08-25 22:35:51 +0000788 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000789 StringRef isysroot, raw_ostream *Out)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000790 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000791 Hash(Unit.getCurrentTopLevelHashValue()) {
792 Hash = 0;
793 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000794
Douglas Gregore9db88f2010-08-03 19:06:41 +0000795 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000796 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
797 Decl *D = *it;
798 // FIXME: Currently ObjC method declarations are incorrectly being
799 // reported as top-level declarations, even though their DeclContext
800 // is the containing ObjC @interface/@implementation. This is a
801 // fundamental problem in the parser right now.
802 if (isa<ObjCMethodDecl>(D))
803 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000804 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000805 TopLevelDecls.push_back(D);
806 }
807 }
808
809 virtual void HandleTranslationUnit(ASTContext &Ctx) {
810 PCHGenerator::HandleTranslationUnit(Ctx);
811 if (!Unit.getDiagnostics().hasErrorOccurred()) {
812 // Translate the top-level declarations we captured during
813 // parsing into declaration IDs in the precompiled
814 // preamble. This will allow us to deserialize those top-level
815 // declarations when requested.
816 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
817 Unit.addTopLevelDeclFromPreamble(
818 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000819 }
820 }
821};
822
823class PrecompilePreambleAction : public ASTFrontendAction {
824 ASTUnit &Unit;
825
826public:
827 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
828
829 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000830 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000831 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000832 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000833 raw_ostream *OS = 0;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000834 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
835 OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000836 OS))
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000837 return 0;
838
Douglas Gregorc567ba22011-07-22 16:35:34 +0000839 if (!CI.getFrontendOpts().RelocatablePCH)
840 Sysroot.clear();
841
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000842 CI.getPreprocessor().addPPCallbacks(
843 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor36db4f92011-08-25 22:35:51 +0000844 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
845 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000846 }
847
848 virtual bool hasCodeCompletionSupport() const { return false; }
849 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000850 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000851};
852
Daniel Dunbar764c0822009-12-01 09:51:01 +0000853}
854
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000855/// Parse the source file into a translation unit using the given compiler
856/// invocation, replacing the current translation unit.
857///
858/// \returns True if a failure occurred that causes the ASTUnit not to
859/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000860bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000861 delete SavedMainFileBuffer;
862 SavedMainFileBuffer = 0;
863
Ted Kremenek5e14d392011-03-21 18:40:17 +0000864 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000865 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000866 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000867 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000868
Daniel Dunbar764c0822009-12-01 09:51:01 +0000869 // Create the compiler instance to use for building the AST.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000870 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
871
872 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000873 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
874 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +0000875
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +0000876 llvm::IntrusiveRefCntPtr<CompilerInvocation>
877 CCInvocation(new CompilerInvocation(*Invocation));
878
879 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek84de4a12011-03-21 18:40:07 +0000880 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000881
Douglas Gregor8e984da2010-08-04 16:47:14 +0000882 // Set up diagnostics, capturing any diagnostics that would
883 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000884 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000885
Daniel Dunbar764c0822009-12-01 09:51:01 +0000886 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000887 Clang->getTargetOpts().Features = TargetFeatures;
888 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +0000889 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +0000890 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000891 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000892 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000893 }
894
Daniel Dunbar764c0822009-12-01 09:51:01 +0000895 // Inform the target of the language options.
896 //
897 // FIXME: We shouldn't need to do this, the target should be immutable once
898 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000899 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000900
Ted Kremenek84de4a12011-03-21 18:40:07 +0000901 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000902 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000903 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000904 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +0000905 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000906 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000907
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000908 // Configure the various subsystems.
909 // FIXME: Should we retain the previous file manager?
Ted Kremenek84de4a12011-03-21 18:40:07 +0000910 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000911 FileMgr = new FileManager(FileSystemOpts);
912 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000913 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000914 Ctx = 0;
915 PP = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000916
917 // Clear out old caches and data.
918 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000919 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000920
Douglas Gregor7b02b582010-08-20 00:02:33 +0000921 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000922 StoredDiagnostics.erase(
923 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
924 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000925 TopLevelDeclsInPreamble.clear();
926 }
927
Daniel Dunbar764c0822009-12-01 09:51:01 +0000928 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000929 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000930
Daniel Dunbar764c0822009-12-01 09:51:01 +0000931 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000932 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000933
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000934 // If the main file has been overridden due to the use of a preamble,
935 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000936 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthde81fc82011-07-14 09:02:10 +0000937 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
938 = NestedMacroExpansions;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000939 if (OverrideMainBuffer) {
940 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
941 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
942 PreprocessorOpts.PrecompiledPreambleBytes.second
943 = PreambleEndsAtStartOfLine;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000944 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000945 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000946
Douglas Gregord9a30af2010-08-02 20:51:39 +0000947 // The stored diagnostic has the old source manager in it; update
948 // the locations to refer into the new source manager. Since we've
949 // been careful to make sure that the source manager's state
950 // before and after are identical, so that we can reuse the source
951 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000952 for (unsigned I = NumStoredDiagnosticsFromDriver,
953 N = StoredDiagnostics.size();
954 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000955 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
956 getSourceManager());
957 StoredDiagnostics[I].setLocation(Loc);
958 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000959
960 // Keep track of the override buffer;
961 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000962 }
963
Ted Kremenek022a4902011-03-22 01:15:24 +0000964 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
965 new TopLevelDeclTrackerAction(*this));
966
967 // Recover resources if we crash before exiting this method.
968 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
969 ActCleanup(Act.get());
970
Ted Kremenek84de4a12011-03-21 18:40:07 +0000971 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
972 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000973 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +0000974
975 if (OverrideMainBuffer) {
Jonathan D. Turner2214acd2011-07-22 17:25:03 +0000976 std::string ModName = PreambleFile;
Douglas Gregor925296b2011-07-19 16:10:42 +0000977 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
978 getSourceManager(), PreambleDiagnostics,
979 StoredDiagnostics);
980 }
981
Daniel Dunbar644dca02009-12-04 08:17:33 +0000982 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000983
Ted Kremenek5e14d392011-03-21 18:40:17 +0000984 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000985 TheSema.reset(Clang->takeSema());
986 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +0000987 Ctx = &Clang->getASTContext();
988 PP = &Clang->getPreprocessor();
989 Clang->setSourceManager(0);
990 Clang->setFileManager(0);
991 Target = &Clang->getTarget();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000992
Daniel Dunbar644dca02009-12-04 08:17:33 +0000993 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000994
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000995 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000996
Daniel Dunbar764c0822009-12-01 09:51:01 +0000997error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000998 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000999 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001000 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001001 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001002 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001003
Douglas Gregorefc46952010-10-12 16:25:54 +00001004 StoredDiagnostics.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001005 return true;
1006}
1007
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001008/// \brief Simple function to retrieve a path for a preamble precompiled header.
1009static std::string GetPreamblePCHPath() {
1010 // FIXME: This is lame; sys::Path should provide this function (in particular,
1011 // it should know how to find the temporary files dir).
1012 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001013 // FIXME: This is a hack so that we can override the preamble file during
1014 // crash-recovery testing, which is the only case where the preamble files
1015 // are not necessarily cleaned up.
1016 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1017 if (TmpFile)
1018 return TmpFile;
1019
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001020 std::string Error;
1021 const char *TmpDir = ::getenv("TMPDIR");
1022 if (!TmpDir)
1023 TmpDir = ::getenv("TEMP");
1024 if (!TmpDir)
1025 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001026#ifdef LLVM_ON_WIN32
1027 if (!TmpDir)
1028 TmpDir = ::getenv("USERPROFILE");
1029#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001030 if (!TmpDir)
1031 TmpDir = "/tmp";
1032 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001033 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001034 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001035 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001036 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001037 return std::string();
1038
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001039 return P.str();
1040}
1041
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001042/// \brief Compute the preamble for the main file, providing the source buffer
1043/// that corresponds to the main file along with a pair (bytes, start-of-line)
1044/// that describes the preamble.
1045std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001046ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1047 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001048 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001049 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001050 CreatedBuffer = false;
1051
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001052 // Try to determine if the main file has been remapped, either from the
1053 // command line (to another file) or directly through the compiler invocation
1054 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001055 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001056 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1057 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1058 // Check whether there is a file-file remapping of the main file
1059 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001060 M = PreprocessorOpts.remapped_file_begin(),
1061 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001062 M != E;
1063 ++M) {
1064 llvm::sys::PathWithStatus MPath(M->first);
1065 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1066 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1067 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001068 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001069 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001070 CreatedBuffer = false;
1071 }
1072
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001073 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001074 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001075 return std::make_pair((llvm::MemoryBuffer*)0,
1076 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001077 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001078 }
1079 }
1080 }
1081
1082 // Check whether there is a file-buffer remapping. It supercedes the
1083 // file-file remapping.
1084 for (PreprocessorOptions::remapped_file_buffer_iterator
1085 M = PreprocessorOpts.remapped_file_buffer_begin(),
1086 E = PreprocessorOpts.remapped_file_buffer_end();
1087 M != E;
1088 ++M) {
1089 llvm::sys::PathWithStatus MPath(M->first);
1090 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1091 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1092 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001093 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001094 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001095 CreatedBuffer = false;
1096 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001097
Douglas Gregor4dde7492010-07-23 23:58:40 +00001098 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001099 }
1100 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001101 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001102 }
1103
1104 // If the main source file was not remapped, load it now.
1105 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001106 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001107 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001108 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001109
1110 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001111 }
1112
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001113 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1114 Invocation.getLangOpts(),
1115 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001116}
1117
Douglas Gregor6481ef12010-07-24 00:38:13 +00001118static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001119 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001120 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001121 llvm::MemoryBuffer *Result
1122 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1123 memcpy(const_cast<char*>(Result->getBufferStart()),
1124 Old->getBufferStart(), Old->getBufferSize());
1125 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001126 ' ', NewSize - Old->getBufferSize() - 1);
1127 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001128
Douglas Gregor6481ef12010-07-24 00:38:13 +00001129 return Result;
1130}
1131
Douglas Gregor4dde7492010-07-23 23:58:40 +00001132/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1133/// the source file.
1134///
1135/// This routine will compute the preamble of the main source file. If a
1136/// non-trivial preamble is found, it will precompile that preamble into a
1137/// precompiled header so that the precompiled preamble can be used to reduce
1138/// reparsing time. If a precompiled preamble has already been constructed,
1139/// this routine will determine if it is still valid and, if so, avoid
1140/// rebuilding the precompiled preamble.
1141///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001142/// \param AllowRebuild When true (the default), this routine is
1143/// allowed to rebuild the precompiled preamble if it is found to be
1144/// out-of-date.
1145///
1146/// \param MaxLines When non-zero, the maximum number of lines that
1147/// can occur within the preamble.
1148///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001149/// \returns If the precompiled preamble can be used, returns a newly-allocated
1150/// buffer that should be used in place of the main file when doing so.
1151/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001152llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001153 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001154 bool AllowRebuild,
1155 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001156
1157 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1158 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1159 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001160 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001161 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001162
1163 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001164 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001165 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001166
Douglas Gregor925296b2011-07-19 16:10:42 +00001167 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor3edb1672010-11-16 20:45:51 +00001168 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1169 if (CreatedPreambleBuffer)
1170 OwnedPreambleBuffer.reset(NewPreamble.first);
1171
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001172 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001173 // We couldn't find a preamble in the main source. Clear out the current
1174 // preamble, if we have one. It's obviously no good any more.
1175 Preamble.clear();
1176 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001177 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001178 PreambleFile.clear();
1179 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001180
1181 // The next time we actually see a preamble, precompile it.
1182 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001183 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001184 }
1185
1186 if (!Preamble.empty()) {
1187 // We've previously computed a preamble. Check whether we have the same
1188 // preamble now that we did before, and that there's enough space in
1189 // the main-file buffer within the precompiled preamble to fit the
1190 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001191 if (Preamble.size() == NewPreamble.second.first &&
1192 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001193 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001194 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001195 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001196 // The preamble has not changed. We may be able to re-use the precompiled
1197 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001198
Douglas Gregor0e119552010-07-31 00:40:00 +00001199 // Check that none of the files used by the preamble have changed.
1200 bool AnyFileChanged = false;
1201
1202 // First, make a record of those files that have been overridden via
1203 // remapping or unsaved_files.
1204 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1205 for (PreprocessorOptions::remapped_file_iterator
1206 R = PreprocessorOpts.remapped_file_begin(),
1207 REnd = PreprocessorOpts.remapped_file_end();
1208 !AnyFileChanged && R != REnd;
1209 ++R) {
1210 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001211 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001212 // If we can't stat the file we're remapping to, assume that something
1213 // horrible happened.
1214 AnyFileChanged = true;
1215 break;
1216 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001217
Douglas Gregor0e119552010-07-31 00:40:00 +00001218 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1219 StatBuf.st_mtime);
1220 }
1221 for (PreprocessorOptions::remapped_file_buffer_iterator
1222 R = PreprocessorOpts.remapped_file_buffer_begin(),
1223 REnd = PreprocessorOpts.remapped_file_buffer_end();
1224 !AnyFileChanged && R != REnd;
1225 ++R) {
1226 // FIXME: Should we actually compare the contents of file->buffer
1227 // remappings?
1228 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1229 0);
1230 }
1231
1232 // Check whether anything has changed.
1233 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1234 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1235 !AnyFileChanged && F != FEnd;
1236 ++F) {
1237 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1238 = OverriddenFiles.find(F->first());
1239 if (Overridden != OverriddenFiles.end()) {
1240 // This file was remapped; check whether the newly-mapped file
1241 // matches up with the previous mapping.
1242 if (Overridden->second != F->second)
1243 AnyFileChanged = true;
1244 continue;
1245 }
1246
1247 // The file was not remapped; check whether it has changed on disk.
1248 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001249 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001250 // If we can't stat the file, assume that something horrible happened.
1251 AnyFileChanged = true;
1252 } else if (StatBuf.st_size != F->second.first ||
1253 StatBuf.st_mtime != F->second.second)
1254 AnyFileChanged = true;
1255 }
1256
1257 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001258 // Okay! We can re-use the precompiled preamble.
1259
1260 // Set the state of the diagnostic object to mimic its state
1261 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001262 // FIXME: This won't catch any #pragma push warning changes that
1263 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001264 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001265 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001266 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001267 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001268
1269 // Create a version of the main file buffer that is padded to
1270 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001271 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001272 PreambleReservedSize,
1273 FrontendOpts.Inputs[0].second);
1274 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001275 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001276
1277 // If we aren't allowed to rebuild the precompiled preamble, just
1278 // return now.
1279 if (!AllowRebuild)
1280 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001281
Douglas Gregor4dde7492010-07-23 23:58:40 +00001282 // We can't reuse the previously-computed preamble. Build a new one.
1283 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001284 PreambleDiagnostics.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001285 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001286 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001287 } else if (!AllowRebuild) {
1288 // We aren't allowed to rebuild the precompiled preamble; just
1289 // return now.
1290 return 0;
1291 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001292
1293 // If the preamble rebuild counter > 1, it's because we previously
1294 // failed to build a preamble and we're not yet ready to try
1295 // again. Decrement the counter and return a failure.
1296 if (PreambleRebuildCounter > 1) {
1297 --PreambleRebuildCounter;
1298 return 0;
1299 }
1300
Douglas Gregore10f0e52010-09-11 17:56:52 +00001301 // Create a temporary file for the precompiled preamble. In rare
1302 // circumstances, this can fail.
1303 std::string PreamblePCHPath = GetPreamblePCHPath();
1304 if (PreamblePCHPath.empty()) {
1305 // Try again next time.
1306 PreambleRebuildCounter = 1;
1307 return 0;
1308 }
1309
Douglas Gregor4dde7492010-07-23 23:58:40 +00001310 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001311 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001312 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001313
1314 // Create a new buffer that stores the preamble. The buffer also contains
1315 // extra space for the original contents of the file (which will be present
1316 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001317 // grows.
1318 PreambleReservedSize = NewPreamble.first->getBufferSize();
1319 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001320 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001321 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322 PreambleReservedSize *= 2;
1323
Douglas Gregord9a30af2010-08-02 20:51:39 +00001324 // Save the preamble text for later; we'll need to compare against it for
1325 // subsequent reparses.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001326 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1327 Preamble.assign(FileMgr->getFile(MainFilename),
1328 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001329 NewPreamble.first->getBufferStart()
1330 + NewPreamble.second.first);
1331 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1332
Douglas Gregora0734c52010-08-19 01:33:06 +00001333 delete PreambleBuffer;
1334 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001335 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001336 FrontendOpts.Inputs[0].second);
1337 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001338 NewPreamble.first->getBufferStart(), Preamble.size());
1339 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001340 ' ', PreambleReservedSize - Preamble.size() - 1);
1341 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001342
1343 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001344 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001345 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1346
1347 // Tell the compiler invocation to generate a temporary precompiled header.
1348 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001349 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001350 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001351 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1352 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001353
1354 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001355 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1356
1357 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001358 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1359 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001360
Douglas Gregor3cc15812011-07-01 18:22:13 +00001361 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00001362 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001363
Douglas Gregor8e984da2010-08-04 16:47:14 +00001364 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001365 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001366
1367 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001368 Clang->getTargetOpts().Features = TargetFeatures;
1369 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1370 Clang->getTargetOpts()));
1371 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001372 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1373 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001374 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001375 PreprocessorOpts.eraseRemappedFile(
1376 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001377 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001378 }
1379
1380 // Inform the target of the language options.
1381 //
1382 // FIXME: We shouldn't need to do this, the target should be immutable once
1383 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001384 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001385
Ted Kremenek84de4a12011-03-21 18:40:07 +00001386 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001387 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001388 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001389 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001390 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001391 "IR inputs not support here!");
1392
1393 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001394 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001395 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001396 StoredDiagnostics.erase(
1397 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1398 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001399 TopLevelDecls.clear();
1400 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001401
1402 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001403 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001404
1405 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001406 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001407 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001408
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001409 llvm::OwningPtr<PrecompilePreambleAction> Act;
1410 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001411 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1412 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001413 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1414 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001415 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001416 PreprocessorOpts.eraseRemappedFile(
1417 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001418 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001419 }
1420
1421 Act->Execute();
1422 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001423
Douglas Gregore9db88f2010-08-03 19:06:41 +00001424 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001425 // There were errors parsing the preamble, so no precompiled header was
1426 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001427 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001428 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1429 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001430 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001431 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001432 PreprocessorOpts.eraseRemappedFile(
1433 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001434 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001435 }
1436
Douglas Gregor925296b2011-07-19 16:10:42 +00001437 // Transfer any diagnostics generated when parsing the preamble into the set
1438 // of preamble diagnostics.
1439 PreambleDiagnostics.clear();
1440 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1441 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1442 StoredDiagnostics.end());
1443 StoredDiagnostics.erase(
1444 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1445 StoredDiagnostics.end());
1446
Douglas Gregor4dde7492010-07-23 23:58:40 +00001447 // Keep track of the preamble we precompiled.
1448 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001449 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001450
1451 // Keep track of all of the files that the source manager knows about,
1452 // so we can verify whether they have changed or not.
1453 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001454 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001455 const llvm::MemoryBuffer *MainFileBuffer
1456 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1457 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1458 FEnd = SourceMgr.fileinfo_end();
1459 F != FEnd;
1460 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001461 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001462 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1463 continue;
1464
1465 FilesInPreamble[File->getName()]
1466 = std::make_pair(F->second->getSize(), File->getModificationTime());
1467 }
1468
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001469 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001470 PreprocessorOpts.eraseRemappedFile(
1471 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001472
1473 // If the hash of top-level entities differs from the hash of the top-level
1474 // entities the last time we rebuilt the preamble, clear out the completion
1475 // cache.
1476 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1477 CompletionCacheTopLevelHashValue = 0;
1478 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1479 }
1480
Douglas Gregor6481ef12010-07-24 00:38:13 +00001481 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001482 PreambleReservedSize,
1483 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001484}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001485
Douglas Gregore9db88f2010-08-03 19:06:41 +00001486void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1487 std::vector<Decl *> Resolved;
1488 Resolved.reserve(TopLevelDeclsInPreamble.size());
1489 ExternalASTSource &Source = *getASTContext().getExternalSource();
1490 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1491 // Resolve the declaration ID to an actual declaration, possibly
1492 // deserializing the declaration in the process.
1493 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1494 if (D)
1495 Resolved.push_back(D);
1496 }
1497 TopLevelDeclsInPreamble.clear();
1498 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1499}
1500
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001501StringRef ASTUnit::getMainFileName() const {
Douglas Gregor16896c42010-10-28 15:44:59 +00001502 return Invocation->getFrontendOpts().Inputs[0].second;
1503}
1504
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001505ASTUnit *ASTUnit::create(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001506 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001507 llvm::OwningPtr<ASTUnit> AST;
1508 AST.reset(new ASTUnit(false));
1509 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1510 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001511 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001512 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001513 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1514 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001515
1516 return AST.take();
1517}
1518
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001519ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001520 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001521 ASTFrontendAction *Action) {
1522 assert(CI && "A CompilerInvocation is required");
1523
1524 // Create the AST unit.
1525 llvm::OwningPtr<ASTUnit> AST;
1526 AST.reset(new ASTUnit(false));
1527 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1528 AST->Diagnostics = Diags;
1529 AST->OnlyLocalDecls = false;
1530 AST->CaptureDiagnostics = false;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001531 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001532 AST->ShouldCacheCodeCompletionResults = false;
1533 AST->Invocation = CI;
1534
1535 // Recover resources if we crash before exiting this method.
1536 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1537 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001538 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1539 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001540 DiagCleanup(Diags.getPtr());
1541
1542 // We'll manage file buffers ourselves.
1543 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1544 CI->getFrontendOpts().DisableFree = false;
1545 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1546
1547 // Save the target features.
1548 AST->TargetFeatures = CI->getTargetOpts().Features;
1549
1550 // Create the compiler instance to use for building the AST.
1551 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1552
1553 // Recover resources if we crash before exiting this method.
1554 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1555 CICleanup(Clang.get());
1556
1557 Clang->setInvocation(CI);
1558 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1559
1560 // Set up diagnostics, capturing any diagnostics that would
1561 // otherwise be dropped.
1562 Clang->setDiagnostics(&AST->getDiagnostics());
1563
1564 // Create the target instance.
1565 Clang->getTargetOpts().Features = AST->TargetFeatures;
1566 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1567 Clang->getTargetOpts()));
1568 if (!Clang->hasTarget())
1569 return 0;
1570
1571 // Inform the target of the language options.
1572 //
1573 // FIXME: We shouldn't need to do this, the target should be immutable once
1574 // created. This complexity should be lifted elsewhere.
1575 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1576
1577 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1578 "Invocation must have exactly one source file!");
1579 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1580 "FIXME: AST inputs not yet supported here!");
1581 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1582 "IR inputs not supported here!");
1583
1584 // Configure the various subsystems.
1585 AST->FileSystemOpts = Clang->getFileSystemOpts();
1586 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1587 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1588 AST->TheSema.reset();
1589 AST->Ctx = 0;
1590 AST->PP = 0;
1591
1592 // Create a file manager object to provide access to and cache the filesystem.
1593 Clang->setFileManager(&AST->getFileManager());
1594
1595 // Create the source manager.
1596 Clang->setSourceManager(&AST->getSourceManager());
1597
1598 ASTFrontendAction *Act = Action;
1599
1600 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1601 if (!Act) {
1602 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1603 Act = TrackerAct.get();
1604 }
1605
1606 // Recover resources if we crash before exiting this method.
1607 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1608 ActCleanup(TrackerAct.get());
1609
1610 if (!Act->BeginSourceFile(*Clang.get(),
1611 Clang->getFrontendOpts().Inputs[0].second,
1612 Clang->getFrontendOpts().Inputs[0].first))
1613 return 0;
1614
1615 Act->Execute();
1616
1617 // Steal the created target, context, and preprocessor.
1618 AST->TheSema.reset(Clang->takeSema());
1619 AST->Consumer.reset(Clang->takeASTConsumer());
1620 AST->Ctx = &Clang->getASTContext();
1621 AST->PP = &Clang->getPreprocessor();
1622 Clang->setSourceManager(0);
1623 Clang->setFileManager(0);
1624 AST->Target = &Clang->getTarget();
1625
1626 Act->EndSourceFile();
1627
1628 return AST.take();
1629}
1630
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001631bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1632 if (!Invocation)
1633 return true;
1634
1635 // We'll manage file buffers ourselves.
1636 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1637 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001638 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001639
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001640 // Save the target features.
1641 TargetFeatures = Invocation->getTargetOpts().Features;
1642
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001643 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001644 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001645 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001646 OverrideMainBuffer
1647 = getMainBufferWithPrecompiledPreamble(*Invocation);
1648 }
1649
Douglas Gregor16896c42010-10-28 15:44:59 +00001650 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001651 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001652
Ted Kremenek022a4902011-03-22 01:15:24 +00001653 // Recover resources if we crash before exiting this method.
1654 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1655 MemBufferCleanup(OverrideMainBuffer);
1656
Douglas Gregor16896c42010-10-28 15:44:59 +00001657 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001658}
1659
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001660ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001661 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001662 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001663 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001664 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001665 TranslationUnitKind TUKind,
Douglas Gregor998caea2011-05-06 16:33:08 +00001666 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001667 bool NestedMacroExpansions) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001668 // Create the AST unit.
1669 llvm::OwningPtr<ASTUnit> AST;
1670 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001671 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001672 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001673 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001674 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001675 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001676 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001677 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001678 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001679
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001680 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001681 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1682 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001683 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1684 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001685 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001686
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001687 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001688}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001689
1690ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1691 const char **ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00001692 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001693 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001694 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001695 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001696 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001697 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001698 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001699 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001700 TranslationUnitKind TUKind,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001701 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001702 bool NestedMacroExpansions) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001703 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001704 // No diagnostics engine was provided, so create our own diagnostics object
1705 // with the default options.
1706 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001707 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1708 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001709 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001710
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001711 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001712
Ted Kremenek5e14d392011-03-21 18:40:17 +00001713 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001714
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001715 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001716
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001717 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001718 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001719
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001720 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001721 llvm::makeArrayRef(ArgBegin, ArgEnd),
1722 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001723 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001724 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001725 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001726
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001727 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001728 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1729 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1730 if (const llvm::MemoryBuffer *
1731 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1732 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1733 } else {
1734 const char *fname = fileOrBuf.get<const char *>();
1735 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1736 }
1737 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001738 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1739 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001740
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001741 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001742 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001743
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001744 // Create the AST unit.
1745 llvm::OwningPtr<ASTUnit> AST;
1746 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001747 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001748 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001749
1750 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001751 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001752 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001753 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001754 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001755 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1756 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001757 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001758 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001759 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001760
1761 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001762 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1763 ASTUnitCleanup(AST.get());
1764 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1765 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1766 CICleanup(CI.getPtr());
David Blaikie9c902b52011-09-25 23:23:43 +00001767 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1768 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001769 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001770
Chris Lattner5159f612010-11-23 08:35:12 +00001771 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001772}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001773
1774bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001775 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001776 return true;
1777
Douglas Gregor16896c42010-10-28 15:44:59 +00001778 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001779 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001780
Douglas Gregor0e119552010-07-31 00:40:00 +00001781 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001782 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001783 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001784 for (PreprocessorOptions::remapped_file_buffer_iterator
1785 R = PPOpts.remapped_file_buffer_begin(),
1786 REnd = PPOpts.remapped_file_buffer_end();
1787 R != REnd;
1788 ++R) {
1789 delete R->second;
1790 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001791 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001792 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1793 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1794 if (const llvm::MemoryBuffer *
1795 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1796 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1797 memBuf);
1798 } else {
1799 const char *fname = fileOrBuf.get<const char *>();
1800 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1801 fname);
1802 }
1803 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001804
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001805 // If we have a preamble file lying around, or if we might try to
1806 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001807 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001808 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001809 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001810
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001811 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001812 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001813 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001814 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1815 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001816
Douglas Gregor4dde7492010-07-23 23:58:40 +00001817 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001818 bool Result = Parse(OverrideMainBuffer);
1819
1820 // If we're caching global code-completion results, and the top-level
1821 // declarations have changed, clear out the code-completion cache.
1822 if (!Result && ShouldCacheCodeCompletionResults &&
1823 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1824 CacheCodeCompletionResults();
1825
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001826 // We now need to clear out the completion allocator for
1827 // clang_getCursorCompletionString; it'll be recreated if necessary.
1828 CursorCompletionAllocator = 0;
1829
Douglas Gregor4dde7492010-07-23 23:58:40 +00001830 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001831}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001832
Douglas Gregorb14904c2010-08-13 22:48:40 +00001833//----------------------------------------------------------------------------//
1834// Code completion
1835//----------------------------------------------------------------------------//
1836
1837namespace {
1838 /// \brief Code completion consumer that combines the cached code-completion
1839 /// results from an ASTUnit with the code-completion results provided to it,
1840 /// then passes the result on to
1841 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00001842 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001843 ASTUnit &AST;
1844 CodeCompleteConsumer &Next;
1845
1846 public:
1847 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001848 bool IncludeMacros, bool IncludeCodePatterns,
1849 bool IncludeGlobals)
1850 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001851 Next.isOutputBinary()), AST(AST), Next(Next)
1852 {
1853 // Compute the set of contexts in which we will look when we don't have
1854 // any information about the specific context.
1855 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00001856 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1857 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1858 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1859 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1860 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1861 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1862 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1863 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1864 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1865 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1866 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1867 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1868 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001869
Douglas Gregorb14904c2010-08-13 22:48:40 +00001870 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00001871 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1872 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1873 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00001874 }
1875
1876 virtual void ProcessCodeCompleteResults(Sema &S,
1877 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001878 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001879 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001880
1881 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1882 OverloadCandidate *Candidates,
1883 unsigned NumCandidates) {
1884 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1885 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001886
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001887 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001888 return Next.getAllocator();
1889 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001890 };
1891}
Douglas Gregord46cf182010-08-16 20:01:48 +00001892
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001893/// \brief Helper function that computes which global names are hidden by the
1894/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001895static void CalculateHiddenNames(const CodeCompletionContext &Context,
1896 CodeCompletionResult *Results,
1897 unsigned NumResults,
1898 ASTContext &Ctx,
1899 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001900 bool OnlyTagNames = false;
1901 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001902 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001903 case CodeCompletionContext::CCC_TopLevel:
1904 case CodeCompletionContext::CCC_ObjCInterface:
1905 case CodeCompletionContext::CCC_ObjCImplementation:
1906 case CodeCompletionContext::CCC_ObjCIvarList:
1907 case CodeCompletionContext::CCC_ClassStructUnion:
1908 case CodeCompletionContext::CCC_Statement:
1909 case CodeCompletionContext::CCC_Expression:
1910 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001911 case CodeCompletionContext::CCC_DotMemberAccess:
1912 case CodeCompletionContext::CCC_ArrowMemberAccess:
1913 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001914 case CodeCompletionContext::CCC_Namespace:
1915 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001916 case CodeCompletionContext::CCC_Name:
1917 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001918 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001919 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001920 break;
1921
1922 case CodeCompletionContext::CCC_EnumTag:
1923 case CodeCompletionContext::CCC_UnionTag:
1924 case CodeCompletionContext::CCC_ClassOrStructTag:
1925 OnlyTagNames = true;
1926 break;
1927
1928 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001929 case CodeCompletionContext::CCC_MacroName:
1930 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001931 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001932 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001933 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001934 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001935 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001936 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001937 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00001938 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1939 case CodeCompletionContext::CCC_ObjCClassMessage:
1940 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001941 // We're looking for nothing, or we're looking for names that cannot
1942 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001943 return;
1944 }
1945
John McCall276321a2010-08-25 06:19:51 +00001946 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001947 for (unsigned I = 0; I != NumResults; ++I) {
1948 if (Results[I].Kind != Result::RK_Declaration)
1949 continue;
1950
1951 unsigned IDNS
1952 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1953
1954 bool Hiding = false;
1955 if (OnlyTagNames)
1956 Hiding = (IDNS & Decl::IDNS_Tag);
1957 else {
1958 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001959 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1960 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001961 if (Ctx.getLangOptions().CPlusPlus)
1962 HiddenIDNS |= Decl::IDNS_Tag;
1963 Hiding = (IDNS & HiddenIDNS);
1964 }
1965
1966 if (!Hiding)
1967 continue;
1968
1969 DeclarationName Name = Results[I].Declaration->getDeclName();
1970 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1971 HiddenNames.insert(Identifier->getName());
1972 else
1973 HiddenNames.insert(Name.getAsString());
1974 }
1975}
1976
1977
Douglas Gregord46cf182010-08-16 20:01:48 +00001978void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1979 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001980 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001981 unsigned NumResults) {
1982 // Merge the results we were given with the results we cached.
1983 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001984 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001985 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi203f87c2011-08-17 01:46:16 +00001986 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001987 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001988 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001989 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001990 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00001991 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001992 C = AST.cached_completion_begin(),
1993 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001994 C != CEnd; ++C) {
1995 // If the context we are in matches any of the contexts we are
1996 // interested in, we'll add this result.
1997 if ((C->ShowInContexts & InContexts) == 0)
1998 continue;
1999
2000 // If we haven't added any results previously, do so now.
2001 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002002 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2003 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002004 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2005 AddedResult = true;
2006 }
2007
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002008 // Determine whether this global completion result is hidden by a local
2009 // completion result. If so, skip it.
2010 if (C->Kind != CXCursor_MacroDefinition &&
2011 HiddenNames.count(C->Completion->getTypedText()))
2012 continue;
2013
Douglas Gregord46cf182010-08-16 20:01:48 +00002014 // Adjust priority based on similar type classes.
2015 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002016 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002017 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002018 if (!Context.getPreferredType().isNull()) {
2019 if (C->Kind == CXCursor_MacroDefinition) {
2020 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002021 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00002022 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002023 } else if (C->Type) {
2024 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002025 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002026 Context.getPreferredType().getUnqualifiedType());
2027 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2028 if (ExpectedSTC == C->TypeClass) {
2029 // We know this type is similar; check for an exact match.
2030 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002031 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002032 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002033 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002034 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2035 Priority /= CCF_ExactTypeMatch;
2036 else
2037 Priority /= CCF_SimilarTypeMatch;
2038 }
2039 }
2040 }
2041
Douglas Gregor12785102010-08-24 20:21:13 +00002042 // Adjust the completion string, if required.
2043 if (C->Kind == CXCursor_MacroDefinition &&
2044 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2045 // Create a new code-completion string that just contains the
2046 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002047 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2048 C->Availability);
2049 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002050 CursorKind = CXCursor_NotImplemented;
2051 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002052 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002053 }
2054
Douglas Gregor8850aa32010-08-25 18:03:13 +00002055 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002056 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002057 }
2058
2059 // If we did not add any cached completion results, just forward the
2060 // results we were given to the next consumer.
2061 if (!AddedResult) {
2062 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2063 return;
2064 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002065
Douglas Gregord46cf182010-08-16 20:01:48 +00002066 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2067 AllResults.size());
2068}
2069
2070
2071
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002072void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002073 RemappedFile *RemappedFiles,
2074 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002075 bool IncludeMacros,
2076 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002077 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002078 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002079 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002080 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2081 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002082 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002083 return;
2084
Douglas Gregor16896c42010-10-28 15:44:59 +00002085 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002086 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002087 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002088
Ted Kremenek5e14d392011-03-21 18:40:17 +00002089 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2090 CCInvocation(new CompilerInvocation(*Invocation));
2091
2092 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2093 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002094
Douglas Gregorb14904c2010-08-13 22:48:40 +00002095 FrontendOpts.ShowMacrosInCodeCompletion
2096 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002097 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002098 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2099 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002100 FrontendOpts.CodeCompletionAt.FileName = File;
2101 FrontendOpts.CodeCompletionAt.Line = Line;
2102 FrontendOpts.CodeCompletionAt.Column = Column;
2103
2104 // Set the language options appropriately.
Ted Kremenek5e14d392011-03-21 18:40:17 +00002105 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002106
Ted Kremenek84de4a12011-03-21 18:40:07 +00002107 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2108
2109 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002110 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2111 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002112
Ted Kremenek5e14d392011-03-21 18:40:17 +00002113 Clang->setInvocation(&*CCInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002114 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002115
2116 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002117 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002118 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002119 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002120 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002121 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002122
2123 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002124 Clang->getTargetOpts().Features = TargetFeatures;
2125 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2126 Clang->getTargetOpts()));
2127 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002128 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002129 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002130 }
2131
2132 // Inform the target of the language options.
2133 //
2134 // FIXME: We shouldn't need to do this, the target should be immutable once
2135 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002136 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002137
Ted Kremenek84de4a12011-03-21 18:40:07 +00002138 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002139 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002140 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002141 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002142 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002143 "IR inputs not support here!");
2144
2145
2146 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002147 Clang->setFileManager(&FileMgr);
2148 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002149
2150 // Remap files.
2151 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002152 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002153 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002154 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2155 if (const llvm::MemoryBuffer *
2156 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2157 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2158 OwnedBuffers.push_back(memBuf);
2159 } else {
2160 const char *fname = fileOrBuf.get<const char *>();
2161 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2162 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002163 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002164
Douglas Gregorb14904c2010-08-13 22:48:40 +00002165 // Use the code completion consumer we were given, but adding any cached
2166 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002167 AugmentedCodeCompleteConsumer *AugmentedConsumer
2168 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2169 FrontendOpts.ShowMacrosInCodeCompletion,
2170 FrontendOpts.ShowCodePatternsInCodeCompletion,
2171 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002172 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002173
Douglas Gregor028d3e42010-08-09 20:45:32 +00002174 // If we have a precompiled preamble, try to use it. We only allow
2175 // the use of the precompiled preamble if we're if the completion
2176 // point is within the main file, after the end of the precompiled
2177 // preamble.
2178 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2179 if (!PreambleFile.empty()) {
2180 using llvm::sys::FileStatus;
2181 llvm::sys::PathWithStatus CompleteFilePath(File);
2182 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2183 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2184 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +00002185 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2186 Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002187 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002188 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002189 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002190 }
2191
2192 // If the main file has been overridden due to the use of a preamble,
2193 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002194 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002195 StoredDiagnostics.insert(StoredDiagnostics.end(),
2196 this->StoredDiagnostics.begin(),
2197 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002198 if (OverrideMainBuffer) {
2199 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2200 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2201 PreprocessorOpts.PrecompiledPreambleBytes.second
2202 = PreambleEndsAtStartOfLine;
2203 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2204 PreprocessorOpts.DisablePCHValidation = true;
2205
Douglas Gregorb97b6662010-08-20 00:59:43 +00002206 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002207 } else {
2208 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2209 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002210 }
2211
Douglas Gregor998caea2011-05-06 16:33:08 +00002212 // Disable the preprocessing record
2213 PreprocessorOpts.DetailedRecord = false;
2214
Douglas Gregor8e984da2010-08-04 16:47:14 +00002215 llvm::OwningPtr<SyntaxOnlyAction> Act;
2216 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002217 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2218 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002219 if (OverrideMainBuffer) {
Jonathan D. Turner2214acd2011-07-22 17:25:03 +00002220 std::string ModName = PreambleFile;
Douglas Gregor925296b2011-07-19 16:10:42 +00002221 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2222 getSourceManager(), PreambleDiagnostics,
2223 StoredDiagnostics);
2224 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002225 Act->Execute();
2226 Act->EndSourceFile();
2227 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002228}
Douglas Gregore9386682010-08-13 05:36:37 +00002229
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002230CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor8a60bbe2011-07-06 17:40:26 +00002231 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor30c80fa2011-07-06 16:43:36 +00002232 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002233
2234 // Write to a temporary file and later rename it to the actual file, to avoid
2235 // possible race conditions.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002236 llvm::SmallString<128> TempPath;
2237 TempPath = File;
2238 TempPath += "-%%%%%%%%";
2239 int fd;
2240 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2241 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002242 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002243
Douglas Gregore9386682010-08-13 05:36:37 +00002244 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2245 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002246 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002247
2248 serialize(Out);
2249 Out.close();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002250 if (Out.has_error())
2251 return CXSaveError_Unknown;
2252
2253 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2254 bool exists;
2255 llvm::sys::fs::remove(TempPath.str(), exists);
2256 return CXSaveError_Unknown;
2257 }
2258
2259 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002260}
2261
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002262bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002263 if (getDiagnostics().hasErrorOccurred())
2264 return true;
2265
Douglas Gregore9386682010-08-13 05:36:37 +00002266 std::vector<unsigned char> Buffer;
2267 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002268 ASTWriter Writer(Stream);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002269 // FIXME: Handle modules
2270 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregore9386682010-08-13 05:36:37 +00002271
2272 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002273 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002274 OS.write((char *)&Buffer.front(), Buffer.size());
2275
2276 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002277}
Douglas Gregor925296b2011-07-19 16:10:42 +00002278
2279typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2280
2281static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2282 unsigned Raw = L.getRawEncoding();
2283 const unsigned MacroBit = 1U << 31;
2284 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2285 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2286}
2287
2288void ASTUnit::TranslateStoredDiagnostics(
2289 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002290 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002291 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002292 const SmallVectorImpl<StoredDiagnostic> &Diags,
2293 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002294 // The stored diagnostic has the old source manager in it; update
2295 // the locations to refer into the new source manager. We also need to remap
2296 // all the locations to the new view. This includes the diag location, any
2297 // associated source ranges, and the source ranges of associated fix-its.
2298 // FIXME: There should be a cleaner way to do this.
2299
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002300 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002301 Result.reserve(Diags.size());
2302 assert(MMan && "Don't have a module manager");
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00002303 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002304 assert(Mod && "Don't have preamble module");
2305 SLocRemap &Remap = Mod->SLocRemap;
2306 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2307 // Rebuild the StoredDiagnostic.
2308 const StoredDiagnostic &SD = Diags[I];
2309 SourceLocation L = SD.getLocation();
2310 TranslateSLoc(L, Remap);
2311 FullSourceLoc Loc(L, SrcMgr);
2312
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002313 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002314 Ranges.reserve(SD.range_size());
2315 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2316 E = SD.range_end();
2317 I != E; ++I) {
2318 SourceLocation BL = I->getBegin();
2319 TranslateSLoc(BL, Remap);
2320 SourceLocation EL = I->getEnd();
2321 TranslateSLoc(EL, Remap);
2322 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2323 }
2324
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002325 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002326 FixIts.reserve(SD.fixit_size());
2327 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2328 E = SD.fixit_end();
2329 I != E; ++I) {
2330 FixIts.push_back(FixItHint());
2331 FixItHint &FH = FixIts.back();
2332 FH.CodeToInsert = I->CodeToInsert;
2333 SourceLocation BL = I->RemoveRange.getBegin();
2334 TranslateSLoc(BL, Remap);
2335 SourceLocation EL = I->RemoveRange.getEnd();
2336 TranslateSLoc(EL, Remap);
2337 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2338 I->RemoveRange.isTokenRange());
2339 }
2340
2341 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2342 SD.getMessage(), Loc, Ranges, FixIts));
2343 }
2344 Result.swap(Out);
2345}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002346
2347SourceLocation ASTUnit::getLocation(const FileEntry *File,
2348 unsigned Line, unsigned Col) const {
2349 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002350 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002351 return SM.getMacroArgExpandedLocation(Loc);
2352}
2353
2354SourceLocation ASTUnit::getLocation(const FileEntry *File,
2355 unsigned Offset) const {
2356 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002357 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002358 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2359}
2360
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002361/// \brief If \arg Loc is a loaded location from the preamble, returns
2362/// the corresponding local location of the main file, otherwise it returns
2363/// \arg Loc.
2364SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2365 FileID PreambleID;
2366 if (SourceMgr)
2367 PreambleID = SourceMgr->getPreambleFileID();
2368
2369 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2370 return Loc;
2371
2372 unsigned Offs;
2373 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2374 SourceLocation FileLoc
2375 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2376 return FileLoc.getLocWithOffset(Offs);
2377 }
2378
2379 return Loc;
2380}
2381
2382/// \brief If \arg Loc is a local location of the main file but inside the
2383/// preamble chunk, returns the corresponding loaded location from the
2384/// preamble, otherwise it returns \arg Loc.
2385SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2386 FileID PreambleID;
2387 if (SourceMgr)
2388 PreambleID = SourceMgr->getPreambleFileID();
2389
2390 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2391 return Loc;
2392
2393 unsigned Offs;
2394 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2395 Offs < Preamble.size()) {
2396 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2397 return FileLoc.getLocWithOffset(Offs);
2398 }
2399
2400 return Loc;
2401}
2402
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002403void ASTUnit::PreambleData::countLines() const {
2404 NumLines = 0;
2405 if (empty())
2406 return;
2407
2408 for (std::vector<char>::const_iterator
2409 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2410 if (*I == '\n')
2411 ++NumLines;
2412 }
2413 if (Buffer.back() != '\n')
2414 ++NumLines;
2415}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002416
2417#ifndef NDEBUG
2418ASTUnit::ConcurrencyState::ConcurrencyState() {
2419 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2420}
2421
2422ASTUnit::ConcurrencyState::~ConcurrencyState() {
2423 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2424}
2425
2426void ASTUnit::ConcurrencyState::start() {
2427 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2428 assert(acquired && "Concurrent access to ASTUnit!");
2429}
2430
2431void ASTUnit::ConcurrencyState::finish() {
2432 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2433}
2434
2435#else // NDEBUG
2436
2437ASTUnit::ConcurrencyState::ConcurrencyState() {}
2438ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2439void ASTUnit::ConcurrencyState::start() {}
2440void ASTUnit::ConcurrencyState::finish() {}
2441
2442#endif