blob: 6ea48d878729f3478d241bbba1fd1f27721e4253 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregoreababfb2010-08-04 05:53:38 +000046/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
Douglas Gregor3687e9d2010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor87c08a52010-08-13 22:48:40 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000060}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000061
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000067
68 // Free the buffers associated with remapped files. We are required to
69 // perform this operation here because we explicitly request that the
70 // compiler instance *not* free these buffers for each invocation of the
71 // parser.
72 if (Invocation.get()) {
73 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
74 for (PreprocessorOptions::remapped_file_buffer_iterator
75 FB = PPOpts.remapped_file_buffer_begin(),
76 FBEnd = PPOpts.remapped_file_buffer_end();
77 FB != FBEnd;
78 ++FB)
79 delete FB->second;
80 }
Douglas Gregor28233422010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000083
Douglas Gregor87c08a52010-08-13 22:48:40 +000084 ClearCachedCompletionResults();
85
Douglas Gregor385103b2010-07-30 20:58:08 +000086 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
87 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000088}
89
90void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000091 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
92 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000093 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000094}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000095
Douglas Gregor8071e422010-08-15 06:18:01 +000096/// \brief Determine the set of code-completion contexts in which this
97/// declaration should be shown.
98static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +000099 const LangOptions &LangOpts,
100 bool &IsNestedNameSpecifier) {
101 IsNestedNameSpecifier = false;
102
Douglas Gregor8071e422010-08-15 06:18:01 +0000103 if (isa<UsingShadowDecl>(ND))
104 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
105 if (!ND)
106 return 0;
107
108 unsigned Contexts = 0;
109 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
110 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
111 // Types can appear in these contexts.
112 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
113 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
114 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
115 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
116 | (1 << (CodeCompletionContext::CCC_Statement - 1))
117 | (1 << (CodeCompletionContext::CCC_Type - 1));
118
119 // In C++, types can appear in expressions contexts (for functional casts).
120 if (LangOpts.CPlusPlus)
121 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
122
123 // In Objective-C, message sends can send interfaces. In Objective-C++,
124 // all types are available due to functional casts.
125 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
126 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
127
128 // Deal with tag names.
129 if (isa<EnumDecl>(ND)) {
130 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
131
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000132 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000133 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000134 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000135 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
136 if (Record->isUnion())
137 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
138 else
139 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
140
Douglas Gregor8071e422010-08-15 06:18:01 +0000141 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000142 IsNestedNameSpecifier = true;
143 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
144 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000145 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
146 // Values can appear in these contexts.
147 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
148 | (1 << (CodeCompletionContext::CCC_Expression - 1))
149 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
150 } else if (isa<ObjCProtocolDecl>(ND)) {
151 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
152 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000153 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000154
155 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000156 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000157 }
158
159 return Contexts;
160}
161
Douglas Gregor87c08a52010-08-13 22:48:40 +0000162void ASTUnit::CacheCodeCompletionResults() {
163 if (!TheSema)
164 return;
165
166 llvm::Timer *CachingTimer = 0;
167 if (TimerGroup.get()) {
168 CachingTimer = new llvm::Timer("Cache global code completions",
169 *TimerGroup);
170 CachingTimer->startTimer();
171 Timers.push_back(CachingTimer);
172 }
173
174 // Clear out the previous results.
175 ClearCachedCompletionResults();
176
177 // Gather the set of global code completions.
178 typedef CodeCompleteConsumer::Result Result;
179 llvm::SmallVector<Result, 8> Results;
180 TheSema->GatherGlobalCodeCompletions(Results);
181
182 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000183 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
184
Douglas Gregor87c08a52010-08-13 22:48:40 +0000185 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
186 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000187 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000188 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000189 CachedCodeCompletionResult CachedResult;
190 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
191 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000192 Ctx->getLangOptions(),
193 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000194 CachedResult.Priority = Results[I].Priority;
195 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000196
Douglas Gregorf5586f62010-08-16 18:08:11 +0000197 // Keep track of the type of this completion in an ASTContext-agnostic
198 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000199 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000200 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000201 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000202 CachedResult.Type = 0;
203 } else {
204 CanQualType CanUsageType
205 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
206 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
207
208 // Determine whether we have already seen this type. If so, we save
209 // ourselves the work of formatting the type string by using the
210 // temporary, CanQualType-based hash table to find the associated value.
211 unsigned &TypeValue = CompletionTypes[CanUsageType];
212 if (TypeValue == 0) {
213 TypeValue = CompletionTypes.size();
214 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
215 = TypeValue;
216 }
217
218 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000219 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000220
Douglas Gregor8071e422010-08-15 06:18:01 +0000221 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000222
223 /// Handle nested-name-specifiers in C++.
224 if (TheSema->Context.getLangOptions().CPlusPlus &&
225 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
226 // The contexts in which a nested-name-specifier can appear in C++.
227 unsigned NNSContexts
228 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
229 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
230 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
231 | (1 << (CodeCompletionContext::CCC_Statement - 1))
232 | (1 << (CodeCompletionContext::CCC_Expression - 1))
233 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
234 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
235 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
236 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
237 | (1 << (CodeCompletionContext::CCC_Type - 1));
238
239 if (isa<NamespaceDecl>(Results[I].Declaration) ||
240 isa<NamespaceAliasDecl>(Results[I].Declaration))
241 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
242
243 if (unsigned RemainingContexts
244 = NNSContexts & ~CachedResult.ShowInContexts) {
245 // If there any contexts where this completion can be a
246 // nested-name-specifier but isn't already an option, create a
247 // nested-name-specifier completion.
248 Results[I].StartsNestedNameSpecifier = true;
249 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
250 CachedResult.ShowInContexts = RemainingContexts;
251 CachedResult.Priority = CCP_NestedNameSpecifier;
252 CachedResult.TypeClass = STC_Void;
253 CachedResult.Type = 0;
254 CachedCompletionResults.push_back(CachedResult);
255 }
256 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000257 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000258 }
259
Douglas Gregor87c08a52010-08-13 22:48:40 +0000260 case Result::RK_Keyword:
261 case Result::RK_Pattern:
262 // Ignore keywords and patterns; we don't care, since they are so
263 // easily regenerated.
264 break;
265
266 case Result::RK_Macro: {
267 CachedCodeCompletionResult CachedResult;
268 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
269 CachedResult.ShowInContexts
270 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
271 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
272 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
274 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
275 | (1 << (CodeCompletionContext::CCC_Statement - 1))
276 | (1 << (CodeCompletionContext::CCC_Expression - 1))
277 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
278 CachedResult.Priority = Results[I].Priority;
279 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor1827e102010-08-16 16:18:59 +0000280 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000281 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000282 CachedCompletionResults.push_back(CachedResult);
283 break;
284 }
285 }
286 Results[I].Destroy();
287 }
288
289 if (CachingTimer)
290 CachingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +0000291
292 // Make a note of the state when we performed this caching.
293 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
294 CacheCodeCompletionCoolDown = 15;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000295}
296
297void ASTUnit::ClearCachedCompletionResults() {
298 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
299 delete CachedCompletionResults[I].Completion;
300 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000301 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000302}
303
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000304namespace {
305
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000306/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000307/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000308class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000309 LangOptions &LangOpt;
310 HeaderSearch &HSI;
311 std::string &TargetTriple;
312 std::string &Predefines;
313 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000315 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000317public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000318 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000319 std::string &TargetTriple, std::string &Predefines,
320 unsigned &Counter)
321 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
322 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000324 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
325 LangOpt = LangOpts;
326 return false;
327 }
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000329 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000330 TargetTriple = Triple;
331 return false;
332 }
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000334 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000335 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000336 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000337 Predefines = Buffers[0].Data;
338 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
339 Predefines += Buffers[I].Data;
340 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000341 return false;
342 }
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000344 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000345 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
346 }
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000348 virtual void ReadCounter(unsigned Value) {
349 Counter = Value;
350 }
351};
352
Douglas Gregora88084b2010-02-18 18:08:43 +0000353class StoredDiagnosticClient : public DiagnosticClient {
354 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
355
356public:
357 explicit StoredDiagnosticClient(
358 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
359 : StoredDiags(StoredDiags) { }
360
361 virtual void HandleDiagnostic(Diagnostic::Level Level,
362 const DiagnosticInfo &Info);
363};
364
365/// \brief RAII object that optionally captures diagnostics, if
366/// there is no diagnostic client to capture them already.
367class CaptureDroppedDiagnostics {
368 Diagnostic &Diags;
369 StoredDiagnosticClient Client;
370 DiagnosticClient *PreviousClient;
371
372public:
373 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
374 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000375 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000376 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000377 if (RequestCapture || Diags.getClient() == 0) {
378 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000379 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000380 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000381 }
382
383 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000384 if (Diags.getClient() == &Client) {
385 Diags.takeClient();
386 Diags.setClient(PreviousClient);
387 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000388 }
389};
390
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000391} // anonymous namespace
392
Douglas Gregora88084b2010-02-18 18:08:43 +0000393void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
394 const DiagnosticInfo &Info) {
395 StoredDiags.push_back(StoredDiagnostic(Level, Info));
396}
397
Steve Naroff77accc12009-09-03 18:19:54 +0000398const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000399 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000400}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000401
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000402const std::string &ASTUnit::getASTFileName() {
403 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000404 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000405}
406
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000407ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000408 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000409 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000410 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000411 unsigned NumRemappedFiles,
412 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000413 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
414
Douglas Gregor28019772010-04-05 23:52:57 +0000415 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000416 // No diagnostics engine was provided, so create our own diagnostics object
417 // with the default options.
418 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000419 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000420 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000421
422 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000423 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000424 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000425 AST->FileMgr.reset(new FileManager);
426 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000427 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000428
Douglas Gregora88084b2010-02-18 18:08:43 +0000429 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000430 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000431 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000432
Douglas Gregor4db64a42010-01-23 00:14:00 +0000433 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
434 // Create the file entry for the file that we're mapping from.
435 const FileEntry *FromFile
436 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
437 RemappedFiles[I].second->getBufferSize(),
438 0);
439 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000440 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000441 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000442 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000443 continue;
444 }
445
446 // Override the contents of the "from" file with the contents of
447 // the "to" file.
448 AST->getSourceManager().overrideFileContents(FromFile,
449 RemappedFiles[I].second);
450 }
451
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000452 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000454 LangOptions LangInfo;
455 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
456 std::string TargetTriple;
457 std::string Predefines;
458 unsigned Counter;
459
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000460 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000461
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000462 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000463 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000464 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000465 Predefines, Counter));
466
Sebastian Redl571db7f2010-08-18 23:56:56 +0000467 switch (Reader->ReadAST(Filename)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000468 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000469 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000471 case ASTReader::Failure:
472 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000473 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000474 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000475 }
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000477 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
478
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000479 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000481 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000482 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000483 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000484 TargetOptions TargetOpts;
485 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000486 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000487 TargetOpts.CPU = "";
488 TargetOpts.Features.clear();
489 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000490 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
491 TargetOpts));
492 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
493 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000494 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000495 Preprocessor &PP = *AST->PP.get();
496
Daniel Dunbard5b61262009-09-21 03:03:47 +0000497 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000499 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501 // Create and initialize the ASTContext.
502
503 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000504 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505 *AST->Target.get(),
506 PP.getIdentifierTable(),
507 PP.getSelectorTable(),
508 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509 /* size_reserve = */0));
510 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Daniel Dunbarcc318932009-09-03 05:59:35 +0000512 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000514 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000516 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000517 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000518 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519 Context.setExternalSource(Source);
520
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000521 // Create an AST consumer, even though it isn't used.
522 AST->Consumer.reset(new ASTConsumer);
523
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000524 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000525 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
526 AST->TheSema->Initialize();
527 ReaderPtr->InitializeSema(*AST->TheSema);
528
Mike Stump1eb44332009-09-09 15:08:12 +0000529 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000530}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000531
532namespace {
533
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000534class TopLevelDeclTrackerConsumer : public ASTConsumer {
535 ASTUnit &Unit;
536
537public:
538 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
539
540 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000541 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
542 Decl *D = *it;
543 // FIXME: Currently ObjC method declarations are incorrectly being
544 // reported as top-level declarations, even though their DeclContext
545 // is the containing ObjC @interface/@implementation. This is a
546 // fundamental problem in the parser right now.
547 if (isa<ObjCMethodDecl>(D))
548 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000549 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000550 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000551 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000552
553 // We're not interested in "interesting" decls.
554 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000555};
556
557class TopLevelDeclTrackerAction : public ASTFrontendAction {
558public:
559 ASTUnit &Unit;
560
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000561 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
562 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000563 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000564 }
565
566public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000567 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
568
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000569 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000570 virtual bool usesCompleteTranslationUnit() {
571 return Unit.isCompleteTranslationUnit();
572 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000573};
574
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000575class PrecompilePreambleConsumer : public PCHGenerator {
576 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000577 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000578
579public:
580 PrecompilePreambleConsumer(ASTUnit &Unit,
581 const Preprocessor &PP, bool Chaining,
582 const char *isysroot, llvm::raw_ostream *Out)
583 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
584
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000585 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000586 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
587 Decl *D = *it;
588 // FIXME: Currently ObjC method declarations are incorrectly being
589 // reported as top-level declarations, even though their DeclContext
590 // is the containing ObjC @interface/@implementation. This is a
591 // fundamental problem in the parser right now.
592 if (isa<ObjCMethodDecl>(D))
593 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000594 TopLevelDecls.push_back(D);
595 }
596 }
597
598 virtual void HandleTranslationUnit(ASTContext &Ctx) {
599 PCHGenerator::HandleTranslationUnit(Ctx);
600 if (!Unit.getDiagnostics().hasErrorOccurred()) {
601 // Translate the top-level declarations we captured during
602 // parsing into declaration IDs in the precompiled
603 // preamble. This will allow us to deserialize those top-level
604 // declarations when requested.
605 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
606 Unit.addTopLevelDeclFromPreamble(
607 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000608 }
609 }
610};
611
612class PrecompilePreambleAction : public ASTFrontendAction {
613 ASTUnit &Unit;
614
615public:
616 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
617
618 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
619 llvm::StringRef InFile) {
620 std::string Sysroot;
621 llvm::raw_ostream *OS = 0;
622 bool Chaining;
623 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
624 OS, Chaining))
625 return 0;
626
627 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
628 Sysroot.c_str() : 0;
629 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
630 isysroot, OS);
631 }
632
633 virtual bool hasCodeCompletionSupport() const { return false; }
634 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000635 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000636};
637
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000638}
639
Douglas Gregorabc563f2010-07-19 21:46:24 +0000640/// Parse the source file into a translation unit using the given compiler
641/// invocation, replacing the current translation unit.
642///
643/// \returns True if a failure occurred that causes the ASTUnit not to
644/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000645bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000646 delete SavedMainFileBuffer;
647 SavedMainFileBuffer = 0;
648
Douglas Gregorabc563f2010-07-19 21:46:24 +0000649 if (!Invocation.get())
650 return true;
651
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000652 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000653 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000654 Clang.setInvocation(Invocation.take());
655 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
656
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000657 // Set up diagnostics, capturing any diagnostics that would
658 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000659 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000660 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
661 getDiagnostics(),
662 StoredDiagnostics);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000663
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000664 // Create the target instance.
665 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
666 Clang.getTargetOpts()));
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000667 if (!Clang.hasTarget())
Douglas Gregorabc563f2010-07-19 21:46:24 +0000668 return true;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000669
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000670 // Inform the target of the language options.
671 //
672 // FIXME: We shouldn't need to do this, the target should be immutable once
673 // created. This complexity should be lifted elsewhere.
674 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000675
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000676 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
677 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000678 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000679 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000680 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
681 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000682
Douglas Gregorabc563f2010-07-19 21:46:24 +0000683 // Configure the various subsystems.
684 // FIXME: Should we retain the previous file manager?
685 FileMgr.reset(new FileManager);
686 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000687 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000688 Ctx.reset();
689 PP.reset();
690
691 // Clear out old caches and data.
692 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000693 CleanTemporaryFiles();
694 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000695
696 if (!OverrideMainBuffer)
697 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000698
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000699 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000700 Clang.setFileManager(&getFileManager());
701
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000702 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000703 Clang.setSourceManager(&getSourceManager());
704
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000705 // If the main file has been overridden due to the use of a preamble,
706 // make that override happen and introduce the preamble.
707 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000708 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000709 if (OverrideMainBuffer) {
710 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
711 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
712 PreprocessorOpts.PrecompiledPreambleBytes.second
713 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000714 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000715 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000716 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000717
718 // Keep track of the override buffer;
719 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000720
721 // The stored diagnostic has the old source manager in it; update
722 // the locations to refer into the new source manager. Since we've
723 // been careful to make sure that the source manager's state
724 // before and after are identical, so that we can reuse the source
725 // location itself.
726 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
727 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
728 getSourceManager());
729 StoredDiagnostics[I].setLocation(Loc);
730 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000731 }
732
Douglas Gregorabc563f2010-07-19 21:46:24 +0000733 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
734 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000735 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000736 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000737 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000738
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000739 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000740
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000741 // Steal the created target, context, and preprocessor, and take back the
742 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000743 TheSema.reset(Clang.takeSema());
744 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000745 Ctx.reset(Clang.takeASTContext());
746 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000747 Clang.takeSourceManager();
748 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000749 Target.reset(Clang.takeTarget());
750
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000751 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000752
753 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000754 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000755 PreprocessorOpts.eraseRemappedFile(
756 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000757 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
758 }
759
Douglas Gregorabc563f2010-07-19 21:46:24 +0000760 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000761
762 // If we were asked to cache code-completion results and don't have any
763 // results yet, do so now.
764 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
765 CacheCodeCompletionResults();
766
Douglas Gregorabc563f2010-07-19 21:46:24 +0000767 return false;
768
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000769error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000770 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000771 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000772 PreprocessorOpts.eraseRemappedFile(
773 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000774 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000775 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000776 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000777
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000778 Clang.takeSourceManager();
779 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000780 Invocation.reset(Clang.takeInvocation());
781 return true;
782}
783
Douglas Gregor44c181a2010-07-23 00:33:23 +0000784/// \brief Simple function to retrieve a path for a preamble precompiled header.
785static std::string GetPreamblePCHPath() {
786 // FIXME: This is lame; sys::Path should provide this function (in particular,
787 // it should know how to find the temporary files dir).
788 // FIXME: This is really lame. I copied this code from the Driver!
789 std::string Error;
790 const char *TmpDir = ::getenv("TMPDIR");
791 if (!TmpDir)
792 TmpDir = ::getenv("TEMP");
793 if (!TmpDir)
794 TmpDir = ::getenv("TMP");
795 if (!TmpDir)
796 TmpDir = "/tmp";
797 llvm::sys::Path P(TmpDir);
798 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000799 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000800 if (P.createTemporaryFileOnDisk())
801 return std::string();
802
Douglas Gregor44c181a2010-07-23 00:33:23 +0000803 return P.str();
804}
805
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000806/// \brief Compute the preamble for the main file, providing the source buffer
807/// that corresponds to the main file along with a pair (bytes, start-of-line)
808/// that describes the preamble.
809std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000810ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
811 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000812 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000813 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000814 = Invocation.getPreprocessorOpts();
815 CreatedBuffer = false;
816
Douglas Gregor44c181a2010-07-23 00:33:23 +0000817 // Try to determine if the main file has been remapped, either from the
818 // command line (to another file) or directly through the compiler invocation
819 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000820 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000821 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
822 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
823 // Check whether there is a file-file remapping of the main file
824 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000825 M = PreprocessorOpts.remapped_file_begin(),
826 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000827 M != E;
828 ++M) {
829 llvm::sys::PathWithStatus MPath(M->first);
830 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
831 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
832 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000833 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000834 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000835 CreatedBuffer = false;
836 }
837
Douglas Gregor44c181a2010-07-23 00:33:23 +0000838 Buffer = llvm::MemoryBuffer::getFile(M->second);
839 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000840 return std::make_pair((llvm::MemoryBuffer*)0,
841 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000842 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000843
Douglas Gregor175c4a92010-07-23 23:58:40 +0000844 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000845 M = PreprocessorOpts.eraseRemappedFile(M);
846 E = PreprocessorOpts.remapped_file_end();
847 }
848 }
849 }
850
851 // Check whether there is a file-buffer remapping. It supercedes the
852 // file-file remapping.
853 for (PreprocessorOptions::remapped_file_buffer_iterator
854 M = PreprocessorOpts.remapped_file_buffer_begin(),
855 E = PreprocessorOpts.remapped_file_buffer_end();
856 M != E;
857 ++M) {
858 llvm::sys::PathWithStatus MPath(M->first);
859 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
860 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
861 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000862 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000863 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000864 CreatedBuffer = false;
865 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000866
Douglas Gregor175c4a92010-07-23 23:58:40 +0000867 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
868
869 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000870 M = PreprocessorOpts.eraseRemappedFile(M);
871 E = PreprocessorOpts.remapped_file_buffer_end();
872 }
873 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000874 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000875 }
876
877 // If the main source file was not remapped, load it now.
878 if (!Buffer) {
879 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
880 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000881 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000882
883 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000884 }
885
Douglas Gregordf95a132010-08-09 20:45:32 +0000886 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000887}
888
Douglas Gregor754f3492010-07-24 00:38:13 +0000889static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
890 bool DeleteOld,
891 unsigned NewSize,
892 llvm::StringRef NewName) {
893 llvm::MemoryBuffer *Result
894 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
895 memcpy(const_cast<char*>(Result->getBufferStart()),
896 Old->getBufferStart(), Old->getBufferSize());
897 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000898 ' ', NewSize - Old->getBufferSize() - 1);
899 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000900
901 if (DeleteOld)
902 delete Old;
903
904 return Result;
905}
906
Douglas Gregor175c4a92010-07-23 23:58:40 +0000907/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
908/// the source file.
909///
910/// This routine will compute the preamble of the main source file. If a
911/// non-trivial preamble is found, it will precompile that preamble into a
912/// precompiled header so that the precompiled preamble can be used to reduce
913/// reparsing time. If a precompiled preamble has already been constructed,
914/// this routine will determine if it is still valid and, if so, avoid
915/// rebuilding the precompiled preamble.
916///
Douglas Gregordf95a132010-08-09 20:45:32 +0000917/// \param AllowRebuild When true (the default), this routine is
918/// allowed to rebuild the precompiled preamble if it is found to be
919/// out-of-date.
920///
921/// \param MaxLines When non-zero, the maximum number of lines that
922/// can occur within the preamble.
923///
Douglas Gregor754f3492010-07-24 00:38:13 +0000924/// \returns If the precompiled preamble can be used, returns a newly-allocated
925/// buffer that should be used in place of the main file when doing so.
926/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000927llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
928 bool AllowRebuild,
929 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000930 CompilerInvocation PreambleInvocation(*Invocation);
931 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
932 PreprocessorOptions &PreprocessorOpts
933 = PreambleInvocation.getPreprocessorOpts();
934
935 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000936 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000937 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000938
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000939 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000940 // We couldn't find a preamble in the main source. Clear out the current
941 // preamble, if we have one. It's obviously no good any more.
942 Preamble.clear();
943 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000944 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000945 PreambleFile.clear();
946 }
947 if (CreatedPreambleBuffer)
948 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000949
950 // The next time we actually see a preamble, precompile it.
951 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000952 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000953 }
954
955 if (!Preamble.empty()) {
956 // We've previously computed a preamble. Check whether we have the same
957 // preamble now that we did before, and that there's enough space in
958 // the main-file buffer within the precompiled preamble to fit the
959 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000960 if (Preamble.size() == NewPreamble.second.first &&
961 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000962 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000963 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000964 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000965 // The preamble has not changed. We may be able to re-use the precompiled
966 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000967
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000968 // Check that none of the files used by the preamble have changed.
969 bool AnyFileChanged = false;
970
971 // First, make a record of those files that have been overridden via
972 // remapping or unsaved_files.
973 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
974 for (PreprocessorOptions::remapped_file_iterator
975 R = PreprocessorOpts.remapped_file_begin(),
976 REnd = PreprocessorOpts.remapped_file_end();
977 !AnyFileChanged && R != REnd;
978 ++R) {
979 struct stat StatBuf;
980 if (stat(R->second.c_str(), &StatBuf)) {
981 // If we can't stat the file we're remapping to, assume that something
982 // horrible happened.
983 AnyFileChanged = true;
984 break;
985 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000986
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000987 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
988 StatBuf.st_mtime);
989 }
990 for (PreprocessorOptions::remapped_file_buffer_iterator
991 R = PreprocessorOpts.remapped_file_buffer_begin(),
992 REnd = PreprocessorOpts.remapped_file_buffer_end();
993 !AnyFileChanged && R != REnd;
994 ++R) {
995 // FIXME: Should we actually compare the contents of file->buffer
996 // remappings?
997 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
998 0);
999 }
1000
1001 // Check whether anything has changed.
1002 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1003 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1004 !AnyFileChanged && F != FEnd;
1005 ++F) {
1006 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1007 = OverriddenFiles.find(F->first());
1008 if (Overridden != OverriddenFiles.end()) {
1009 // This file was remapped; check whether the newly-mapped file
1010 // matches up with the previous mapping.
1011 if (Overridden->second != F->second)
1012 AnyFileChanged = true;
1013 continue;
1014 }
1015
1016 // The file was not remapped; check whether it has changed on disk.
1017 struct stat StatBuf;
1018 if (stat(F->first(), &StatBuf)) {
1019 // If we can't stat the file, assume that something horrible happened.
1020 AnyFileChanged = true;
1021 } else if (StatBuf.st_size != F->second.first ||
1022 StatBuf.st_mtime != F->second.second)
1023 AnyFileChanged = true;
1024 }
1025
1026 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001027 // Okay! We can re-use the precompiled preamble.
1028
1029 // Set the state of the diagnostic object to mimic its state
1030 // after parsing the preamble.
1031 getDiagnostics().Reset();
1032 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1033 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1034 StoredDiagnostics.erase(
1035 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1036 StoredDiagnostics.end());
1037
1038 // Create a version of the main file buffer that is padded to
1039 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001040 return CreatePaddedMainFileBuffer(NewPreamble.first,
1041 CreatedPreambleBuffer,
1042 PreambleReservedSize,
1043 FrontendOpts.Inputs[0].second);
1044 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001045 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001046
1047 // If we aren't allowed to rebuild the precompiled preamble, just
1048 // return now.
1049 if (!AllowRebuild)
1050 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001051
1052 // We can't reuse the previously-computed preamble. Build a new one.
1053 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001054 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001055 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001056 } else if (!AllowRebuild) {
1057 // We aren't allowed to rebuild the precompiled preamble; just
1058 // return now.
1059 return 0;
1060 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001061
1062 // If the preamble rebuild counter > 1, it's because we previously
1063 // failed to build a preamble and we're not yet ready to try
1064 // again. Decrement the counter and return a failure.
1065 if (PreambleRebuildCounter > 1) {
1066 --PreambleRebuildCounter;
1067 return 0;
1068 }
1069
Douglas Gregor175c4a92010-07-23 23:58:40 +00001070 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001071 llvm::Timer *PreambleTimer = 0;
1072 if (TimerGroup.get()) {
1073 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1074 PreambleTimer->startTimer();
1075 Timers.push_back(PreambleTimer);
1076 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001077
1078 // Create a new buffer that stores the preamble. The buffer also contains
1079 // extra space for the original contents of the file (which will be present
1080 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001081 // grows.
1082 PreambleReservedSize = NewPreamble.first->getBufferSize();
1083 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001084 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001085 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001086 PreambleReservedSize *= 2;
1087
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001088 // Save the preamble text for later; we'll need to compare against it for
1089 // subsequent reparses.
1090 Preamble.assign(NewPreamble.first->getBufferStart(),
1091 NewPreamble.first->getBufferStart()
1092 + NewPreamble.second.first);
1093 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1094
Douglas Gregor44c181a2010-07-23 00:33:23 +00001095 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001096 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001097 FrontendOpts.Inputs[0].second);
1098 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001099 NewPreamble.first->getBufferStart(), Preamble.size());
1100 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001101 ' ', PreambleReservedSize - Preamble.size() - 1);
1102 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001103
1104 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001105 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001106 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1107
1108 // Tell the compiler invocation to generate a temporary precompiled header.
1109 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001110 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1111 if (::getenv("LIBCLANG_CHAINING"))
1112 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001113 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +00001114 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001115
1116 // Create the compiler instance to use for building the precompiled preamble.
1117 CompilerInstance Clang;
1118 Clang.setInvocation(&PreambleInvocation);
1119 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1120
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001121 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001122 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001123 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1124 getDiagnostics(),
1125 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001126
1127 // Create the target instance.
1128 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1129 Clang.getTargetOpts()));
1130 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001131 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1132 Preamble.clear();
1133 if (CreatedPreambleBuffer)
1134 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001135 if (PreambleTimer)
1136 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001137 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001138 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001139 }
1140
1141 // Inform the target of the language options.
1142 //
1143 // FIXME: We shouldn't need to do this, the target should be immutable once
1144 // created. This complexity should be lifted elsewhere.
1145 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1146
1147 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1148 "Invocation must have exactly one source file!");
1149 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1150 "FIXME: AST inputs not yet supported here!");
1151 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1152 "IR inputs not support here!");
1153
1154 // Clear out old caches and data.
1155 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001156 TopLevelDecls.clear();
1157 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001158
1159 // Create a file manager object to provide access to and cache the filesystem.
1160 Clang.setFileManager(new FileManager);
1161
1162 // Create the source manager.
1163 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1164
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001165 llvm::OwningPtr<PrecompilePreambleAction> Act;
1166 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001167 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1168 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001169 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001170 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1171 Preamble.clear();
1172 if (CreatedPreambleBuffer)
1173 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001174 if (PreambleTimer)
1175 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001176 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +00001177
Douglas Gregor754f3492010-07-24 00:38:13 +00001178 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001179 }
1180
1181 Act->Execute();
1182 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001183 Clang.takeInvocation();
1184
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001185 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001186 // There were errors parsing the preamble, so no precompiled header was
1187 // generated. Forget that we even tried.
1188 // FIXME: Should we leave a note for ourselves to try again?
1189 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1190 Preamble.clear();
1191 if (CreatedPreambleBuffer)
1192 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001193 if (PreambleTimer)
1194 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001195 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001196 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001197 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001198 }
1199
1200 // Keep track of the preamble we precompiled.
1201 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001202 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1203 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001204
1205 // Keep track of all of the files that the source manager knows about,
1206 // so we can verify whether they have changed or not.
1207 FilesInPreamble.clear();
1208 SourceManager &SourceMgr = Clang.getSourceManager();
1209 const llvm::MemoryBuffer *MainFileBuffer
1210 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1211 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1212 FEnd = SourceMgr.fileinfo_end();
1213 F != FEnd;
1214 ++F) {
1215 const FileEntry *File = F->second->Entry;
1216 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1217 continue;
1218
1219 FilesInPreamble[File->getName()]
1220 = std::make_pair(F->second->getSize(), File->getModificationTime());
1221 }
1222
Douglas Gregor385103b2010-07-30 20:58:08 +00001223 if (PreambleTimer)
1224 PreambleTimer->stopTimer();
1225
Douglas Gregoreababfb2010-08-04 05:53:38 +00001226 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001227 return CreatePaddedMainFileBuffer(NewPreamble.first,
1228 CreatedPreambleBuffer,
1229 PreambleReservedSize,
1230 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001232
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001233void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1234 std::vector<Decl *> Resolved;
1235 Resolved.reserve(TopLevelDeclsInPreamble.size());
1236 ExternalASTSource &Source = *getASTContext().getExternalSource();
1237 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1238 // Resolve the declaration ID to an actual declaration, possibly
1239 // deserializing the declaration in the process.
1240 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1241 if (D)
1242 Resolved.push_back(D);
1243 }
1244 TopLevelDeclsInPreamble.clear();
1245 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1246}
1247
1248unsigned ASTUnit::getMaxPCHLevel() const {
1249 if (!getOnlyLocalDecls())
1250 return Decl::MaxPCHLevel;
1251
1252 unsigned Result = 0;
1253 if (isMainFileAST() || SavedMainFileBuffer)
1254 ++Result;
1255 return Result;
1256}
1257
Douglas Gregorabc563f2010-07-19 21:46:24 +00001258ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1259 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1260 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001262 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001263 bool CompleteTranslationUnit,
1264 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001265 if (!Diags.getPtr()) {
1266 // No diagnostics engine was provided, so create our own diagnostics object
1267 // with the default options.
1268 DiagnosticOptions DiagOpts;
1269 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1270 }
1271
1272 // Create the AST unit.
1273 llvm::OwningPtr<ASTUnit> AST;
1274 AST.reset(new ASTUnit(false));
1275 AST->Diagnostics = Diags;
1276 AST->CaptureDiagnostics = CaptureDiagnostics;
1277 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001278 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001279 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001280 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001281 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001282
Douglas Gregor385103b2010-07-30 20:58:08 +00001283 if (getenv("LIBCLANG_TIMING"))
1284 AST->TimerGroup.reset(
1285 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1286
1287
Douglas Gregor754f3492010-07-24 00:38:13 +00001288 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001289 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001290 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1291 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001292 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001293 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001294
Douglas Gregor385103b2010-07-30 20:58:08 +00001295 llvm::Timer *ParsingTimer = 0;
1296 if (AST->TimerGroup.get()) {
1297 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1298 ParsingTimer->startTimer();
1299 AST->Timers.push_back(ParsingTimer);
1300 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001301
Douglas Gregor385103b2010-07-30 20:58:08 +00001302 bool Failed = AST->Parse(OverrideMainBuffer);
1303 if (ParsingTimer)
1304 ParsingTimer->stopTimer();
1305
1306 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001307}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001308
1309ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1310 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001311 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001312 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001313 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001314 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001315 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001316 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001317 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001318 bool CompleteTranslationUnit,
1319 bool CacheCodeCompletionResults) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001320 bool CreatedDiagnosticsObject = false;
1321
Douglas Gregor28019772010-04-05 23:52:57 +00001322 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001323 // No diagnostics engine was provided, so create our own diagnostics object
1324 // with the default options.
1325 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001326 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001327 CreatedDiagnosticsObject = true;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001328 }
1329
Daniel Dunbar7b556682009-12-02 03:23:45 +00001330 llvm::SmallVector<const char *, 16> Args;
1331 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1332 Args.insert(Args.end(), ArgBegin, ArgEnd);
1333
1334 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1335 // also want to force it to use clang.
1336 Args.push_back("-fsyntax-only");
1337
Daniel Dunbar869824e2009-12-13 03:46:13 +00001338 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001339 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001340 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001341
1342 // Don't check that inputs exist, they have been remapped.
1343 TheDriver.setCheckInputsExist(false);
1344
Daniel Dunbar7b556682009-12-02 03:23:45 +00001345 llvm::OwningPtr<driver::Compilation> C(
1346 TheDriver.BuildCompilation(Args.size(), Args.data()));
1347
1348 // We expect to get back exactly one command job, if we didn't something
1349 // failed.
1350 const driver::JobList &Jobs = C->getJobs();
1351 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1352 llvm::SmallString<256> Msg;
1353 llvm::raw_svector_ostream OS(Msg);
1354 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001355 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001356 return 0;
1357 }
1358
1359 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1360 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001361 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001362 return 0;
1363 }
1364
1365 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001366 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001367 CompilerInvocation::CreateFromArgs(*CI,
1368 const_cast<const char **>(CCArgs.data()),
1369 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001370 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001371 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001372
Douglas Gregor4db64a42010-01-23 00:14:00 +00001373 // Override any files that need remapping
1374 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001375 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001376 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001377
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001378 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001379 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001380
Douglas Gregorf4210892010-08-18 23:38:21 +00001381 CI->getFrontendOpts().DisableFree = false;
Douglas Gregora88084b2010-02-18 18:08:43 +00001382 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001383 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001384 CompleteTranslationUnit,
1385 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001386}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001387
1388bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1389 if (!Invocation.get())
1390 return true;
1391
Douglas Gregor385103b2010-07-30 20:58:08 +00001392 llvm::Timer *ReparsingTimer = 0;
1393 if (TimerGroup.get()) {
1394 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1395 ReparsingTimer->startTimer();
1396 Timers.push_back(ReparsingTimer);
1397 }
1398
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001399 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001400 Invocation->getPreprocessorOpts().clearRemappedFiles();
1401 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1402 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1403 RemappedFiles[I].second);
1404
Douglas Gregoreababfb2010-08-04 05:53:38 +00001405 // If we have a preamble file lying around, or if we might try to
1406 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001407 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001408 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001409 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001410
Douglas Gregorabc563f2010-07-19 21:46:24 +00001411 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001412 if (!OverrideMainBuffer)
1413 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001414
Douglas Gregor175c4a92010-07-23 23:58:40 +00001415 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001416 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001417 if (ReparsingTimer)
1418 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001419
1420 if (ShouldCacheCodeCompletionResults) {
1421 if (CacheCodeCompletionCoolDown > 0)
1422 --CacheCodeCompletionCoolDown;
1423 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1424 CacheCodeCompletionResults();
1425 }
1426
Douglas Gregor175c4a92010-07-23 23:58:40 +00001427 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001428}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001429
Douglas Gregor87c08a52010-08-13 22:48:40 +00001430//----------------------------------------------------------------------------//
1431// Code completion
1432//----------------------------------------------------------------------------//
1433
1434namespace {
1435 /// \brief Code completion consumer that combines the cached code-completion
1436 /// results from an ASTUnit with the code-completion results provided to it,
1437 /// then passes the result on to
1438 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1439 unsigned NormalContexts;
1440 ASTUnit &AST;
1441 CodeCompleteConsumer &Next;
1442
1443 public:
1444 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001445 bool IncludeMacros, bool IncludeCodePatterns,
1446 bool IncludeGlobals)
1447 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001448 Next.isOutputBinary()), AST(AST), Next(Next)
1449 {
1450 // Compute the set of contexts in which we will look when we don't have
1451 // any information about the specific context.
1452 NormalContexts
1453 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1454 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1455 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1456 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1457 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1458 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1459 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1460 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1461 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1462
1463 if (AST.getASTContext().getLangOptions().CPlusPlus)
1464 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1465 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1466 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1467 }
1468
1469 virtual void ProcessCodeCompleteResults(Sema &S,
1470 CodeCompletionContext Context,
1471 Result *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001472 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001473
1474 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1475 OverloadCandidate *Candidates,
1476 unsigned NumCandidates) {
1477 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1478 }
1479 };
1480}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001481
Douglas Gregor5f808c22010-08-16 21:18:39 +00001482/// \brief Helper function that computes which global names are hidden by the
1483/// local code-completion results.
1484void CalculateHiddenNames(const CodeCompletionContext &Context,
1485 CodeCompleteConsumer::Result *Results,
1486 unsigned NumResults,
1487 ASTContext &Ctx,
1488 llvm::StringSet<> &HiddenNames) {
1489 bool OnlyTagNames = false;
1490 switch (Context.getKind()) {
1491 case CodeCompletionContext::CCC_Other:
1492 case CodeCompletionContext::CCC_TopLevel:
1493 case CodeCompletionContext::CCC_ObjCInterface:
1494 case CodeCompletionContext::CCC_ObjCImplementation:
1495 case CodeCompletionContext::CCC_ObjCIvarList:
1496 case CodeCompletionContext::CCC_ClassStructUnion:
1497 case CodeCompletionContext::CCC_Statement:
1498 case CodeCompletionContext::CCC_Expression:
1499 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1500 case CodeCompletionContext::CCC_MemberAccess:
1501 case CodeCompletionContext::CCC_Namespace:
1502 case CodeCompletionContext::CCC_Type:
1503 break;
1504
1505 case CodeCompletionContext::CCC_EnumTag:
1506 case CodeCompletionContext::CCC_UnionTag:
1507 case CodeCompletionContext::CCC_ClassOrStructTag:
1508 OnlyTagNames = true;
1509 break;
1510
1511 case CodeCompletionContext::CCC_ObjCProtocolName:
1512 // If we're just looking for protocol names, nothing can hide them.
1513 return;
1514 }
1515
1516 typedef CodeCompleteConsumer::Result Result;
1517 for (unsigned I = 0; I != NumResults; ++I) {
1518 if (Results[I].Kind != Result::RK_Declaration)
1519 continue;
1520
1521 unsigned IDNS
1522 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1523
1524 bool Hiding = false;
1525 if (OnlyTagNames)
1526 Hiding = (IDNS & Decl::IDNS_Tag);
1527 else {
1528 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001529 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1530 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001531 if (Ctx.getLangOptions().CPlusPlus)
1532 HiddenIDNS |= Decl::IDNS_Tag;
1533 Hiding = (IDNS & HiddenIDNS);
1534 }
1535
1536 if (!Hiding)
1537 continue;
1538
1539 DeclarationName Name = Results[I].Declaration->getDeclName();
1540 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1541 HiddenNames.insert(Identifier->getName());
1542 else
1543 HiddenNames.insert(Name.getAsString());
1544 }
1545}
1546
1547
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001548void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1549 CodeCompletionContext Context,
1550 Result *Results,
1551 unsigned NumResults) {
1552 // Merge the results we were given with the results we cached.
1553 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001554 unsigned InContexts
1555 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1556 : (1 << (Context.getKind() - 1)));
1557
1558 // Contains the set of names that are hidden by "local" completion results.
1559 llvm::StringSet<> HiddenNames;
1560
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001561 typedef CodeCompleteConsumer::Result Result;
1562 llvm::SmallVector<Result, 8> AllResults;
1563 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001564 C = AST.cached_completion_begin(),
1565 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001566 C != CEnd; ++C) {
1567 // If the context we are in matches any of the contexts we are
1568 // interested in, we'll add this result.
1569 if ((C->ShowInContexts & InContexts) == 0)
1570 continue;
1571
1572 // If we haven't added any results previously, do so now.
1573 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001574 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1575 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001576 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1577 AddedResult = true;
1578 }
1579
Douglas Gregor5f808c22010-08-16 21:18:39 +00001580 // Determine whether this global completion result is hidden by a local
1581 // completion result. If so, skip it.
1582 if (C->Kind != CXCursor_MacroDefinition &&
1583 HiddenNames.count(C->Completion->getTypedText()))
1584 continue;
1585
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001586 // Adjust priority based on similar type classes.
1587 unsigned Priority = C->Priority;
1588 if (!Context.getPreferredType().isNull()) {
1589 if (C->Kind == CXCursor_MacroDefinition) {
1590 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1591 Context.getPreferredType()->isAnyPointerType());
1592 } else if (C->Type) {
1593 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001594 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001595 Context.getPreferredType().getUnqualifiedType());
1596 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1597 if (ExpectedSTC == C->TypeClass) {
1598 // We know this type is similar; check for an exact match.
1599 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001600 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001601 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001602 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001603 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1604 Priority /= CCF_ExactTypeMatch;
1605 else
1606 Priority /= CCF_SimilarTypeMatch;
1607 }
1608 }
1609 }
1610
1611 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1612 }
1613
1614 // If we did not add any cached completion results, just forward the
1615 // results we were given to the next consumer.
1616 if (!AddedResult) {
1617 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1618 return;
1619 }
1620
1621 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1622 AllResults.size());
1623}
1624
1625
1626
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001627void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1628 RemappedFile *RemappedFiles,
1629 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001630 bool IncludeMacros,
1631 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001632 CodeCompleteConsumer &Consumer,
1633 Diagnostic &Diag, LangOptions &LangOpts,
1634 SourceManager &SourceMgr, FileManager &FileMgr,
1635 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1636 if (!Invocation.get())
1637 return;
1638
Douglas Gregordf95a132010-08-09 20:45:32 +00001639 llvm::Timer *CompletionTimer = 0;
1640 if (TimerGroup.get()) {
1641 llvm::SmallString<128> TimerName;
1642 llvm::raw_svector_ostream TimerNameOut(TimerName);
1643 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1644 << Column;
1645 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1646 CompletionTimer->startTimer();
1647 Timers.push_back(CompletionTimer);
1648 }
1649
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001650 CompilerInvocation CCInvocation(*Invocation);
1651 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1652 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001653
Douglas Gregor87c08a52010-08-13 22:48:40 +00001654 FrontendOpts.ShowMacrosInCodeCompletion
1655 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001656 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001657 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1658 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001659 FrontendOpts.CodeCompletionAt.FileName = File;
1660 FrontendOpts.CodeCompletionAt.Line = Line;
1661 FrontendOpts.CodeCompletionAt.Column = Column;
1662
Douglas Gregorcee235c2010-08-05 09:09:23 +00001663 // Turn on spell-checking when performing code completion. It leads
1664 // to better results.
1665 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1666 CCInvocation.getLangOpts().SpellChecking = 1;
1667
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001668 // Set the language options appropriately.
1669 LangOpts = CCInvocation.getLangOpts();
1670
1671 CompilerInstance Clang;
1672 Clang.setInvocation(&CCInvocation);
1673 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1674
1675 // Set up diagnostics, capturing any diagnostics produced.
1676 Clang.setDiagnostics(&Diag);
1677 CaptureDroppedDiagnostics Capture(true,
1678 Clang.getDiagnostics(),
1679 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001680
1681 // Create the target instance.
1682 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1683 Clang.getTargetOpts()));
1684 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001685 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001686 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1687 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001688 }
1689
1690 // Inform the target of the language options.
1691 //
1692 // FIXME: We shouldn't need to do this, the target should be immutable once
1693 // created. This complexity should be lifted elsewhere.
1694 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1695
1696 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1697 "Invocation must have exactly one source file!");
1698 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1699 "FIXME: AST inputs not yet supported here!");
1700 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1701 "IR inputs not support here!");
1702
1703
1704 // Use the source and file managers that we were given.
1705 Clang.setFileManager(&FileMgr);
1706 Clang.setSourceManager(&SourceMgr);
1707
1708 // Remap files.
1709 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001710 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001711 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1712 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1713 RemappedFiles[I].second);
1714
Douglas Gregor87c08a52010-08-13 22:48:40 +00001715 // Use the code completion consumer we were given, but adding any cached
1716 // code-completion results.
1717 AugmentedCodeCompleteConsumer
1718 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001719 FrontendOpts.ShowCodePatternsInCodeCompletion,
1720 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001721 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001722
Douglas Gregordf95a132010-08-09 20:45:32 +00001723 // If we have a precompiled preamble, try to use it. We only allow
1724 // the use of the precompiled preamble if we're if the completion
1725 // point is within the main file, after the end of the precompiled
1726 // preamble.
1727 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1728 if (!PreambleFile.empty()) {
1729 using llvm::sys::FileStatus;
1730 llvm::sys::PathWithStatus CompleteFilePath(File);
1731 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1732 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1733 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1734 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1735 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1736 Line);
1737 }
1738
1739 // If the main file has been overridden due to the use of a preamble,
1740 // make that override happen and introduce the preamble.
1741 if (OverrideMainBuffer) {
1742 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1743 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1744 PreprocessorOpts.PrecompiledPreambleBytes.second
1745 = PreambleEndsAtStartOfLine;
1746 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1747 PreprocessorOpts.DisablePCHValidation = true;
1748
1749 // The stored diagnostics have the old source manager. Copy them
1750 // to our output set of stored diagnostics, updating the source
1751 // manager to the one we were given.
1752 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1753 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1754 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1755 StoredDiagnostics[I].setLocation(Loc);
1756 }
1757 }
1758
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001759 llvm::OwningPtr<SyntaxOnlyAction> Act;
1760 Act.reset(new SyntaxOnlyAction);
1761 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1762 Clang.getFrontendOpts().Inputs[0].first)) {
1763 Act->Execute();
1764 Act->EndSourceFile();
1765 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001766
1767 if (CompletionTimer)
1768 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001769
1770 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001771 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001772 Clang.takeFileManager();
1773 Clang.takeSourceManager();
1774 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001775 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001776 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001777}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001778
1779bool ASTUnit::Save(llvm::StringRef File) {
1780 if (getDiagnostics().hasErrorOccurred())
1781 return true;
1782
1783 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1784 // unconditionally create a stat cache when we parse the file?
1785 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001786 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1787 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001788 if (!ErrorInfo.empty() || Out.has_error())
1789 return true;
1790
1791 std::vector<unsigned char> Buffer;
1792 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001793 ASTWriter Writer(Stream);
1794 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001795
1796 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001797 if (!Buffer.empty())
1798 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001799 Out.close();
1800 return Out.has_error();
1801}