blob: 428647f03f41eb7157a99edbdda3813062288199 [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"
Douglas Gregor4557e472010-08-17 18:31:01 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000019#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000020#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000021#include "clang/Driver/Compilation.h"
22#include "clang/Driver/Driver.h"
23#include "clang/Driver/Job.h"
24#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor4557e472010-08-17 18:31:01 +000029#include "clang/Frontend/PCHReader.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),
58 CacheCodeCompletionCoolDown(0) {
Douglas Gregor385103b2010-07-30 20:58:08 +000059}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000060
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000061ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000062 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000063 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000064 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000065 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000066
67 // Free the buffers associated with remapped files. We are required to
68 // perform this operation here because we explicitly request that the
69 // compiler instance *not* free these buffers for each invocation of the
70 // parser.
71 if (Invocation.get()) {
72 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
73 for (PreprocessorOptions::remapped_file_buffer_iterator
74 FB = PPOpts.remapped_file_buffer_begin(),
75 FBEnd = PPOpts.remapped_file_buffer_end();
76 FB != FBEnd;
77 ++FB)
78 delete FB->second;
79 }
Douglas Gregor28233422010-07-27 14:52:07 +000080
81 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000082
Douglas Gregor87c08a52010-08-13 22:48:40 +000083 ClearCachedCompletionResults();
84
Douglas Gregor385103b2010-07-30 20:58:08 +000085 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
86 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000087}
88
89void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000090 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
91 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000092 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000093}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000094
Douglas Gregor8071e422010-08-15 06:18:01 +000095/// \brief Determine the set of code-completion contexts in which this
96/// declaration should be shown.
97static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +000098 const LangOptions &LangOpts,
99 bool &IsNestedNameSpecifier) {
100 IsNestedNameSpecifier = false;
101
Douglas Gregor8071e422010-08-15 06:18:01 +0000102 if (isa<UsingShadowDecl>(ND))
103 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
104 if (!ND)
105 return 0;
106
107 unsigned Contexts = 0;
108 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
109 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
110 // Types can appear in these contexts.
111 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
112 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
113 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
114 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
115 | (1 << (CodeCompletionContext::CCC_Statement - 1))
116 | (1 << (CodeCompletionContext::CCC_Type - 1));
117
118 // In C++, types can appear in expressions contexts (for functional casts).
119 if (LangOpts.CPlusPlus)
120 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
121
122 // In Objective-C, message sends can send interfaces. In Objective-C++,
123 // all types are available due to functional casts.
124 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
125 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
126
127 // Deal with tag names.
128 if (isa<EnumDecl>(ND)) {
129 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
130
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000131 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000132 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000133 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000134 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
135 if (Record->isUnion())
136 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
137 else
138 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
139
Douglas Gregor8071e422010-08-15 06:18:01 +0000140 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000141 IsNestedNameSpecifier = true;
142 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
143 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000144 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
145 // Values can appear in these contexts.
146 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
147 | (1 << (CodeCompletionContext::CCC_Expression - 1))
148 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
149 } else if (isa<ObjCProtocolDecl>(ND)) {
150 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
151 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000152 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000153
154 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000155 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000156 }
157
158 return Contexts;
159}
160
Douglas Gregor87c08a52010-08-13 22:48:40 +0000161void ASTUnit::CacheCodeCompletionResults() {
162 if (!TheSema)
163 return;
164
165 llvm::Timer *CachingTimer = 0;
166 if (TimerGroup.get()) {
167 CachingTimer = new llvm::Timer("Cache global code completions",
168 *TimerGroup);
169 CachingTimer->startTimer();
170 Timers.push_back(CachingTimer);
171 }
172
173 // Clear out the previous results.
174 ClearCachedCompletionResults();
175
176 // Gather the set of global code completions.
177 typedef CodeCompleteConsumer::Result Result;
178 llvm::SmallVector<Result, 8> Results;
179 TheSema->GatherGlobalCodeCompletions(Results);
180
181 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000182 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
183
Douglas Gregor87c08a52010-08-13 22:48:40 +0000184 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
185 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000186 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000187 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000188 CachedCodeCompletionResult CachedResult;
189 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
190 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 Ctx->getLangOptions(),
192 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000193 CachedResult.Priority = Results[I].Priority;
194 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000195
Douglas Gregorf5586f62010-08-16 18:08:11 +0000196 // Keep track of the type of this completion in an ASTContext-agnostic
197 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000198 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000199 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000200 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000201 CachedResult.Type = 0;
202 } else {
203 CanQualType CanUsageType
204 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
205 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
206
207 // Determine whether we have already seen this type. If so, we save
208 // ourselves the work of formatting the type string by using the
209 // temporary, CanQualType-based hash table to find the associated value.
210 unsigned &TypeValue = CompletionTypes[CanUsageType];
211 if (TypeValue == 0) {
212 TypeValue = CompletionTypes.size();
213 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
214 = TypeValue;
215 }
216
217 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000218 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000219
Douglas Gregor8071e422010-08-15 06:18:01 +0000220 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000221
222 /// Handle nested-name-specifiers in C++.
223 if (TheSema->Context.getLangOptions().CPlusPlus &&
224 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
225 // The contexts in which a nested-name-specifier can appear in C++.
226 unsigned NNSContexts
227 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
228 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
229 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
230 | (1 << (CodeCompletionContext::CCC_Statement - 1))
231 | (1 << (CodeCompletionContext::CCC_Expression - 1))
232 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
233 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
234 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
235 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
236 | (1 << (CodeCompletionContext::CCC_Type - 1));
237
238 if (isa<NamespaceDecl>(Results[I].Declaration) ||
239 isa<NamespaceAliasDecl>(Results[I].Declaration))
240 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
241
242 if (unsigned RemainingContexts
243 = NNSContexts & ~CachedResult.ShowInContexts) {
244 // If there any contexts where this completion can be a
245 // nested-name-specifier but isn't already an option, create a
246 // nested-name-specifier completion.
247 Results[I].StartsNestedNameSpecifier = true;
248 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
249 CachedResult.ShowInContexts = RemainingContexts;
250 CachedResult.Priority = CCP_NestedNameSpecifier;
251 CachedResult.TypeClass = STC_Void;
252 CachedResult.Type = 0;
253 CachedCompletionResults.push_back(CachedResult);
254 }
255 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000256 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000257 }
258
Douglas Gregor87c08a52010-08-13 22:48:40 +0000259 case Result::RK_Keyword:
260 case Result::RK_Pattern:
261 // Ignore keywords and patterns; we don't care, since they are so
262 // easily regenerated.
263 break;
264
265 case Result::RK_Macro: {
266 CachedCodeCompletionResult CachedResult;
267 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
268 CachedResult.ShowInContexts
269 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
270 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
271 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
272 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
273 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
274 | (1 << (CodeCompletionContext::CCC_Statement - 1))
275 | (1 << (CodeCompletionContext::CCC_Expression - 1))
276 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
277 CachedResult.Priority = Results[I].Priority;
278 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor1827e102010-08-16 16:18:59 +0000279 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000280 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000281 CachedCompletionResults.push_back(CachedResult);
282 break;
283 }
284 }
285 Results[I].Destroy();
286 }
287
288 if (CachingTimer)
289 CachingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +0000290
291 // Make a note of the state when we performed this caching.
292 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
293 CacheCodeCompletionCoolDown = 15;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000294}
295
296void ASTUnit::ClearCachedCompletionResults() {
297 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
298 delete CachedCompletionResults[I].Completion;
299 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000300 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000301}
302
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000303namespace {
304
305/// \brief Gathers information from PCHReader that will be used to initialize
306/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000307class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000308 LangOptions &LangOpt;
309 HeaderSearch &HSI;
310 std::string &TargetTriple;
311 std::string &Predefines;
312 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000314 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000316public:
317 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
318 std::string &TargetTriple, std::string &Predefines,
319 unsigned &Counter)
320 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
321 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000323 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
324 LangOpt = LangOpts;
325 return false;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000328 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000329 TargetTriple = Triple;
330 return false;
331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000333 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000334 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000335 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000336 Predefines = Buffers[0].Data;
337 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
338 Predefines += Buffers[I].Data;
339 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000340 return false;
341 }
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000343 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000344 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000347 virtual void ReadCounter(unsigned Value) {
348 Counter = Value;
349 }
350};
351
Douglas Gregora88084b2010-02-18 18:08:43 +0000352class StoredDiagnosticClient : public DiagnosticClient {
353 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
354
355public:
356 explicit StoredDiagnosticClient(
357 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
358 : StoredDiags(StoredDiags) { }
359
360 virtual void HandleDiagnostic(Diagnostic::Level Level,
361 const DiagnosticInfo &Info);
362};
363
364/// \brief RAII object that optionally captures diagnostics, if
365/// there is no diagnostic client to capture them already.
366class CaptureDroppedDiagnostics {
367 Diagnostic &Diags;
368 StoredDiagnosticClient Client;
369 DiagnosticClient *PreviousClient;
370
371public:
372 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
373 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
374 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
375 {
376 if (RequestCapture || Diags.getClient() == 0)
377 Diags.setClient(&Client);
378 }
379
380 ~CaptureDroppedDiagnostics() {
381 Diags.setClient(PreviousClient);
382 }
383};
384
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000385} // anonymous namespace
386
Douglas Gregora88084b2010-02-18 18:08:43 +0000387void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
388 const DiagnosticInfo &Info) {
389 StoredDiags.push_back(StoredDiagnostic(Level, Info));
390}
391
Steve Naroff77accc12009-09-03 18:19:54 +0000392const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000393 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000394}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000395
Steve Naroffe19944c2009-10-15 22:23:48 +0000396const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000397 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000398 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000399}
400
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000401ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000402 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000403 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000404 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000405 unsigned NumRemappedFiles,
406 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000407 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
408
Douglas Gregor28019772010-04-05 23:52:57 +0000409 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000410 // No diagnostics engine was provided, so create our own diagnostics object
411 // with the default options.
412 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000413 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000414 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000415
416 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000417 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000418 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000419 AST->FileMgr.reset(new FileManager);
420 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000421 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000422
Douglas Gregora88084b2010-02-18 18:08:43 +0000423 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000424 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000425 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000426
Douglas Gregor4db64a42010-01-23 00:14:00 +0000427 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
428 // Create the file entry for the file that we're mapping from.
429 const FileEntry *FromFile
430 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
431 RemappedFiles[I].second->getBufferSize(),
432 0);
433 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000434 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000435 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000436 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000437 continue;
438 }
439
440 // Override the contents of the "from" file with the contents of
441 // the "to" file.
442 AST->getSourceManager().overrideFileContents(FromFile,
443 RemappedFiles[I].second);
444 }
445
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000446 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000448 LangOptions LangInfo;
449 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
450 std::string TargetTriple;
451 std::string Predefines;
452 unsigned Counter;
453
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000454 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000455
Ted Kremenekfc062212009-10-19 21:44:57 +0000456 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000457 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000458 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
459 Predefines, Counter));
460
461 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000462 case PCHReader::Success:
463 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000465 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000466 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000467 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000468 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000471 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
472
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000473 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000475 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000476 //
477 // FIXME: This is broken, we should store the TargetOptions in the PCH.
478 TargetOptions TargetOpts;
479 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000480 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000481 TargetOpts.CPU = "";
482 TargetOpts.Features.clear();
483 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000484 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
485 TargetOpts));
486 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
487 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000488 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000489 Preprocessor &PP = *AST->PP.get();
490
Daniel Dunbard5b61262009-09-21 03:03:47 +0000491 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000492 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000493 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000495 // Create and initialize the ASTContext.
496
497 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000498 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499 *AST->Target.get(),
500 PP.getIdentifierTable(),
501 PP.getSelectorTable(),
502 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000503 /* size_reserve = */0));
504 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Daniel Dunbarcc318932009-09-03 05:59:35 +0000506 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000508 // Attach the PCH reader to the AST context as an external AST
509 // source, so that declarations will be deserialized from the
510 // PCH file as needed.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000511 PCHReader *ReaderPtr = Reader.get();
512 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 Context.setExternalSource(Source);
514
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000515 // Create an AST consumer, even though it isn't used.
516 AST->Consumer.reset(new ASTConsumer);
517
518 // Create a semantic analysis object and tell the PCH reader about it.
519 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
520 AST->TheSema->Initialize();
521 ReaderPtr->InitializeSema(*AST->TheSema);
522
Mike Stump1eb44332009-09-09 15:08:12 +0000523 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000524}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000525
526namespace {
527
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000528class TopLevelDeclTrackerConsumer : public ASTConsumer {
529 ASTUnit &Unit;
530
531public:
532 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
533
534 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000535 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
536 Decl *D = *it;
537 // FIXME: Currently ObjC method declarations are incorrectly being
538 // reported as top-level declarations, even though their DeclContext
539 // is the containing ObjC @interface/@implementation. This is a
540 // fundamental problem in the parser right now.
541 if (isa<ObjCMethodDecl>(D))
542 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000543 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000544 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000545 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000546
547 // We're not interested in "interesting" decls.
548 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000549};
550
551class TopLevelDeclTrackerAction : public ASTFrontendAction {
552public:
553 ASTUnit &Unit;
554
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000555 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
556 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000557 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000558 }
559
560public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000561 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
562
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000563 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000564 virtual bool usesCompleteTranslationUnit() {
565 return Unit.isCompleteTranslationUnit();
566 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000567};
568
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000569class PrecompilePreambleConsumer : public PCHGenerator {
570 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000571 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000572
573public:
574 PrecompilePreambleConsumer(ASTUnit &Unit,
575 const Preprocessor &PP, bool Chaining,
576 const char *isysroot, llvm::raw_ostream *Out)
577 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
578
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000579 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000580 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
581 Decl *D = *it;
582 // FIXME: Currently ObjC method declarations are incorrectly being
583 // reported as top-level declarations, even though their DeclContext
584 // is the containing ObjC @interface/@implementation. This is a
585 // fundamental problem in the parser right now.
586 if (isa<ObjCMethodDecl>(D))
587 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000588 TopLevelDecls.push_back(D);
589 }
590 }
591
592 virtual void HandleTranslationUnit(ASTContext &Ctx) {
593 PCHGenerator::HandleTranslationUnit(Ctx);
594 if (!Unit.getDiagnostics().hasErrorOccurred()) {
595 // Translate the top-level declarations we captured during
596 // parsing into declaration IDs in the precompiled
597 // preamble. This will allow us to deserialize those top-level
598 // declarations when requested.
599 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
600 Unit.addTopLevelDeclFromPreamble(
601 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000602 }
603 }
604};
605
606class PrecompilePreambleAction : public ASTFrontendAction {
607 ASTUnit &Unit;
608
609public:
610 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
611
612 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
613 llvm::StringRef InFile) {
614 std::string Sysroot;
615 llvm::raw_ostream *OS = 0;
616 bool Chaining;
617 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
618 OS, Chaining))
619 return 0;
620
621 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
622 Sysroot.c_str() : 0;
623 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
624 isysroot, OS);
625 }
626
627 virtual bool hasCodeCompletionSupport() const { return false; }
628 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000629 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000630};
631
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000632}
633
Douglas Gregorabc563f2010-07-19 21:46:24 +0000634/// Parse the source file into a translation unit using the given compiler
635/// invocation, replacing the current translation unit.
636///
637/// \returns True if a failure occurred that causes the ASTUnit not to
638/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000639bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000640 delete SavedMainFileBuffer;
641 SavedMainFileBuffer = 0;
642
Douglas Gregorabc563f2010-07-19 21:46:24 +0000643 if (!Invocation.get())
644 return true;
645
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000646 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000647 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000648 Clang.setInvocation(Invocation.take());
649 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
650
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000651 // Set up diagnostics, capturing any diagnostics that would
652 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000653 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000654 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
655 getDiagnostics(),
656 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000657 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000658
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000659 // Create the target instance.
660 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
661 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000662 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000663 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000664 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000665 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000666
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000667 // Inform the target of the language options.
668 //
669 // FIXME: We shouldn't need to do this, the target should be immutable once
670 // created. This complexity should be lifted elsewhere.
671 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000672
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000673 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
674 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000675 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000676 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000677 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
678 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000679
Douglas Gregorabc563f2010-07-19 21:46:24 +0000680 // Configure the various subsystems.
681 // FIXME: Should we retain the previous file manager?
682 FileMgr.reset(new FileManager);
683 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000684 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000685 Ctx.reset();
686 PP.reset();
687
688 // Clear out old caches and data.
689 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000690 CleanTemporaryFiles();
691 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000692
693 if (!OverrideMainBuffer)
694 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000695
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000696 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000697 Clang.setFileManager(&getFileManager());
698
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000699 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000700 Clang.setSourceManager(&getSourceManager());
701
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000702 // If the main file has been overridden due to the use of a preamble,
703 // make that override happen and introduce the preamble.
704 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000705 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000706 if (OverrideMainBuffer) {
707 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
708 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
709 PreprocessorOpts.PrecompiledPreambleBytes.second
710 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000711 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000712 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000713 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000714
715 // Keep track of the override buffer;
716 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000717
718 // The stored diagnostic has the old source manager in it; update
719 // the locations to refer into the new source manager. Since we've
720 // been careful to make sure that the source manager's state
721 // before and after are identical, so that we can reuse the source
722 // location itself.
723 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
724 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
725 getSourceManager());
726 StoredDiagnostics[I].setLocation(Loc);
727 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000728 }
729
Douglas Gregorabc563f2010-07-19 21:46:24 +0000730 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
731 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000732 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000733 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000734 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000735
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000736 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000737
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000738 // Steal the created target, context, and preprocessor, and take back the
739 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000740 TheSema.reset(Clang.takeSema());
741 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000742 Ctx.reset(Clang.takeASTContext());
743 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000744 Clang.takeSourceManager();
745 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000746 Target.reset(Clang.takeTarget());
747
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000748 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000749
750 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000751 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000752 PreprocessorOpts.eraseRemappedFile(
753 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000754 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
755 }
756
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000757 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000758
759 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000760
761 // If we were asked to cache code-completion results and don't have any
762 // results yet, do so now.
763 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
764 CacheCodeCompletionResults();
765
Douglas Gregorabc563f2010-07-19 21:46:24 +0000766 return false;
767
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000768error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000769 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000770 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000771 PreprocessorOpts.eraseRemappedFile(
772 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000773 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000774 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000775 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000776
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000777 Clang.takeSourceManager();
778 Clang.takeFileManager();
779 Clang.takeDiagnosticClient();
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 Clang.setDiagnosticClient(getDiagnostics().getClient());
1127
1128 // Create the target instance.
1129 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1130 Clang.getTargetOpts()));
1131 if (!Clang.hasTarget()) {
1132 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001133 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1134 Preamble.clear();
1135 if (CreatedPreambleBuffer)
1136 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001137 if (PreambleTimer)
1138 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001139 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001140 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001141 }
1142
1143 // Inform the target of the language options.
1144 //
1145 // FIXME: We shouldn't need to do this, the target should be immutable once
1146 // created. This complexity should be lifted elsewhere.
1147 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1148
1149 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1150 "Invocation must have exactly one source file!");
1151 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1152 "FIXME: AST inputs not yet supported here!");
1153 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1154 "IR inputs not support here!");
1155
1156 // Clear out old caches and data.
1157 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001158 TopLevelDecls.clear();
1159 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001160
1161 // Create a file manager object to provide access to and cache the filesystem.
1162 Clang.setFileManager(new FileManager);
1163
1164 // Create the source manager.
1165 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1166
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001167 llvm::OwningPtr<PrecompilePreambleAction> Act;
1168 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001169 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1170 Clang.getFrontendOpts().Inputs[0].first)) {
1171 Clang.takeDiagnosticClient();
1172 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001173 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1174 Preamble.clear();
1175 if (CreatedPreambleBuffer)
1176 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001177 if (PreambleTimer)
1178 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001179 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +00001180
Douglas Gregor754f3492010-07-24 00:38:13 +00001181 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001182 }
1183
1184 Act->Execute();
1185 Act->EndSourceFile();
1186 Clang.takeDiagnosticClient();
1187 Clang.takeInvocation();
1188
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001189 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001190 // There were errors parsing the preamble, so no precompiled header was
1191 // generated. Forget that we even tried.
1192 // FIXME: Should we leave a note for ourselves to try again?
1193 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1194 Preamble.clear();
1195 if (CreatedPreambleBuffer)
1196 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001197 if (PreambleTimer)
1198 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001199 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001200 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001201 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001202 }
1203
1204 // Keep track of the preamble we precompiled.
1205 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001206 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1207 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001208
1209 // Keep track of all of the files that the source manager knows about,
1210 // so we can verify whether they have changed or not.
1211 FilesInPreamble.clear();
1212 SourceManager &SourceMgr = Clang.getSourceManager();
1213 const llvm::MemoryBuffer *MainFileBuffer
1214 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1215 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1216 FEnd = SourceMgr.fileinfo_end();
1217 F != FEnd;
1218 ++F) {
1219 const FileEntry *File = F->second->Entry;
1220 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1221 continue;
1222
1223 FilesInPreamble[File->getName()]
1224 = std::make_pair(F->second->getSize(), File->getModificationTime());
1225 }
1226
Douglas Gregor385103b2010-07-30 20:58:08 +00001227 if (PreambleTimer)
1228 PreambleTimer->stopTimer();
1229
Douglas Gregoreababfb2010-08-04 05:53:38 +00001230 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001231 return CreatePaddedMainFileBuffer(NewPreamble.first,
1232 CreatedPreambleBuffer,
1233 PreambleReservedSize,
1234 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001235}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001236
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001237void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1238 std::vector<Decl *> Resolved;
1239 Resolved.reserve(TopLevelDeclsInPreamble.size());
1240 ExternalASTSource &Source = *getASTContext().getExternalSource();
1241 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1242 // Resolve the declaration ID to an actual declaration, possibly
1243 // deserializing the declaration in the process.
1244 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1245 if (D)
1246 Resolved.push_back(D);
1247 }
1248 TopLevelDeclsInPreamble.clear();
1249 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1250}
1251
1252unsigned ASTUnit::getMaxPCHLevel() const {
1253 if (!getOnlyLocalDecls())
1254 return Decl::MaxPCHLevel;
1255
1256 unsigned Result = 0;
1257 if (isMainFileAST() || SavedMainFileBuffer)
1258 ++Result;
1259 return Result;
1260}
1261
Douglas Gregorabc563f2010-07-19 21:46:24 +00001262ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1263 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1264 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001265 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001266 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001267 bool CompleteTranslationUnit,
1268 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001269 if (!Diags.getPtr()) {
1270 // No diagnostics engine was provided, so create our own diagnostics object
1271 // with the default options.
1272 DiagnosticOptions DiagOpts;
1273 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1274 }
1275
1276 // Create the AST unit.
1277 llvm::OwningPtr<ASTUnit> AST;
1278 AST.reset(new ASTUnit(false));
1279 AST->Diagnostics = Diags;
1280 AST->CaptureDiagnostics = CaptureDiagnostics;
1281 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001282 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001283 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001284 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001285 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001286
Douglas Gregor385103b2010-07-30 20:58:08 +00001287 if (getenv("LIBCLANG_TIMING"))
1288 AST->TimerGroup.reset(
1289 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1290
1291
Douglas Gregor754f3492010-07-24 00:38:13 +00001292 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001293 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001294 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1295 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001296 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001297 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001298
Douglas Gregor385103b2010-07-30 20:58:08 +00001299 llvm::Timer *ParsingTimer = 0;
1300 if (AST->TimerGroup.get()) {
1301 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1302 ParsingTimer->startTimer();
1303 AST->Timers.push_back(ParsingTimer);
1304 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001305
Douglas Gregor385103b2010-07-30 20:58:08 +00001306 bool Failed = AST->Parse(OverrideMainBuffer);
1307 if (ParsingTimer)
1308 ParsingTimer->stopTimer();
1309
1310 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001311}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001312
1313ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1314 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001315 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001316 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001317 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001318 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001319 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001320 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001321 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001322 bool CompleteTranslationUnit,
1323 bool CacheCodeCompletionResults) {
Douglas Gregor28019772010-04-05 23:52:57 +00001324 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001325 // No diagnostics engine was provided, so create our own diagnostics object
1326 // with the default options.
1327 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001328 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001329 }
1330
Daniel Dunbar7b556682009-12-02 03:23:45 +00001331 llvm::SmallVector<const char *, 16> Args;
1332 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1333 Args.insert(Args.end(), ArgBegin, ArgEnd);
1334
1335 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1336 // also want to force it to use clang.
1337 Args.push_back("-fsyntax-only");
1338
Daniel Dunbar869824e2009-12-13 03:46:13 +00001339 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001340 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001341 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001342
1343 // Don't check that inputs exist, they have been remapped.
1344 TheDriver.setCheckInputsExist(false);
1345
Daniel Dunbar7b556682009-12-02 03:23:45 +00001346 llvm::OwningPtr<driver::Compilation> C(
1347 TheDriver.BuildCompilation(Args.size(), Args.data()));
1348
1349 // We expect to get back exactly one command job, if we didn't something
1350 // failed.
1351 const driver::JobList &Jobs = C->getJobs();
1352 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1353 llvm::SmallString<256> Msg;
1354 llvm::raw_svector_ostream OS(Msg);
1355 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001356 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001357 return 0;
1358 }
1359
1360 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1361 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001362 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001363 return 0;
1364 }
1365
1366 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001367 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001368 CompilerInvocation::CreateFromArgs(*CI,
1369 const_cast<const char **>(CCArgs.data()),
1370 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001371 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001372 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001373
Douglas Gregor4db64a42010-01-23 00:14:00 +00001374 // Override any files that need remapping
1375 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001376 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001377 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001378
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001379 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001380 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001381
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001382 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001383 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001384 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001385 CompleteTranslationUnit,
1386 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001387}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001388
1389bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1390 if (!Invocation.get())
1391 return true;
1392
Douglas Gregor385103b2010-07-30 20:58:08 +00001393 llvm::Timer *ReparsingTimer = 0;
1394 if (TimerGroup.get()) {
1395 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1396 ReparsingTimer->startTimer();
1397 Timers.push_back(ReparsingTimer);
1398 }
1399
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001400 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001401 Invocation->getPreprocessorOpts().clearRemappedFiles();
1402 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1403 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1404 RemappedFiles[I].second);
1405
Douglas Gregoreababfb2010-08-04 05:53:38 +00001406 // If we have a preamble file lying around, or if we might try to
1407 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001408 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001409 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001410 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001411
Douglas Gregorabc563f2010-07-19 21:46:24 +00001412 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001413 if (!OverrideMainBuffer)
1414 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001415
Douglas Gregor175c4a92010-07-23 23:58:40 +00001416 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001417 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001418 if (ReparsingTimer)
1419 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001420
1421 if (ShouldCacheCodeCompletionResults) {
1422 if (CacheCodeCompletionCoolDown > 0)
1423 --CacheCodeCompletionCoolDown;
1424 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1425 CacheCodeCompletionResults();
1426 }
1427
Douglas Gregor175c4a92010-07-23 23:58:40 +00001428 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001429}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001430
Douglas Gregor87c08a52010-08-13 22:48:40 +00001431//----------------------------------------------------------------------------//
1432// Code completion
1433//----------------------------------------------------------------------------//
1434
1435namespace {
1436 /// \brief Code completion consumer that combines the cached code-completion
1437 /// results from an ASTUnit with the code-completion results provided to it,
1438 /// then passes the result on to
1439 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1440 unsigned NormalContexts;
1441 ASTUnit &AST;
1442 CodeCompleteConsumer &Next;
1443
1444 public:
1445 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001446 bool IncludeMacros, bool IncludeCodePatterns,
1447 bool IncludeGlobals)
1448 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001449 Next.isOutputBinary()), AST(AST), Next(Next)
1450 {
1451 // Compute the set of contexts in which we will look when we don't have
1452 // any information about the specific context.
1453 NormalContexts
1454 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1455 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1456 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1457 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1458 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1459 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1460 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1461 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1462 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1463
1464 if (AST.getASTContext().getLangOptions().CPlusPlus)
1465 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1466 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1467 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1468 }
1469
1470 virtual void ProcessCodeCompleteResults(Sema &S,
1471 CodeCompletionContext Context,
1472 Result *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001473 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001474
1475 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1476 OverloadCandidate *Candidates,
1477 unsigned NumCandidates) {
1478 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1479 }
1480 };
1481}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001482
Douglas Gregor5f808c22010-08-16 21:18:39 +00001483/// \brief Helper function that computes which global names are hidden by the
1484/// local code-completion results.
1485void CalculateHiddenNames(const CodeCompletionContext &Context,
1486 CodeCompleteConsumer::Result *Results,
1487 unsigned NumResults,
1488 ASTContext &Ctx,
1489 llvm::StringSet<> &HiddenNames) {
1490 bool OnlyTagNames = false;
1491 switch (Context.getKind()) {
1492 case CodeCompletionContext::CCC_Other:
1493 case CodeCompletionContext::CCC_TopLevel:
1494 case CodeCompletionContext::CCC_ObjCInterface:
1495 case CodeCompletionContext::CCC_ObjCImplementation:
1496 case CodeCompletionContext::CCC_ObjCIvarList:
1497 case CodeCompletionContext::CCC_ClassStructUnion:
1498 case CodeCompletionContext::CCC_Statement:
1499 case CodeCompletionContext::CCC_Expression:
1500 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1501 case CodeCompletionContext::CCC_MemberAccess:
1502 case CodeCompletionContext::CCC_Namespace:
1503 case CodeCompletionContext::CCC_Type:
1504 break;
1505
1506 case CodeCompletionContext::CCC_EnumTag:
1507 case CodeCompletionContext::CCC_UnionTag:
1508 case CodeCompletionContext::CCC_ClassOrStructTag:
1509 OnlyTagNames = true;
1510 break;
1511
1512 case CodeCompletionContext::CCC_ObjCProtocolName:
1513 // If we're just looking for protocol names, nothing can hide them.
1514 return;
1515 }
1516
1517 typedef CodeCompleteConsumer::Result Result;
1518 for (unsigned I = 0; I != NumResults; ++I) {
1519 if (Results[I].Kind != Result::RK_Declaration)
1520 continue;
1521
1522 unsigned IDNS
1523 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1524
1525 bool Hiding = false;
1526 if (OnlyTagNames)
1527 Hiding = (IDNS & Decl::IDNS_Tag);
1528 else {
1529 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001530 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1531 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001532 if (Ctx.getLangOptions().CPlusPlus)
1533 HiddenIDNS |= Decl::IDNS_Tag;
1534 Hiding = (IDNS & HiddenIDNS);
1535 }
1536
1537 if (!Hiding)
1538 continue;
1539
1540 DeclarationName Name = Results[I].Declaration->getDeclName();
1541 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1542 HiddenNames.insert(Identifier->getName());
1543 else
1544 HiddenNames.insert(Name.getAsString());
1545 }
1546}
1547
1548
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001549void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1550 CodeCompletionContext Context,
1551 Result *Results,
1552 unsigned NumResults) {
1553 // Merge the results we were given with the results we cached.
1554 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001555 unsigned InContexts
1556 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1557 : (1 << (Context.getKind() - 1)));
1558
1559 // Contains the set of names that are hidden by "local" completion results.
1560 llvm::StringSet<> HiddenNames;
1561
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001562 typedef CodeCompleteConsumer::Result Result;
1563 llvm::SmallVector<Result, 8> AllResults;
1564 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001565 C = AST.cached_completion_begin(),
1566 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001567 C != CEnd; ++C) {
1568 // If the context we are in matches any of the contexts we are
1569 // interested in, we'll add this result.
1570 if ((C->ShowInContexts & InContexts) == 0)
1571 continue;
1572
1573 // If we haven't added any results previously, do so now.
1574 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001575 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1576 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001577 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1578 AddedResult = true;
1579 }
1580
Douglas Gregor5f808c22010-08-16 21:18:39 +00001581 // Determine whether this global completion result is hidden by a local
1582 // completion result. If so, skip it.
1583 if (C->Kind != CXCursor_MacroDefinition &&
1584 HiddenNames.count(C->Completion->getTypedText()))
1585 continue;
1586
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001587 // Adjust priority based on similar type classes.
1588 unsigned Priority = C->Priority;
1589 if (!Context.getPreferredType().isNull()) {
1590 if (C->Kind == CXCursor_MacroDefinition) {
1591 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1592 Context.getPreferredType()->isAnyPointerType());
1593 } else if (C->Type) {
1594 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001595 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001596 Context.getPreferredType().getUnqualifiedType());
1597 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1598 if (ExpectedSTC == C->TypeClass) {
1599 // We know this type is similar; check for an exact match.
1600 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001601 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001602 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001603 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001604 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1605 Priority /= CCF_ExactTypeMatch;
1606 else
1607 Priority /= CCF_SimilarTypeMatch;
1608 }
1609 }
1610 }
1611
1612 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1613 }
1614
1615 // If we did not add any cached completion results, just forward the
1616 // results we were given to the next consumer.
1617 if (!AddedResult) {
1618 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1619 return;
1620 }
1621
1622 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1623 AllResults.size());
1624}
1625
1626
1627
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001628void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1629 RemappedFile *RemappedFiles,
1630 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001631 bool IncludeMacros,
1632 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001633 CodeCompleteConsumer &Consumer,
1634 Diagnostic &Diag, LangOptions &LangOpts,
1635 SourceManager &SourceMgr, FileManager &FileMgr,
1636 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1637 if (!Invocation.get())
1638 return;
1639
Douglas Gregordf95a132010-08-09 20:45:32 +00001640 llvm::Timer *CompletionTimer = 0;
1641 if (TimerGroup.get()) {
1642 llvm::SmallString<128> TimerName;
1643 llvm::raw_svector_ostream TimerNameOut(TimerName);
1644 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1645 << Column;
1646 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1647 CompletionTimer->startTimer();
1648 Timers.push_back(CompletionTimer);
1649 }
1650
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001651 CompilerInvocation CCInvocation(*Invocation);
1652 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1653 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001654
Douglas Gregor87c08a52010-08-13 22:48:40 +00001655 FrontendOpts.ShowMacrosInCodeCompletion
1656 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001657 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001658 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1659 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001660 FrontendOpts.CodeCompletionAt.FileName = File;
1661 FrontendOpts.CodeCompletionAt.Line = Line;
1662 FrontendOpts.CodeCompletionAt.Column = Column;
1663
Douglas Gregorcee235c2010-08-05 09:09:23 +00001664 // Turn on spell-checking when performing code completion. It leads
1665 // to better results.
1666 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1667 CCInvocation.getLangOpts().SpellChecking = 1;
1668
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001669 // Set the language options appropriately.
1670 LangOpts = CCInvocation.getLangOpts();
1671
1672 CompilerInstance Clang;
1673 Clang.setInvocation(&CCInvocation);
1674 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1675
1676 // Set up diagnostics, capturing any diagnostics produced.
1677 Clang.setDiagnostics(&Diag);
1678 CaptureDroppedDiagnostics Capture(true,
1679 Clang.getDiagnostics(),
1680 StoredDiagnostics);
1681 Clang.setDiagnosticClient(Diag.getClient());
1682
1683 // Create the target instance.
1684 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1685 Clang.getTargetOpts()));
1686 if (!Clang.hasTarget()) {
1687 Clang.takeDiagnosticClient();
1688 Clang.takeInvocation();
1689 }
1690
1691 // Inform the target of the language options.
1692 //
1693 // FIXME: We shouldn't need to do this, the target should be immutable once
1694 // created. This complexity should be lifted elsewhere.
1695 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1696
1697 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1698 "Invocation must have exactly one source file!");
1699 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1700 "FIXME: AST inputs not yet supported here!");
1701 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1702 "IR inputs not support here!");
1703
1704
1705 // Use the source and file managers that we were given.
1706 Clang.setFileManager(&FileMgr);
1707 Clang.setSourceManager(&SourceMgr);
1708
1709 // Remap files.
1710 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001711 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001712 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1713 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1714 RemappedFiles[I].second);
1715
Douglas Gregor87c08a52010-08-13 22:48:40 +00001716 // Use the code completion consumer we were given, but adding any cached
1717 // code-completion results.
1718 AugmentedCodeCompleteConsumer
1719 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001720 FrontendOpts.ShowCodePatternsInCodeCompletion,
1721 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001722 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001723
Douglas Gregordf95a132010-08-09 20:45:32 +00001724 // If we have a precompiled preamble, try to use it. We only allow
1725 // the use of the precompiled preamble if we're if the completion
1726 // point is within the main file, after the end of the precompiled
1727 // preamble.
1728 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1729 if (!PreambleFile.empty()) {
1730 using llvm::sys::FileStatus;
1731 llvm::sys::PathWithStatus CompleteFilePath(File);
1732 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1733 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1734 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1735 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1736 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1737 Line);
1738 }
1739
1740 // If the main file has been overridden due to the use of a preamble,
1741 // make that override happen and introduce the preamble.
1742 if (OverrideMainBuffer) {
1743 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1744 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1745 PreprocessorOpts.PrecompiledPreambleBytes.second
1746 = PreambleEndsAtStartOfLine;
1747 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1748 PreprocessorOpts.DisablePCHValidation = true;
1749
1750 // The stored diagnostics have the old source manager. Copy them
1751 // to our output set of stored diagnostics, updating the source
1752 // manager to the one we were given.
1753 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1754 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1755 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1756 StoredDiagnostics[I].setLocation(Loc);
1757 }
1758 }
1759
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001760 llvm::OwningPtr<SyntaxOnlyAction> Act;
1761 Act.reset(new SyntaxOnlyAction);
1762 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1763 Clang.getFrontendOpts().Inputs[0].first)) {
1764 Act->Execute();
1765 Act->EndSourceFile();
1766 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001767
1768 if (CompletionTimer)
1769 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001770
1771 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001772 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001773 Clang.takeFileManager();
1774 Clang.takeSourceManager();
1775 Clang.takeInvocation();
1776 Clang.takeDiagnosticClient();
1777 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001778 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001779}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001780
1781bool ASTUnit::Save(llvm::StringRef File) {
1782 if (getDiagnostics().hasErrorOccurred())
1783 return true;
1784
1785 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1786 // unconditionally create a stat cache when we parse the file?
1787 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001788 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1789 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001790 if (!ErrorInfo.empty() || Out.has_error())
1791 return true;
1792
1793 std::vector<unsigned char> Buffer;
1794 llvm::BitstreamWriter Stream(Buffer);
1795 PCHWriter Writer(Stream);
1796 Writer.WritePCH(getSema(), 0, 0);
1797
1798 // Write the generated bitstream to "Out".
1799 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001800 Out.close();
1801 return Out.has_error();
1802}