blob: 6cd07842157ba76ef8599f05960791bf30776313 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000032#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000035#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000036#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000038#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000039#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000040#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000041#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000046#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000047#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000048#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000049#include "llvm/Support/MutexGuard.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000050#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000051#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000052#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000053#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000054using namespace clang;
55
Douglas Gregor16896c42010-10-28 15:44:59 +000056using llvm::TimeRecord;
57
58namespace {
59 class SimpleTimer {
60 bool WantTiming;
61 TimeRecord Start;
62 std::string Output;
63
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000065 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000067 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000068 }
69
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000071 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000072 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000073 }
74
Douglas Gregor16896c42010-10-28 15:44:59 +000075 ~SimpleTimer() {
76 if (WantTiming) {
77 TimeRecord Elapsed = TimeRecord::getCurrentTime();
78 Elapsed -= Start;
79 llvm::errs() << Output << ':';
80 Elapsed.print(Elapsed, llvm::errs());
81 llvm::errs() << '\n';
82 }
83 }
84 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000085
86 struct OnDiskData {
87 /// \brief The file in which the precompiled preamble is stored.
88 std::string PreambleFile;
89
90 /// \brief Temporary files that should be removed when the ASTUnit is
91 /// destroyed.
92 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
93
94 /// \brief Erase temporary files.
95 void CleanTemporaryFiles();
96
97 /// \brief Erase the preamble file.
98 void CleanPreambleFile();
99
100 /// \brief Erase temporary files and the preamble file.
101 void Cleanup();
102 };
103}
104
Ted Kremenekbd307a52011-10-27 19:44:25 +0000105static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
106 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
107 return M;
108}
109
Ted Kremenek06b4f912011-10-27 17:55:18 +0000110static void cleanupOnDiskMapAtExit(void);
111
112typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
113static OnDiskDataMap &getOnDiskDataMap() {
114 static OnDiskDataMap M;
115 static bool hasRegisteredAtExit = false;
116 if (!hasRegisteredAtExit) {
117 hasRegisteredAtExit = true;
118 atexit(cleanupOnDiskMapAtExit);
119 }
120 return M;
121}
122
123static void cleanupOnDiskMapAtExit(void) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000124 // No mutex required here since we are leaving the program.
Ted Kremenek06b4f912011-10-27 17:55:18 +0000125 OnDiskDataMap &M = getOnDiskDataMap();
126 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
127 // We don't worry about freeing the memory associated with OnDiskDataMap.
128 // All we care about is erasing stale files.
129 I->second->Cleanup();
130 }
131}
132
133static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000134 // We require the mutex since we are modifying the structure of the
135 // DenseMap.
136 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000137 OnDiskDataMap &M = getOnDiskDataMap();
138 OnDiskData *&D = M[AU];
139 if (!D)
140 D = new OnDiskData();
141 return *D;
142}
143
144static void erasePreambleFile(const ASTUnit *AU) {
145 getOnDiskData(AU).CleanPreambleFile();
146}
147
148static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000149 // We require the mutex since we are modifying the structure of the
150 // DenseMap.
151 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152 OnDiskDataMap &M = getOnDiskDataMap();
153 OnDiskDataMap::iterator I = M.find(AU);
154 if (I != M.end()) {
155 I->second->Cleanup();
156 delete I->second;
157 M.erase(AU);
158 }
159}
160
161static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
162 getOnDiskData(AU).PreambleFile = preambleFile;
163}
164
165static const std::string &getPreambleFile(const ASTUnit *AU) {
166 return getOnDiskData(AU).PreambleFile;
167}
168
169void OnDiskData::CleanTemporaryFiles() {
170 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
171 TemporaryFiles[I].eraseFromDisk();
172 TemporaryFiles.clear();
173}
174
175void OnDiskData::CleanPreambleFile() {
176 if (!PreambleFile.empty()) {
177 llvm::sys::Path(PreambleFile).eraseFromDisk();
178 PreambleFile.clear();
179 }
180}
181
182void OnDiskData::Cleanup() {
183 CleanTemporaryFiles();
184 CleanPreambleFile();
185}
186
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000187void ASTUnit::clearFileLevelDecls() {
188 for (FileDeclsTy::iterator
189 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
190 delete I->second;
191 FileDecls.clear();
192}
193
Ted Kremenek06b4f912011-10-27 17:55:18 +0000194void ASTUnit::CleanTemporaryFiles() {
195 getOnDiskData(this).CleanTemporaryFiles();
196}
197
198void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
199 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000200}
201
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000202/// \brief After failing to build a precompiled preamble (due to
203/// errors in the source that occurs in the preamble), the number of
204/// reparses during which we'll skip even trying to precompile the
205/// preamble.
206const unsigned DefaultPreambleRebuildInterval = 5;
207
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000208/// \brief Tracks the number of ASTUnit objects that are currently active.
209///
210/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000211static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000212
Douglas Gregord03e8232010-04-05 21:10:19 +0000213ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000214 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000215 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000216 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000217 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000218 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000219 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000220 ShouldCacheCodeCompletionResults(false),
Chandler Carruthde81fc82011-07-14 09:02:10 +0000221 NestedMacroExpansions(true),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000222 CompletionCacheTopLevelHashValue(0),
223 PreambleTopLevelHashValue(0),
224 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000225 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000226 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000227 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000228 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
229 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000230}
Douglas Gregord03e8232010-04-05 21:10:19 +0000231
Daniel Dunbar764c0822009-12-01 09:51:01 +0000232ASTUnit::~ASTUnit() {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000233 clearFileLevelDecls();
234
Ted Kremenek06b4f912011-10-27 17:55:18 +0000235 // Clean up the temporary files and the preamble file.
236 removeOnDiskEntry(this);
237
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000238 // Free the buffers associated with remapped files. We are required to
239 // perform this operation here because we explicitly request that the
240 // compiler instance *not* free these buffers for each invocation of the
241 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000242 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000243 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
244 for (PreprocessorOptions::remapped_file_buffer_iterator
245 FB = PPOpts.remapped_file_buffer_begin(),
246 FBEnd = PPOpts.remapped_file_buffer_end();
247 FB != FBEnd;
248 ++FB)
249 delete FB->second;
250 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000251
252 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000253 delete PreambleBuffer;
254
Douglas Gregor16896c42010-10-28 15:44:59 +0000255 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000256
257 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000258 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000259 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
260 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000261}
262
Douglas Gregor39982192010-08-15 06:18:01 +0000263/// \brief Determine the set of code-completion contexts in which this
264/// declaration should be shown.
265static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000266 const LangOptions &LangOpts,
267 bool &IsNestedNameSpecifier) {
268 IsNestedNameSpecifier = false;
269
Douglas Gregor39982192010-08-15 06:18:01 +0000270 if (isa<UsingShadowDecl>(ND))
271 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
272 if (!ND)
273 return 0;
274
275 unsigned Contexts = 0;
276 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278 // Types can appear in these contexts.
279 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
280 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
281 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
282 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
283 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000284 | (1 << (CodeCompletionContext::CCC_Type - 1))
285 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000286
287 // In C++, types can appear in expressions contexts (for functional casts).
288 if (LangOpts.CPlusPlus)
289 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
290
291 // In Objective-C, message sends can send interfaces. In Objective-C++,
292 // all types are available due to functional casts.
293 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
294 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000295
296 // In Objective-C, you can only be a subclass of another Objective-C class
297 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor2c595ad2011-07-30 06:55:39 +0000298 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000299
300 // Deal with tag names.
301 if (isa<EnumDecl>(ND)) {
302 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
303
Douglas Gregor59cab552010-08-16 23:05:20 +0000304 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000305 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000306 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000307 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
308 if (Record->isUnion())
309 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
310 else
311 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
312
Douglas Gregor39982192010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000315 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000316 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000317 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
318 // Values can appear in these contexts.
319 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
320 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000321 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000322 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
323 } else if (isa<ObjCProtocolDecl>(ND)) {
324 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000325 } else if (isa<ObjCCategoryDecl>(ND)) {
326 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000327 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000328 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000329
330 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000332 }
333
334 return Contexts;
335}
336
Douglas Gregorb14904c2010-08-13 22:48:40 +0000337void ASTUnit::CacheCodeCompletionResults() {
338 if (!TheSema)
339 return;
340
Douglas Gregor16896c42010-10-28 15:44:59 +0000341 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000342 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000343
344 // Clear out the previous results.
345 ClearCachedCompletionResults();
346
347 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000348 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000350 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000352
353 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000354 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
355
Douglas Gregorb14904c2010-08-13 22:48:40 +0000356 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
357 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000358 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000359 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000360 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000361 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000362 *CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000363 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000364 Ctx->getLangOptions(),
365 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000366 CachedResult.Priority = Results[I].Priority;
367 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000368 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000369
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000370 // Keep track of the type of this completion in an ASTContext-agnostic
371 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000372 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000373 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000374 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000375 CachedResult.Type = 0;
376 } else {
377 CanQualType CanUsageType
378 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
379 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
380
381 // Determine whether we have already seen this type. If so, we save
382 // ourselves the work of formatting the type string by using the
383 // temporary, CanQualType-based hash table to find the associated value.
384 unsigned &TypeValue = CompletionTypes[CanUsageType];
385 if (TypeValue == 0) {
386 TypeValue = CompletionTypes.size();
387 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
388 = TypeValue;
389 }
390
391 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000392 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000393
Douglas Gregor39982192010-08-15 06:18:01 +0000394 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000395
396 /// Handle nested-name-specifiers in C++.
397 if (TheSema->Context.getLangOptions().CPlusPlus &&
398 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
399 // The contexts in which a nested-name-specifier can appear in C++.
400 unsigned NNSContexts
401 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
402 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
403 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
404 | (1 << (CodeCompletionContext::CCC_Statement - 1))
405 | (1 << (CodeCompletionContext::CCC_Expression - 1))
406 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
407 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
408 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
409 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000410 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000411 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
412 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000413
414 if (isa<NamespaceDecl>(Results[I].Declaration) ||
415 isa<NamespaceAliasDecl>(Results[I].Declaration))
416 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
417
418 if (unsigned RemainingContexts
419 = NNSContexts & ~CachedResult.ShowInContexts) {
420 // If there any contexts where this completion can be a
421 // nested-name-specifier but isn't already an option, create a
422 // nested-name-specifier completion.
423 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000424 CachedResult.Completion
425 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000426 *CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000427 CachedResult.ShowInContexts = RemainingContexts;
428 CachedResult.Priority = CCP_NestedNameSpecifier;
429 CachedResult.TypeClass = STC_Void;
430 CachedResult.Type = 0;
431 CachedCompletionResults.push_back(CachedResult);
432 }
433 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000434 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000435 }
436
Douglas Gregorb14904c2010-08-13 22:48:40 +0000437 case Result::RK_Keyword:
438 case Result::RK_Pattern:
439 // Ignore keywords and patterns; we don't care, since they are so
440 // easily regenerated.
441 break;
442
443 case Result::RK_Macro: {
444 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000445 CachedResult.Completion
446 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000447 *CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000448 CachedResult.ShowInContexts
449 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
450 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
451 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
452 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
453 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
454 | (1 << (CodeCompletionContext::CCC_Statement - 1))
455 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000456 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000457 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000458 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000459 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
460 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000461
Douglas Gregorb14904c2010-08-13 22:48:40 +0000462 CachedResult.Priority = Results[I].Priority;
463 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000464 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000465 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000466 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000467 CachedCompletionResults.push_back(CachedResult);
468 break;
469 }
470 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000471 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000472
473 // Save the current top-level hash value.
474 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000475}
476
477void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000479 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000480 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000481}
482
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000483namespace {
484
Sebastian Redl2c499f62010-08-18 23:56:43 +0000485/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000486/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000487class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000488 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000489 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000490 LangOptions &LangOpt;
491 HeaderSearch &HSI;
Douglas Gregor83297df2011-09-01 23:39:15 +0000492 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000493 std::string &Predefines;
494 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000496 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Douglas Gregore8bbc122011-09-02 00:18:52 +0000498 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000500 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
501 HeaderSearch &HSI,
Douglas Gregor83297df2011-09-01 23:39:15 +0000502 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
503 std::string &Predefines,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000504 unsigned &Counter)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000505 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor83297df2011-09-01 23:39:15 +0000506 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000507 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000508
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000509 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000510 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000511 return false;
512
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 LangOpt = LangOpts;
Douglas Gregor83297df2011-09-01 23:39:15 +0000514
515 // Initialize the preprocessor.
516 PP.Initialize(*Target);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000517
518 // Initialize the ASTContext
519 Context.InitBuiltinTypes(*Target);
520
521 InitializedLanguage = true;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 return false;
523 }
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000525 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000526 // If we've already initialized the target, don't do it again.
527 if (Target)
528 return false;
529
530 // FIXME: This is broken, we should store the TargetOptions in the AST file.
531 TargetOptions TargetOpts;
532 TargetOpts.ABI = "";
533 TargetOpts.CXXABI = "";
534 TargetOpts.CPU = "";
535 TargetOpts.Features.clear();
536 TargetOpts.Triple = Triple;
537 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000538 return false;
539 }
Mike Stump11289f42009-09-09 15:08:12 +0000540
Sebastian Redl8b41f302010-07-14 23:29:55 +0000541 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000542 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000543 std::string &SuggestedPredefines,
544 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000545 Predefines = Buffers[0].Data;
546 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
547 Predefines += Buffers[I].Data;
548 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000549 return false;
550 }
Mike Stump11289f42009-09-09 15:08:12 +0000551
Douglas Gregora2f49452010-03-16 19:09:18 +0000552 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
554 }
Mike Stump11289f42009-09-09 15:08:12 +0000555
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000556 virtual void ReadCounter(unsigned Value) {
557 Counter = Value;
558 }
559};
560
David Blaikief18d91a2011-09-26 00:01:39 +0000561class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000562 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000563
564public:
David Blaikief18d91a2011-09-26 00:01:39 +0000565 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000566 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000567 : StoredDiags(StoredDiags) { }
568
David Blaikie9c902b52011-09-25 23:23:43 +0000569 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000570 const Diagnostic &Info);
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000571
572 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
573 // Just drop any diagnostics that come from cloned consumers; they'll
574 // have different source managers anyway.
575 return new IgnoringDiagConsumer();
576 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000577};
578
579/// \brief RAII object that optionally captures diagnostics, if
580/// there is no diagnostic client to capture them already.
581class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000582 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000583 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000584 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000585
586public:
David Blaikie9c902b52011-09-25 23:23:43 +0000587 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000588 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000589 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000590 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000591 if (RequestCapture || Diags.getClient() == 0) {
592 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000593 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000594 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595 }
596
597 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000598 if (Diags.getClient() == &Client) {
599 Diags.takeClient();
600 Diags.setClient(PreviousClient);
601 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000602 }
603};
604
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000605} // anonymous namespace
606
David Blaikief18d91a2011-09-26 00:01:39 +0000607void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000608 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000609 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000610 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000611
Douglas Gregor33cdd812010-02-18 18:08:43 +0000612 StoredDiags.push_back(StoredDiagnostic(Level, Info));
613}
614
Steve Naroffc0683b92009-09-03 18:19:54 +0000615const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000616 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000617}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000618
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000620 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000621 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000622 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000623}
624
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000625/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikie9c902b52011-09-25 23:23:43 +0000626void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000627 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000628 ASTUnit &AST, bool CaptureDiagnostics) {
629 if (!Diags.getPtr()) {
630 // No diagnostics engine was provided, so create our own diagnostics object
631 // with the default options.
632 DiagnosticOptions DiagOpts;
David Blaikiee2eefae2011-09-25 23:39:51 +0000633 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000634 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000635 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000636 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
637 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000638 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000639 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000640 }
641}
642
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000643ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikie9c902b52011-09-25 23:23:43 +0000644 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000645 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000646 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000647 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000648 unsigned NumRemappedFiles,
649 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000650 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000651
652 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000653 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
654 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000655 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
656 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000657 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000658
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000659 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000660
Douglas Gregor16bef852009-10-16 20:01:17 +0000661 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000662 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000663 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000664 AST->FileMgr = new FileManager(FileSystemOpts);
665 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
666 AST->getFileManager());
Douglas Gregor197ac202011-11-11 00:35:06 +0000667 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
668 AST->getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000669
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000670 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000671 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
672 if (const llvm::MemoryBuffer *
673 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
674 // Create the file entry for the file that we're mapping from.
675 const FileEntry *FromFile
676 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
677 memBuf->getBufferSize(),
678 0);
679 if (!FromFile) {
680 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
681 << RemappedFiles[I].first;
682 delete memBuf;
683 continue;
684 }
685
686 // Override the contents of the "from" file with the contents of
687 // the "to" file.
688 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
689
690 } else {
691 const char *fname = fileOrBuf.get<const char *>();
692 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
693 if (!ToFile) {
694 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
695 << RemappedFiles[I].first << fname;
696 continue;
697 }
698
699 // Create the file entry for the file that we're mapping from.
700 const FileEntry *FromFile
701 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
702 ToFile->getSize(),
703 0);
704 if (!FromFile) {
705 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
706 << RemappedFiles[I].first;
707 delete memBuf;
708 continue;
709 }
710
711 // Override the contents of the "from" file with the contents of
712 // the "to" file.
713 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000714 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000715 }
716
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000717 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000718
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000720 std::string Predefines;
721 unsigned Counter;
722
Sebastian Redl2c499f62010-08-18 23:56:43 +0000723 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000724
Douglas Gregor83297df2011-09-01 23:39:15 +0000725 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
726 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
727 *AST,
728 /*IILookup=*/0,
729 /*OwnsHeaderSearch=*/false,
730 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000731 Preprocessor &PP = *AST->PP;
732
733 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
734 AST->getSourceManager(),
735 /*Target=*/0,
736 PP.getIdentifierTable(),
737 PP.getSelectorTable(),
738 PP.getBuiltinInfo(),
739 /* size_reserve = */0,
740 /*DelayInitialization=*/true);
741 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000742
Douglas Gregor8835e032011-09-02 00:26:20 +0000743 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000744
745 // Recover resources if we crash before exiting this method.
746 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
747 ReaderCleanup(Reader.get());
748
Douglas Gregore8bbc122011-09-02 00:18:52 +0000749 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor83297df2011-09-01 23:39:15 +0000750 AST->ASTFileLangOpts, HeaderInfo,
751 AST->Target, Predefines, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000752
Douglas Gregora6895d82011-07-22 16:00:58 +0000753 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000754 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000755 break;
Mike Stump11289f42009-09-09 15:08:12 +0000756
Sebastian Redl2c499f62010-08-18 23:56:43 +0000757 case ASTReader::Failure:
758 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000759 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000760 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000761 }
Mike Stump11289f42009-09-09 15:08:12 +0000762
Daniel Dunbara8a50932009-12-02 08:44:16 +0000763 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
764
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000765 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000766 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Sebastian Redl2c499f62010-08-18 23:56:43 +0000768 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000769 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000770 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000771 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000772 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000773
774 // Unregister the cleanup for ASTReader. It will get cleaned up
775 // by the ASTUnit cleanup.
776 ReaderCleanup.unregister();
777
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000778 Context.setExternalSource(Source);
779
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000780 // Create an AST consumer, even though it isn't used.
781 AST->Consumer.reset(new ASTConsumer);
782
Sebastian Redl2c499f62010-08-18 23:56:43 +0000783 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000784 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
785 AST->TheSema->Initialize();
786 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000787 AST->Reader = ReaderPtr;
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000788
Mike Stump11289f42009-09-09 15:08:12 +0000789 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000790}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000791
792namespace {
793
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000794/// \brief Preprocessor callback class that updates a hash value with the names
795/// of all macros that have been defined by the translation unit.
796class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
797 unsigned &Hash;
798
799public:
800 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
801
802 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
803 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
804 }
805};
806
807/// \brief Add the given declaration to the hash of all top-level entities.
808void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
809 if (!D)
810 return;
811
812 DeclContext *DC = D->getDeclContext();
813 if (!DC)
814 return;
815
816 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
817 return;
818
819 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
820 if (ND->getIdentifier())
821 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
822 else if (DeclarationName Name = ND->getDeclName()) {
823 std::string NameStr = Name.getAsString();
824 Hash = llvm::HashString(NameStr, Hash);
825 }
826 return;
827 }
828
829 if (ObjCForwardProtocolDecl *Forward
830 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
831 for (ObjCForwardProtocolDecl::protocol_iterator
832 P = Forward->protocol_begin(),
833 PEnd = Forward->protocol_end();
834 P != PEnd; ++P)
835 AddTopLevelDeclarationToHash(*P, Hash);
836 return;
837 }
838
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000839 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000840 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000841 return;
842 }
843}
844
Daniel Dunbar644dca02009-12-04 08:17:33 +0000845class TopLevelDeclTrackerConsumer : public ASTConsumer {
846 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000847 unsigned &Hash;
848
Daniel Dunbar644dca02009-12-04 08:17:33 +0000849public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000850 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
851 : Unit(_Unit), Hash(Hash) {
852 Hash = 0;
853 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000854
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000855 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000856 if (!D)
857 return;
858
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000859 // FIXME: Currently ObjC method declarations are incorrectly being
860 // reported as top-level declarations, even though their DeclContext
861 // is the containing ObjC @interface/@implementation. This is a
862 // fundamental problem in the parser right now.
863 if (isa<ObjCMethodDecl>(D))
864 return;
865
866 AddTopLevelDeclarationToHash(D, Hash);
867 Unit.addTopLevelDecl(D);
868
869 handleFileLevelDecl(D);
870 }
871
872 void handleFileLevelDecl(Decl *D) {
873 Unit.addFileLevelDecl(D);
874 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
875 for (NamespaceDecl::decl_iterator
876 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
877 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000878 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000879 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000880
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000881 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000882 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
883 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000884 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000885 }
886
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000887 // We're not interested in "interesting" decls.
888 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000889
890 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
891 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
892 handleTopLevelDecl(*it);
893 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000894};
895
896class TopLevelDeclTrackerAction : public ASTFrontendAction {
897public:
898 ASTUnit &Unit;
899
Daniel Dunbar764c0822009-12-01 09:51:01 +0000900 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000901 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000902 CI.getPreprocessor().addPPCallbacks(
903 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
904 return new TopLevelDeclTrackerConsumer(Unit,
905 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000906 }
907
908public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000909 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
910
Daniel Dunbar764c0822009-12-01 09:51:01 +0000911 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000912 virtual TranslationUnitKind getTranslationUnitKind() {
913 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000914 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000915};
916
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000917class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000918 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000919 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000920 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000921
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000922public:
Douglas Gregor36db4f92011-08-25 22:35:51 +0000923 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000924 StringRef isysroot, raw_ostream *Out)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000925 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000926 Hash(Unit.getCurrentTopLevelHashValue()) {
927 Hash = 0;
928 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000929
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000930 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000931 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
932 Decl *D = *it;
933 // FIXME: Currently ObjC method declarations are incorrectly being
934 // reported as top-level declarations, even though their DeclContext
935 // is the containing ObjC @interface/@implementation. This is a
936 // fundamental problem in the parser right now.
937 if (isa<ObjCMethodDecl>(D))
938 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000939 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000940 TopLevelDecls.push_back(D);
941 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000942 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000943 }
944
945 virtual void HandleTranslationUnit(ASTContext &Ctx) {
946 PCHGenerator::HandleTranslationUnit(Ctx);
947 if (!Unit.getDiagnostics().hasErrorOccurred()) {
948 // Translate the top-level declarations we captured during
949 // parsing into declaration IDs in the precompiled
950 // preamble. This will allow us to deserialize those top-level
951 // declarations when requested.
952 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
953 Unit.addTopLevelDeclFromPreamble(
954 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000955 }
956 }
957};
958
959class PrecompilePreambleAction : public ASTFrontendAction {
960 ASTUnit &Unit;
961
962public:
963 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
964
965 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000966 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000967 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000968 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000969 raw_ostream *OS = 0;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000970 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
971 OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000972 OS))
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000973 return 0;
974
Douglas Gregorc567ba22011-07-22 16:35:34 +0000975 if (!CI.getFrontendOpts().RelocatablePCH)
976 Sysroot.clear();
977
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000978 CI.getPreprocessor().addPPCallbacks(
979 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor36db4f92011-08-25 22:35:51 +0000980 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
981 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000982 }
983
984 virtual bool hasCodeCompletionSupport() const { return false; }
985 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000986 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000987};
988
Daniel Dunbar764c0822009-12-01 09:51:01 +0000989}
990
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000991/// Parse the source file into a translation unit using the given compiler
992/// invocation, replacing the current translation unit.
993///
994/// \returns True if a failure occurred that causes the ASTUnit not to
995/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000996bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000997 delete SavedMainFileBuffer;
998 SavedMainFileBuffer = 0;
999
Ted Kremenek5e14d392011-03-21 18:40:17 +00001000 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001001 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001002 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001003 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001004
Daniel Dunbar764c0822009-12-01 09:51:01 +00001005 // Create the compiler instance to use for building the AST.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001006 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1007
1008 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001009 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1010 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001011
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001012 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1013 CCInvocation(new CompilerInvocation(*Invocation));
1014
1015 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001016 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001017
Douglas Gregor8e984da2010-08-04 16:47:14 +00001018 // Set up diagnostics, capturing any diagnostics that would
1019 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001020 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001021
Daniel Dunbar764c0822009-12-01 09:51:01 +00001022 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001023 Clang->getTargetOpts().Features = TargetFeatures;
1024 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001025 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001026 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001027 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001028 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001029 }
1030
Daniel Dunbar764c0822009-12-01 09:51:01 +00001031 // Inform the target of the language options.
1032 //
1033 // FIXME: We shouldn't need to do this, the target should be immutable once
1034 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001035 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001036
Ted Kremenek84de4a12011-03-21 18:40:07 +00001037 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001038 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001039 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001040 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001041 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001042 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001043
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001044 // Configure the various subsystems.
1045 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001046 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001047 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001048 FileMgr = new FileManager(FileSystemOpts);
1049 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001050 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001051 Ctx = 0;
1052 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001053 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001054
1055 // Clear out old caches and data.
1056 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001057 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001058 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001059
Douglas Gregor7b02b582010-08-20 00:02:33 +00001060 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001061 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregor7b02b582010-08-20 00:02:33 +00001062 TopLevelDeclsInPreamble.clear();
1063 }
1064
Daniel Dunbar764c0822009-12-01 09:51:01 +00001065 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001066 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001067
Daniel Dunbar764c0822009-12-01 09:51:01 +00001068 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001069 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001071 // If the main file has been overridden due to the use of a preamble,
1072 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001073 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthde81fc82011-07-14 09:02:10 +00001074 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1075 = NestedMacroExpansions;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001076 if (OverrideMainBuffer) {
1077 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1078 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1079 PreprocessorOpts.PrecompiledPreambleBytes.second
1080 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001081 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001082 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001083
Douglas Gregord9a30af2010-08-02 20:51:39 +00001084 // The stored diagnostic has the old source manager in it; update
1085 // the locations to refer into the new source manager. Since we've
1086 // been careful to make sure that the source manager's state
1087 // before and after are identical, so that we can reuse the source
1088 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001089 for (unsigned I = NumStoredDiagnosticsFromDriver,
1090 N = StoredDiagnostics.size();
1091 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001092 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1093 getSourceManager());
1094 StoredDiagnostics[I].setLocation(Loc);
1095 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001096
1097 // Keep track of the override buffer;
1098 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001099 }
1100
Ted Kremenek022a4902011-03-22 01:15:24 +00001101 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1102 new TopLevelDeclTrackerAction(*this));
1103
1104 // Recover resources if we crash before exiting this method.
1105 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1106 ActCleanup(Act.get());
1107
Ted Kremenek84de4a12011-03-21 18:40:07 +00001108 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1109 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001110 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001111
1112 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001113 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001114 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1115 getSourceManager(), PreambleDiagnostics,
1116 StoredDiagnostics);
1117 }
1118
Daniel Dunbar644dca02009-12-04 08:17:33 +00001119 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001120
Ted Kremenek5e14d392011-03-21 18:40:17 +00001121 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001122 TheSema.reset(Clang->takeSema());
1123 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +00001124 Ctx = &Clang->getASTContext();
1125 PP = &Clang->getPreprocessor();
1126 Clang->setSourceManager(0);
1127 Clang->setFileManager(0);
1128 Target = &Clang->getTarget();
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001129 Reader = Clang->getModuleManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001130
Daniel Dunbar644dca02009-12-04 08:17:33 +00001131 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001132
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001133 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001134
Daniel Dunbar764c0822009-12-01 09:51:01 +00001135error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001136 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001137 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001138 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001139 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001140 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001141
Douglas Gregorefc46952010-10-12 16:25:54 +00001142 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001143 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001144 return true;
1145}
1146
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001147/// \brief Simple function to retrieve a path for a preamble precompiled header.
1148static std::string GetPreamblePCHPath() {
1149 // FIXME: This is lame; sys::Path should provide this function (in particular,
1150 // it should know how to find the temporary files dir).
1151 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001152 // FIXME: This is a hack so that we can override the preamble file during
1153 // crash-recovery testing, which is the only case where the preamble files
1154 // are not necessarily cleaned up.
1155 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1156 if (TmpFile)
1157 return TmpFile;
1158
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001159 std::string Error;
1160 const char *TmpDir = ::getenv("TMPDIR");
1161 if (!TmpDir)
1162 TmpDir = ::getenv("TEMP");
1163 if (!TmpDir)
1164 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001165#ifdef LLVM_ON_WIN32
1166 if (!TmpDir)
1167 TmpDir = ::getenv("USERPROFILE");
1168#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001169 if (!TmpDir)
1170 TmpDir = "/tmp";
1171 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001172 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001173 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001174 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001175 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001176 return std::string();
1177
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001178 return P.str();
1179}
1180
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001181/// \brief Compute the preamble for the main file, providing the source buffer
1182/// that corresponds to the main file along with a pair (bytes, start-of-line)
1183/// that describes the preamble.
1184std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001185ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1186 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001187 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001188 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001189 CreatedBuffer = false;
1190
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191 // Try to determine if the main file has been remapped, either from the
1192 // command line (to another file) or directly through the compiler invocation
1193 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001194 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001195 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1196 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1197 // Check whether there is a file-file remapping of the main file
1198 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001199 M = PreprocessorOpts.remapped_file_begin(),
1200 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001201 M != E;
1202 ++M) {
1203 llvm::sys::PathWithStatus MPath(M->first);
1204 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1205 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1206 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001207 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001208 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001209 CreatedBuffer = false;
1210 }
1211
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001212 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001213 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001214 return std::make_pair((llvm::MemoryBuffer*)0,
1215 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001216 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001217 }
1218 }
1219 }
1220
1221 // Check whether there is a file-buffer remapping. It supercedes the
1222 // file-file remapping.
1223 for (PreprocessorOptions::remapped_file_buffer_iterator
1224 M = PreprocessorOpts.remapped_file_buffer_begin(),
1225 E = PreprocessorOpts.remapped_file_buffer_end();
1226 M != E;
1227 ++M) {
1228 llvm::sys::PathWithStatus MPath(M->first);
1229 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1230 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1231 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001232 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001233 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001234 CreatedBuffer = false;
1235 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236
Douglas Gregor4dde7492010-07-23 23:58:40 +00001237 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238 }
1239 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001240 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001241 }
1242
1243 // If the main source file was not remapped, load it now.
1244 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001245 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001246 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001247 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001248
1249 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001250 }
1251
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001252 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001253 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001254 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001255}
1256
Douglas Gregor6481ef12010-07-24 00:38:13 +00001257static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001258 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001259 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001260 llvm::MemoryBuffer *Result
1261 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1262 memcpy(const_cast<char*>(Result->getBufferStart()),
1263 Old->getBufferStart(), Old->getBufferSize());
1264 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001265 ' ', NewSize - Old->getBufferSize() - 1);
1266 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001267
Douglas Gregor6481ef12010-07-24 00:38:13 +00001268 return Result;
1269}
1270
Douglas Gregor4dde7492010-07-23 23:58:40 +00001271/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1272/// the source file.
1273///
1274/// This routine will compute the preamble of the main source file. If a
1275/// non-trivial preamble is found, it will precompile that preamble into a
1276/// precompiled header so that the precompiled preamble can be used to reduce
1277/// reparsing time. If a precompiled preamble has already been constructed,
1278/// this routine will determine if it is still valid and, if so, avoid
1279/// rebuilding the precompiled preamble.
1280///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001281/// \param AllowRebuild When true (the default), this routine is
1282/// allowed to rebuild the precompiled preamble if it is found to be
1283/// out-of-date.
1284///
1285/// \param MaxLines When non-zero, the maximum number of lines that
1286/// can occur within the preamble.
1287///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001288/// \returns If the precompiled preamble can be used, returns a newly-allocated
1289/// buffer that should be used in place of the main file when doing so.
1290/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001291llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001292 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001293 bool AllowRebuild,
1294 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001295
1296 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1297 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1298 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001299 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001300 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001301
1302 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001303 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001304 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001305
Douglas Gregor925296b2011-07-19 16:10:42 +00001306 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor3edb1672010-11-16 20:45:51 +00001307 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1308 if (CreatedPreambleBuffer)
1309 OwnedPreambleBuffer.reset(NewPreamble.first);
1310
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001311 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001312 // We couldn't find a preamble in the main source. Clear out the current
1313 // preamble, if we have one. It's obviously no good any more.
1314 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001315 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001316
1317 // The next time we actually see a preamble, precompile it.
1318 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001319 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001320 }
1321
1322 if (!Preamble.empty()) {
1323 // We've previously computed a preamble. Check whether we have the same
1324 // preamble now that we did before, and that there's enough space in
1325 // the main-file buffer within the precompiled preamble to fit the
1326 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001327 if (Preamble.size() == NewPreamble.second.first &&
1328 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001329 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001330 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001331 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001332 // The preamble has not changed. We may be able to re-use the precompiled
1333 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001334
Douglas Gregor0e119552010-07-31 00:40:00 +00001335 // Check that none of the files used by the preamble have changed.
1336 bool AnyFileChanged = false;
1337
1338 // First, make a record of those files that have been overridden via
1339 // remapping or unsaved_files.
1340 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1341 for (PreprocessorOptions::remapped_file_iterator
1342 R = PreprocessorOpts.remapped_file_begin(),
1343 REnd = PreprocessorOpts.remapped_file_end();
1344 !AnyFileChanged && R != REnd;
1345 ++R) {
1346 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001347 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001348 // If we can't stat the file we're remapping to, assume that something
1349 // horrible happened.
1350 AnyFileChanged = true;
1351 break;
1352 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001353
Douglas Gregor0e119552010-07-31 00:40:00 +00001354 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1355 StatBuf.st_mtime);
1356 }
1357 for (PreprocessorOptions::remapped_file_buffer_iterator
1358 R = PreprocessorOpts.remapped_file_buffer_begin(),
1359 REnd = PreprocessorOpts.remapped_file_buffer_end();
1360 !AnyFileChanged && R != REnd;
1361 ++R) {
1362 // FIXME: Should we actually compare the contents of file->buffer
1363 // remappings?
1364 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1365 0);
1366 }
1367
1368 // Check whether anything has changed.
1369 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1370 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1371 !AnyFileChanged && F != FEnd;
1372 ++F) {
1373 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1374 = OverriddenFiles.find(F->first());
1375 if (Overridden != OverriddenFiles.end()) {
1376 // This file was remapped; check whether the newly-mapped file
1377 // matches up with the previous mapping.
1378 if (Overridden->second != F->second)
1379 AnyFileChanged = true;
1380 continue;
1381 }
1382
1383 // The file was not remapped; check whether it has changed on disk.
1384 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001385 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001386 // If we can't stat the file, assume that something horrible happened.
1387 AnyFileChanged = true;
1388 } else if (StatBuf.st_size != F->second.first ||
1389 StatBuf.st_mtime != F->second.second)
1390 AnyFileChanged = true;
1391 }
1392
1393 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001394 // Okay! We can re-use the precompiled preamble.
1395
1396 // Set the state of the diagnostic object to mimic its state
1397 // after parsing the preamble.
1398 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001399 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001400 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001401 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001402
1403 // Create a version of the main file buffer that is padded to
1404 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001405 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001406 PreambleReservedSize,
1407 FrontendOpts.Inputs[0].second);
1408 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001409 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001410
1411 // If we aren't allowed to rebuild the precompiled preamble, just
1412 // return now.
1413 if (!AllowRebuild)
1414 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001415
Douglas Gregor4dde7492010-07-23 23:58:40 +00001416 // We can't reuse the previously-computed preamble. Build a new one.
1417 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001418 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001419 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001420 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001421 } else if (!AllowRebuild) {
1422 // We aren't allowed to rebuild the precompiled preamble; just
1423 // return now.
1424 return 0;
1425 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001426
1427 // If the preamble rebuild counter > 1, it's because we previously
1428 // failed to build a preamble and we're not yet ready to try
1429 // again. Decrement the counter and return a failure.
1430 if (PreambleRebuildCounter > 1) {
1431 --PreambleRebuildCounter;
1432 return 0;
1433 }
1434
Douglas Gregore10f0e52010-09-11 17:56:52 +00001435 // Create a temporary file for the precompiled preamble. In rare
1436 // circumstances, this can fail.
1437 std::string PreamblePCHPath = GetPreamblePCHPath();
1438 if (PreamblePCHPath.empty()) {
1439 // Try again next time.
1440 PreambleRebuildCounter = 1;
1441 return 0;
1442 }
1443
Douglas Gregor4dde7492010-07-23 23:58:40 +00001444 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001445 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001446 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001447
1448 // Create a new buffer that stores the preamble. The buffer also contains
1449 // extra space for the original contents of the file (which will be present
1450 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001451 // grows.
1452 PreambleReservedSize = NewPreamble.first->getBufferSize();
1453 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001454 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001455 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001456 PreambleReservedSize *= 2;
1457
Douglas Gregord9a30af2010-08-02 20:51:39 +00001458 // Save the preamble text for later; we'll need to compare against it for
1459 // subsequent reparses.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001460 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1461 Preamble.assign(FileMgr->getFile(MainFilename),
1462 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001463 NewPreamble.first->getBufferStart()
1464 + NewPreamble.second.first);
1465 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1466
Douglas Gregora0734c52010-08-19 01:33:06 +00001467 delete PreambleBuffer;
1468 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001469 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001470 FrontendOpts.Inputs[0].second);
1471 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001472 NewPreamble.first->getBufferStart(), Preamble.size());
1473 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001474 ' ', PreambleReservedSize - Preamble.size() - 1);
1475 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001476
1477 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001478 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001479 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1480
1481 // Tell the compiler invocation to generate a temporary precompiled header.
1482 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001483 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001484 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001485 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1486 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001487
1488 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001489 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1490
1491 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001492 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1493 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001494
Douglas Gregor3cc15812011-07-01 18:22:13 +00001495 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00001496 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001497
Douglas Gregor8e984da2010-08-04 16:47:14 +00001498 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001499 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001500
1501 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001502 Clang->getTargetOpts().Features = TargetFeatures;
1503 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1504 Clang->getTargetOpts()));
1505 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001506 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1507 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001508 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001509 PreprocessorOpts.eraseRemappedFile(
1510 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001511 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001512 }
1513
1514 // Inform the target of the language options.
1515 //
1516 // FIXME: We shouldn't need to do this, the target should be immutable once
1517 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001518 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001519
Ted Kremenek84de4a12011-03-21 18:40:07 +00001520 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001521 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001522 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001523 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001524 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001525 "IR inputs not support here!");
1526
1527 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001528 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001529 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001530 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001531 TopLevelDecls.clear();
1532 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001533
1534 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001535 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001536
1537 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001538 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001539 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001540
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001541 llvm::OwningPtr<PrecompilePreambleAction> Act;
1542 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001543 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1544 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001545 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1546 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001547 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001548 PreprocessorOpts.eraseRemappedFile(
1549 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001550 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001551 }
1552
1553 Act->Execute();
1554 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001555
Douglas Gregore9db88f2010-08-03 19:06:41 +00001556 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001557 // There were errors parsing the preamble, so no precompiled header was
1558 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001559 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001560 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1561 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001562 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001563 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001564 PreprocessorOpts.eraseRemappedFile(
1565 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001566 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001567 }
1568
Douglas Gregor925296b2011-07-19 16:10:42 +00001569 // Transfer any diagnostics generated when parsing the preamble into the set
1570 // of preamble diagnostics.
1571 PreambleDiagnostics.clear();
1572 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001573 stored_diag_afterDriver_begin(), stored_diag_end());
1574 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregor925296b2011-07-19 16:10:42 +00001575
Douglas Gregor4dde7492010-07-23 23:58:40 +00001576 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001577 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001578 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001579
1580 // Keep track of all of the files that the source manager knows about,
1581 // so we can verify whether they have changed or not.
1582 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001583 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001584 const llvm::MemoryBuffer *MainFileBuffer
1585 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1586 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1587 FEnd = SourceMgr.fileinfo_end();
1588 F != FEnd;
1589 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001590 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001591 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1592 continue;
1593
1594 FilesInPreamble[File->getName()]
1595 = std::make_pair(F->second->getSize(), File->getModificationTime());
1596 }
1597
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001598 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001599 PreprocessorOpts.eraseRemappedFile(
1600 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001601
1602 // If the hash of top-level entities differs from the hash of the top-level
1603 // entities the last time we rebuilt the preamble, clear out the completion
1604 // cache.
1605 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1606 CompletionCacheTopLevelHashValue = 0;
1607 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1608 }
1609
Douglas Gregor6481ef12010-07-24 00:38:13 +00001610 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001611 PreambleReservedSize,
1612 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001613}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001614
Douglas Gregore9db88f2010-08-03 19:06:41 +00001615void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1616 std::vector<Decl *> Resolved;
1617 Resolved.reserve(TopLevelDeclsInPreamble.size());
1618 ExternalASTSource &Source = *getASTContext().getExternalSource();
1619 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1620 // Resolve the declaration ID to an actual declaration, possibly
1621 // deserializing the declaration in the process.
1622 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1623 if (D)
1624 Resolved.push_back(D);
1625 }
1626 TopLevelDeclsInPreamble.clear();
1627 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1628}
1629
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001630StringRef ASTUnit::getMainFileName() const {
Douglas Gregor16896c42010-10-28 15:44:59 +00001631 return Invocation->getFrontendOpts().Inputs[0].second;
1632}
1633
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001634ASTUnit *ASTUnit::create(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001635 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001636 llvm::OwningPtr<ASTUnit> AST;
1637 AST.reset(new ASTUnit(false));
1638 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1639 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001640 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001641 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001642 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001643 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001644
1645 return AST.take();
1646}
1647
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001648ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001649 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001650 ASTFrontendAction *Action,
1651 ASTUnit *Unit) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001652 assert(CI && "A CompilerInvocation is required");
1653
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001654 llvm::OwningPtr<ASTUnit> OwnAST;
1655 ASTUnit *AST = Unit;
1656 if (!AST) {
1657 // Create the AST unit.
1658 OwnAST.reset(create(CI, Diags));
1659 AST = OwnAST.get();
1660 }
1661
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001662 AST->OnlyLocalDecls = false;
1663 AST->CaptureDiagnostics = false;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001664 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001665 AST->ShouldCacheCodeCompletionResults = false;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001666
1667 // Recover resources if we crash before exiting this method.
1668 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001669 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001670 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1671 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001672 DiagCleanup(Diags.getPtr());
1673
1674 // We'll manage file buffers ourselves.
1675 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1676 CI->getFrontendOpts().DisableFree = false;
1677 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1678
1679 // Save the target features.
1680 AST->TargetFeatures = CI->getTargetOpts().Features;
1681
1682 // Create the compiler instance to use for building the AST.
1683 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1684
1685 // Recover resources if we crash before exiting this method.
1686 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1687 CICleanup(Clang.get());
1688
1689 Clang->setInvocation(CI);
1690 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1691
1692 // Set up diagnostics, capturing any diagnostics that would
1693 // otherwise be dropped.
1694 Clang->setDiagnostics(&AST->getDiagnostics());
1695
1696 // Create the target instance.
1697 Clang->getTargetOpts().Features = AST->TargetFeatures;
1698 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1699 Clang->getTargetOpts()));
1700 if (!Clang->hasTarget())
1701 return 0;
1702
1703 // Inform the target of the language options.
1704 //
1705 // FIXME: We shouldn't need to do this, the target should be immutable once
1706 // created. This complexity should be lifted elsewhere.
1707 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1708
1709 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1710 "Invocation must have exactly one source file!");
1711 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1712 "FIXME: AST inputs not yet supported here!");
1713 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1714 "IR inputs not supported here!");
1715
1716 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001717 AST->TheSema.reset();
1718 AST->Ctx = 0;
1719 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001720 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001721
1722 // Create a file manager object to provide access to and cache the filesystem.
1723 Clang->setFileManager(&AST->getFileManager());
1724
1725 // Create the source manager.
1726 Clang->setSourceManager(&AST->getSourceManager());
1727
1728 ASTFrontendAction *Act = Action;
1729
1730 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1731 if (!Act) {
1732 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1733 Act = TrackerAct.get();
1734 }
1735
1736 // Recover resources if we crash before exiting this method.
1737 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1738 ActCleanup(TrackerAct.get());
1739
1740 if (!Act->BeginSourceFile(*Clang.get(),
1741 Clang->getFrontendOpts().Inputs[0].second,
1742 Clang->getFrontendOpts().Inputs[0].first))
1743 return 0;
1744
1745 Act->Execute();
1746
1747 // Steal the created target, context, and preprocessor.
1748 AST->TheSema.reset(Clang->takeSema());
1749 AST->Consumer.reset(Clang->takeASTConsumer());
1750 AST->Ctx = &Clang->getASTContext();
1751 AST->PP = &Clang->getPreprocessor();
1752 Clang->setSourceManager(0);
1753 Clang->setFileManager(0);
1754 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001755 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001756
1757 Act->EndSourceFile();
1758
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001759 if (OwnAST)
1760 return OwnAST.take();
1761 else
1762 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001763}
1764
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001765bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1766 if (!Invocation)
1767 return true;
1768
1769 // We'll manage file buffers ourselves.
1770 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1771 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001772 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001773
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001774 // Save the target features.
1775 TargetFeatures = Invocation->getTargetOpts().Features;
1776
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001777 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001778 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001779 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001780 OverrideMainBuffer
1781 = getMainBufferWithPrecompiledPreamble(*Invocation);
1782 }
1783
Douglas Gregor16896c42010-10-28 15:44:59 +00001784 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001785 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001786
Ted Kremenek022a4902011-03-22 01:15:24 +00001787 // Recover resources if we crash before exiting this method.
1788 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1789 MemBufferCleanup(OverrideMainBuffer);
1790
Douglas Gregor16896c42010-10-28 15:44:59 +00001791 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001792}
1793
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001794ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001795 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001796 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001797 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001798 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001799 TranslationUnitKind TUKind,
Douglas Gregor998caea2011-05-06 16:33:08 +00001800 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001801 bool NestedMacroExpansions) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001802 // Create the AST unit.
1803 llvm::OwningPtr<ASTUnit> AST;
1804 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001805 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001806 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001807 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001808 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001809 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001810 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001811 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001812 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001813
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001814 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001815 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1816 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001817 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1818 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001819 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001820
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001821 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001822}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001823
1824ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1825 const char **ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00001826 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001827 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001828 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001829 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001830 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001831 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001832 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001833 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001834 TranslationUnitKind TUKind,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001835 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001836 bool NestedMacroExpansions) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001837 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001838 // No diagnostics engine was provided, so create our own diagnostics object
1839 // with the default options.
1840 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001841 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1842 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001843 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001844
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001845 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001846
Ted Kremenek5e14d392011-03-21 18:40:17 +00001847 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001848
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001849 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001850
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001851 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001852 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001853
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001854 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001855 llvm::makeArrayRef(ArgBegin, ArgEnd),
1856 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001857 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001858 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001859 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001860
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001861 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001862 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1863 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1864 if (const llvm::MemoryBuffer *
1865 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1866 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1867 } else {
1868 const char *fname = fileOrBuf.get<const char *>();
1869 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1870 }
1871 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001872 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1873 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001874
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001875 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001876 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001877
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001878 // Create the AST unit.
1879 llvm::OwningPtr<ASTUnit> AST;
1880 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001881 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001882 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00001883 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001884 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001885 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001886 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001887 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001888 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001889 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1890 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001891 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001892 AST->Invocation = CI;
Ted Kremenek25047602011-11-17 23:01:17 +00001893 CI = 0; // Zero out now to ease cleanup during crash recovery.
Chandler Carruthde81fc82011-07-14 09:02:10 +00001894 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001895
1896 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001897 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1898 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001899
Chris Lattner5159f612010-11-23 08:35:12 +00001900 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001901}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001902
1903bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001904 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001905 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001906
1907 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001908
Douglas Gregor16896c42010-10-28 15:44:59 +00001909 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001910 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001911
Douglas Gregor0e119552010-07-31 00:40:00 +00001912 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001913 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001914 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001915 for (PreprocessorOptions::remapped_file_buffer_iterator
1916 R = PPOpts.remapped_file_buffer_begin(),
1917 REnd = PPOpts.remapped_file_buffer_end();
1918 R != REnd;
1919 ++R) {
1920 delete R->second;
1921 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001922 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001923 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1924 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1925 if (const llvm::MemoryBuffer *
1926 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1927 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1928 memBuf);
1929 } else {
1930 const char *fname = fileOrBuf.get<const char *>();
1931 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1932 fname);
1933 }
1934 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001935
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001936 // If we have a preamble file lying around, or if we might try to
1937 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001938 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001939 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001940 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001941
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001942 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001943 getDiagnostics().Reset();
1944 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001945 if (OverrideMainBuffer)
1946 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001947
Douglas Gregor4dde7492010-07-23 23:58:40 +00001948 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001949 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001950
1951 // If we're caching global code-completion results, and the top-level
1952 // declarations have changed, clear out the code-completion cache.
1953 if (!Result && ShouldCacheCodeCompletionResults &&
1954 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1955 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001956
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001957 // We now need to clear out the completion allocator for
1958 // clang_getCursorCompletionString; it'll be recreated if necessary.
1959 CursorCompletionAllocator = 0;
1960
Douglas Gregor4dde7492010-07-23 23:58:40 +00001961 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001962}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001963
Douglas Gregorb14904c2010-08-13 22:48:40 +00001964//----------------------------------------------------------------------------//
1965// Code completion
1966//----------------------------------------------------------------------------//
1967
1968namespace {
1969 /// \brief Code completion consumer that combines the cached code-completion
1970 /// results from an ASTUnit with the code-completion results provided to it,
1971 /// then passes the result on to
1972 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00001973 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001974 ASTUnit &AST;
1975 CodeCompleteConsumer &Next;
1976
1977 public:
1978 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001979 bool IncludeMacros, bool IncludeCodePatterns,
1980 bool IncludeGlobals)
1981 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001982 Next.isOutputBinary()), AST(AST), Next(Next)
1983 {
1984 // Compute the set of contexts in which we will look when we don't have
1985 // any information about the specific context.
1986 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00001987 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1988 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1989 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1990 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1991 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1992 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1993 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1994 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1995 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1996 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1997 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1998 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1999 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00002000
Douglas Gregorb14904c2010-08-13 22:48:40 +00002001 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00002002 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2003 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2004 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00002005 }
2006
2007 virtual void ProcessCodeCompleteResults(Sema &S,
2008 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002009 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002010 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002011
2012 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2013 OverloadCandidate *Candidates,
2014 unsigned NumCandidates) {
2015 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2016 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002017
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002018 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002019 return Next.getAllocator();
2020 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002021 };
2022}
Douglas Gregord46cf182010-08-16 20:01:48 +00002023
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002024/// \brief Helper function that computes which global names are hidden by the
2025/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002026static void CalculateHiddenNames(const CodeCompletionContext &Context,
2027 CodeCompletionResult *Results,
2028 unsigned NumResults,
2029 ASTContext &Ctx,
2030 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002031 bool OnlyTagNames = false;
2032 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002033 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002034 case CodeCompletionContext::CCC_TopLevel:
2035 case CodeCompletionContext::CCC_ObjCInterface:
2036 case CodeCompletionContext::CCC_ObjCImplementation:
2037 case CodeCompletionContext::CCC_ObjCIvarList:
2038 case CodeCompletionContext::CCC_ClassStructUnion:
2039 case CodeCompletionContext::CCC_Statement:
2040 case CodeCompletionContext::CCC_Expression:
2041 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002042 case CodeCompletionContext::CCC_DotMemberAccess:
2043 case CodeCompletionContext::CCC_ArrowMemberAccess:
2044 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002045 case CodeCompletionContext::CCC_Namespace:
2046 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002047 case CodeCompletionContext::CCC_Name:
2048 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002049 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002050 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002051 break;
2052
2053 case CodeCompletionContext::CCC_EnumTag:
2054 case CodeCompletionContext::CCC_UnionTag:
2055 case CodeCompletionContext::CCC_ClassOrStructTag:
2056 OnlyTagNames = true;
2057 break;
2058
2059 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002060 case CodeCompletionContext::CCC_MacroName:
2061 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002062 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002063 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002064 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002065 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002066 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002067 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002068 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002069 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2070 case CodeCompletionContext::CCC_ObjCClassMessage:
2071 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002072 // We're looking for nothing, or we're looking for names that cannot
2073 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002074 return;
2075 }
2076
John McCall276321a2010-08-25 06:19:51 +00002077 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002078 for (unsigned I = 0; I != NumResults; ++I) {
2079 if (Results[I].Kind != Result::RK_Declaration)
2080 continue;
2081
2082 unsigned IDNS
2083 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2084
2085 bool Hiding = false;
2086 if (OnlyTagNames)
2087 Hiding = (IDNS & Decl::IDNS_Tag);
2088 else {
2089 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002090 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2091 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002092 if (Ctx.getLangOptions().CPlusPlus)
2093 HiddenIDNS |= Decl::IDNS_Tag;
2094 Hiding = (IDNS & HiddenIDNS);
2095 }
2096
2097 if (!Hiding)
2098 continue;
2099
2100 DeclarationName Name = Results[I].Declaration->getDeclName();
2101 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2102 HiddenNames.insert(Identifier->getName());
2103 else
2104 HiddenNames.insert(Name.getAsString());
2105 }
2106}
2107
2108
Douglas Gregord46cf182010-08-16 20:01:48 +00002109void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2110 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002111 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002112 unsigned NumResults) {
2113 // Merge the results we were given with the results we cached.
2114 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002115 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00002116 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi203f87c2011-08-17 01:46:16 +00002117 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002118 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002119 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002120 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002121 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002122 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002123 C = AST.cached_completion_begin(),
2124 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002125 C != CEnd; ++C) {
2126 // If the context we are in matches any of the contexts we are
2127 // interested in, we'll add this result.
2128 if ((C->ShowInContexts & InContexts) == 0)
2129 continue;
2130
2131 // If we haven't added any results previously, do so now.
2132 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002133 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2134 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002135 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2136 AddedResult = true;
2137 }
2138
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002139 // Determine whether this global completion result is hidden by a local
2140 // completion result. If so, skip it.
2141 if (C->Kind != CXCursor_MacroDefinition &&
2142 HiddenNames.count(C->Completion->getTypedText()))
2143 continue;
2144
Douglas Gregord46cf182010-08-16 20:01:48 +00002145 // Adjust priority based on similar type classes.
2146 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002147 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002148 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002149 if (!Context.getPreferredType().isNull()) {
2150 if (C->Kind == CXCursor_MacroDefinition) {
2151 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002152 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00002153 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002154 } else if (C->Type) {
2155 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002156 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002157 Context.getPreferredType().getUnqualifiedType());
2158 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2159 if (ExpectedSTC == C->TypeClass) {
2160 // We know this type is similar; check for an exact match.
2161 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002162 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002163 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002164 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002165 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2166 Priority /= CCF_ExactTypeMatch;
2167 else
2168 Priority /= CCF_SimilarTypeMatch;
2169 }
2170 }
2171 }
2172
Douglas Gregor12785102010-08-24 20:21:13 +00002173 // Adjust the completion string, if required.
2174 if (C->Kind == CXCursor_MacroDefinition &&
2175 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2176 // Create a new code-completion string that just contains the
2177 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002178 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2179 C->Availability);
2180 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002181 CursorKind = CXCursor_NotImplemented;
2182 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002183 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002184 }
2185
Douglas Gregor8850aa32010-08-25 18:03:13 +00002186 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002187 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002188 }
2189
2190 // If we did not add any cached completion results, just forward the
2191 // results we were given to the next consumer.
2192 if (!AddedResult) {
2193 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2194 return;
2195 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002196
Douglas Gregord46cf182010-08-16 20:01:48 +00002197 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2198 AllResults.size());
2199}
2200
2201
2202
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002203void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002204 RemappedFile *RemappedFiles,
2205 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002206 bool IncludeMacros,
2207 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002208 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002209 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002210 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002211 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2212 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002213 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002214 return;
2215
Douglas Gregor16896c42010-10-28 15:44:59 +00002216 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002217 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002218 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002219
Ted Kremenek5e14d392011-03-21 18:40:17 +00002220 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2221 CCInvocation(new CompilerInvocation(*Invocation));
2222
2223 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2224 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002225
Douglas Gregorb14904c2010-08-13 22:48:40 +00002226 FrontendOpts.ShowMacrosInCodeCompletion
2227 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002228 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002229 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2230 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002231 FrontendOpts.CodeCompletionAt.FileName = File;
2232 FrontendOpts.CodeCompletionAt.Line = Line;
2233 FrontendOpts.CodeCompletionAt.Column = Column;
2234
2235 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002236 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002237
Ted Kremenek84de4a12011-03-21 18:40:07 +00002238 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2239
2240 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002241 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2242 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002243
Ted Kremenek5e14d392011-03-21 18:40:17 +00002244 Clang->setInvocation(&*CCInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002245 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002246
2247 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002248 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002249 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002250 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002251 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002252 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002253
2254 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002255 Clang->getTargetOpts().Features = TargetFeatures;
2256 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2257 Clang->getTargetOpts()));
2258 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002259 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002260 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002261 }
2262
2263 // Inform the target of the language options.
2264 //
2265 // FIXME: We shouldn't need to do this, the target should be immutable once
2266 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002267 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002268
Ted Kremenek84de4a12011-03-21 18:40:07 +00002269 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002270 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002271 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002272 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002273 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002274 "IR inputs not support here!");
2275
2276
2277 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002278 Clang->setFileManager(&FileMgr);
2279 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002280
2281 // Remap files.
2282 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002283 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002284 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002285 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2286 if (const llvm::MemoryBuffer *
2287 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2288 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2289 OwnedBuffers.push_back(memBuf);
2290 } else {
2291 const char *fname = fileOrBuf.get<const char *>();
2292 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2293 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002294 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002295
Douglas Gregorb14904c2010-08-13 22:48:40 +00002296 // Use the code completion consumer we were given, but adding any cached
2297 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002298 AugmentedCodeCompleteConsumer *AugmentedConsumer
2299 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2300 FrontendOpts.ShowMacrosInCodeCompletion,
2301 FrontendOpts.ShowCodePatternsInCodeCompletion,
2302 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002303 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002304
Douglas Gregor028d3e42010-08-09 20:45:32 +00002305 // If we have a precompiled preamble, try to use it. We only allow
2306 // the use of the precompiled preamble if we're if the completion
2307 // point is within the main file, after the end of the precompiled
2308 // preamble.
2309 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002310 if (!getPreambleFile(this).empty()) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002311 using llvm::sys::FileStatus;
2312 llvm::sys::PathWithStatus CompleteFilePath(File);
2313 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2314 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2315 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +00002316 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2317 Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002318 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002319 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002320 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002321 }
2322
2323 // If the main file has been overridden due to the use of a preamble,
2324 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002325 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002326 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00002327 stored_diag_begin(),
2328 stored_diag_afterDriver_begin());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002329 if (OverrideMainBuffer) {
2330 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2331 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2332 PreprocessorOpts.PrecompiledPreambleBytes.second
2333 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002334 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002335 PreprocessorOpts.DisablePCHValidation = true;
2336
Douglas Gregorb97b6662010-08-20 00:59:43 +00002337 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002338 } else {
2339 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2340 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002341 }
2342
Douglas Gregor998caea2011-05-06 16:33:08 +00002343 // Disable the preprocessing record
2344 PreprocessorOpts.DetailedRecord = false;
2345
Douglas Gregor8e984da2010-08-04 16:47:14 +00002346 llvm::OwningPtr<SyntaxOnlyAction> Act;
2347 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002348 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2349 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002350 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00002351 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00002352 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2353 getSourceManager(), PreambleDiagnostics,
2354 StoredDiagnostics);
2355 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002356 Act->Execute();
2357 Act->EndSourceFile();
2358 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002359}
Douglas Gregore9386682010-08-13 05:36:37 +00002360
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002361CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor8a60bbe2011-07-06 17:40:26 +00002362 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor30c80fa2011-07-06 16:43:36 +00002363 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002364
2365 // Write to a temporary file and later rename it to the actual file, to avoid
2366 // possible race conditions.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002367 llvm::SmallString<128> TempPath;
2368 TempPath = File;
2369 TempPath += "-%%%%%%%%";
2370 int fd;
2371 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2372 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002373 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002374
Douglas Gregore9386682010-08-13 05:36:37 +00002375 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2376 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002377 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002378
2379 serialize(Out);
2380 Out.close();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002381 if (Out.has_error())
2382 return CXSaveError_Unknown;
2383
2384 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2385 bool exists;
2386 llvm::sys::fs::remove(TempPath.str(), exists);
2387 return CXSaveError_Unknown;
2388 }
2389
2390 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002391}
2392
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002393bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002394 if (getDiagnostics().hasErrorOccurred())
2395 return true;
2396
Douglas Gregore9386682010-08-13 05:36:37 +00002397 std::vector<unsigned char> Buffer;
2398 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002399 ASTWriter Writer(Stream);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002400 // FIXME: Handle modules
2401 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregore9386682010-08-13 05:36:37 +00002402
2403 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002404 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002405 OS.write((char *)&Buffer.front(), Buffer.size());
2406
2407 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002408}
Douglas Gregor925296b2011-07-19 16:10:42 +00002409
2410typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2411
2412static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2413 unsigned Raw = L.getRawEncoding();
2414 const unsigned MacroBit = 1U << 31;
2415 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2416 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2417}
2418
2419void ASTUnit::TranslateStoredDiagnostics(
2420 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002422 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002423 const SmallVectorImpl<StoredDiagnostic> &Diags,
2424 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002425 // The stored diagnostic has the old source manager in it; update
2426 // the locations to refer into the new source manager. We also need to remap
2427 // all the locations to the new view. This includes the diag location, any
2428 // associated source ranges, and the source ranges of associated fix-its.
2429 // FIXME: There should be a cleaner way to do this.
2430
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002431 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002432 Result.reserve(Diags.size());
2433 assert(MMan && "Don't have a module manager");
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00002434 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002435 assert(Mod && "Don't have preamble module");
2436 SLocRemap &Remap = Mod->SLocRemap;
2437 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2438 // Rebuild the StoredDiagnostic.
2439 const StoredDiagnostic &SD = Diags[I];
2440 SourceLocation L = SD.getLocation();
2441 TranslateSLoc(L, Remap);
2442 FullSourceLoc Loc(L, SrcMgr);
2443
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002444 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002445 Ranges.reserve(SD.range_size());
2446 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2447 E = SD.range_end();
2448 I != E; ++I) {
2449 SourceLocation BL = I->getBegin();
2450 TranslateSLoc(BL, Remap);
2451 SourceLocation EL = I->getEnd();
2452 TranslateSLoc(EL, Remap);
2453 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2454 }
2455
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002456 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002457 FixIts.reserve(SD.fixit_size());
2458 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2459 E = SD.fixit_end();
2460 I != E; ++I) {
2461 FixIts.push_back(FixItHint());
2462 FixItHint &FH = FixIts.back();
2463 FH.CodeToInsert = I->CodeToInsert;
2464 SourceLocation BL = I->RemoveRange.getBegin();
2465 TranslateSLoc(BL, Remap);
2466 SourceLocation EL = I->RemoveRange.getEnd();
2467 TranslateSLoc(EL, Remap);
2468 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2469 I->RemoveRange.isTokenRange());
2470 }
2471
2472 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2473 SD.getMessage(), Loc, Ranges, FixIts));
2474 }
2475 Result.swap(Out);
2476}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002477
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002478static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2479 std::pair<unsigned, Decl *> R) {
2480 return L.first < R.first;
2481}
2482
2483void ASTUnit::addFileLevelDecl(Decl *D) {
2484 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002485
2486 // We only care about local declarations.
2487 if (D->isFromASTFile())
2488 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002489
2490 SourceManager &SM = *SourceMgr;
2491 SourceLocation Loc = D->getLocation();
2492 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2493 return;
2494
2495 // We only keep track of the file-level declarations of each file.
2496 if (!D->getLexicalDeclContext()->isFileContext())
2497 return;
2498
2499 SourceLocation FileLoc = SM.getFileLoc(Loc);
2500 assert(SM.isLocalSourceLocation(FileLoc));
2501 FileID FID;
2502 unsigned Offset;
2503 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2504 if (FID.isInvalid())
2505 return;
2506
2507 LocDeclsTy *&Decls = FileDecls[FID];
2508 if (!Decls)
2509 Decls = new LocDeclsTy();
2510
2511 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2512
2513 if (Decls->empty() || Decls->back().first <= Offset) {
2514 Decls->push_back(LocDecl);
2515 return;
2516 }
2517
2518 LocDeclsTy::iterator
2519 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2520
2521 Decls->insert(I, LocDecl);
2522}
2523
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002524void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2525 SmallVectorImpl<Decl *> &Decls) {
2526 if (File.isInvalid())
2527 return;
2528
2529 if (SourceMgr->isLoadedFileID(File)) {
2530 assert(Ctx->getExternalSource() && "No external source!");
2531 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2532 Decls);
2533 }
2534
2535 FileDeclsTy::iterator I = FileDecls.find(File);
2536 if (I == FileDecls.end())
2537 return;
2538
2539 LocDeclsTy &LocDecls = *I->second;
2540 if (LocDecls.empty())
2541 return;
2542
2543 LocDeclsTy::iterator
2544 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2545 std::make_pair(Offset, (Decl*)0), compLocDecl);
2546 if (BeginIt != LocDecls.begin())
2547 --BeginIt;
2548
2549 LocDeclsTy::iterator
2550 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2551 std::make_pair(Offset+Length, (Decl*)0),
2552 compLocDecl);
2553 if (EndIt != LocDecls.end())
2554 ++EndIt;
2555
2556 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2557 Decls.push_back(DIt->second);
2558}
2559
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002560SourceLocation ASTUnit::getLocation(const FileEntry *File,
2561 unsigned Line, unsigned Col) const {
2562 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002563 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002564 return SM.getMacroArgExpandedLocation(Loc);
2565}
2566
2567SourceLocation ASTUnit::getLocation(const FileEntry *File,
2568 unsigned Offset) const {
2569 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002570 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002571 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2572}
2573
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002574/// \brief If \arg Loc is a loaded location from the preamble, returns
2575/// the corresponding local location of the main file, otherwise it returns
2576/// \arg Loc.
2577SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2578 FileID PreambleID;
2579 if (SourceMgr)
2580 PreambleID = SourceMgr->getPreambleFileID();
2581
2582 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2583 return Loc;
2584
2585 unsigned Offs;
2586 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2587 SourceLocation FileLoc
2588 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2589 return FileLoc.getLocWithOffset(Offs);
2590 }
2591
2592 return Loc;
2593}
2594
2595/// \brief If \arg Loc is a local location of the main file but inside the
2596/// preamble chunk, returns the corresponding loaded location from the
2597/// preamble, otherwise it returns \arg Loc.
2598SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2599 FileID PreambleID;
2600 if (SourceMgr)
2601 PreambleID = SourceMgr->getPreambleFileID();
2602
2603 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2604 return Loc;
2605
2606 unsigned Offs;
2607 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2608 Offs < Preamble.size()) {
2609 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2610 return FileLoc.getLocWithOffset(Offs);
2611 }
2612
2613 return Loc;
2614}
2615
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002616bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2617 FileID FID;
2618 if (SourceMgr)
2619 FID = SourceMgr->getPreambleFileID();
2620
2621 if (Loc.isInvalid() || FID.isInvalid())
2622 return false;
2623
2624 return SourceMgr->isInFileID(Loc, FID);
2625}
2626
2627bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2628 FileID FID;
2629 if (SourceMgr)
2630 FID = SourceMgr->getMainFileID();
2631
2632 if (Loc.isInvalid() || FID.isInvalid())
2633 return false;
2634
2635 return SourceMgr->isInFileID(Loc, FID);
2636}
2637
2638SourceLocation ASTUnit::getEndOfPreambleFileID() {
2639 FileID FID;
2640 if (SourceMgr)
2641 FID = SourceMgr->getPreambleFileID();
2642
2643 if (FID.isInvalid())
2644 return SourceLocation();
2645
2646 return SourceMgr->getLocForEndOfFile(FID);
2647}
2648
2649SourceLocation ASTUnit::getStartOfMainFileID() {
2650 FileID FID;
2651 if (SourceMgr)
2652 FID = SourceMgr->getMainFileID();
2653
2654 if (FID.isInvalid())
2655 return SourceLocation();
2656
2657 return SourceMgr->getLocForStartOfFile(FID);
2658}
2659
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002660void ASTUnit::PreambleData::countLines() const {
2661 NumLines = 0;
2662 if (empty())
2663 return;
2664
2665 for (std::vector<char>::const_iterator
2666 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2667 if (*I == '\n')
2668 ++NumLines;
2669 }
2670 if (Buffer.back() != '\n')
2671 ++NumLines;
2672}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002673
2674#ifndef NDEBUG
2675ASTUnit::ConcurrencyState::ConcurrencyState() {
2676 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2677}
2678
2679ASTUnit::ConcurrencyState::~ConcurrencyState() {
2680 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2681}
2682
2683void ASTUnit::ConcurrencyState::start() {
2684 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2685 assert(acquired && "Concurrent access to ASTUnit!");
2686}
2687
2688void ASTUnit::ConcurrencyState::finish() {
2689 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2690}
2691
2692#else // NDEBUG
2693
2694ASTUnit::ConcurrencyState::ConcurrencyState() {}
2695ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2696void ASTUnit::ConcurrencyState::start() {}
2697void ASTUnit::ConcurrencyState::finish() {}
2698
2699#endif