blob: cb52a2f34969567b86be052ff2cd2e829bf59d98 [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 Kyrtzidis35dcda72011-03-09 17:21:42 +0000214 : OnlyLocalDecls(false), CaptureDiagnostics(false),
215 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());
Chris Lattner5159f612010-11-23 08:35:12 +0000667 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000668
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000669 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000670 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
671 if (const llvm::MemoryBuffer *
672 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
673 // Create the file entry for the file that we're mapping from.
674 const FileEntry *FromFile
675 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
676 memBuf->getBufferSize(),
677 0);
678 if (!FromFile) {
679 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
680 << RemappedFiles[I].first;
681 delete memBuf;
682 continue;
683 }
684
685 // Override the contents of the "from" file with the contents of
686 // the "to" file.
687 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
688
689 } else {
690 const char *fname = fileOrBuf.get<const char *>();
691 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
692 if (!ToFile) {
693 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
694 << RemappedFiles[I].first << fname;
695 continue;
696 }
697
698 // Create the file entry for the file that we're mapping from.
699 const FileEntry *FromFile
700 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
701 ToFile->getSize(),
702 0);
703 if (!FromFile) {
704 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
705 << RemappedFiles[I].first;
706 delete memBuf;
707 continue;
708 }
709
710 // Override the contents of the "from" file with the contents of
711 // the "to" file.
712 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000713 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000714 }
715
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000716 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000717
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000718 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 std::string Predefines;
720 unsigned Counter;
721
Sebastian Redl2c499f62010-08-18 23:56:43 +0000722 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000723
Douglas Gregor83297df2011-09-01 23:39:15 +0000724 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
725 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
726 *AST,
727 /*IILookup=*/0,
728 /*OwnsHeaderSearch=*/false,
729 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000730 Preprocessor &PP = *AST->PP;
731
732 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
733 AST->getSourceManager(),
734 /*Target=*/0,
735 PP.getIdentifierTable(),
736 PP.getSelectorTable(),
737 PP.getBuiltinInfo(),
738 /* size_reserve = */0,
739 /*DelayInitialization=*/true);
740 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000741
Douglas Gregor8835e032011-09-02 00:26:20 +0000742 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000743
744 // Recover resources if we crash before exiting this method.
745 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
746 ReaderCleanup(Reader.get());
747
Douglas Gregore8bbc122011-09-02 00:18:52 +0000748 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor83297df2011-09-01 23:39:15 +0000749 AST->ASTFileLangOpts, HeaderInfo,
750 AST->Target, Predefines, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000751
Douglas Gregora6895d82011-07-22 16:00:58 +0000752 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000753 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000754 break;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Sebastian Redl2c499f62010-08-18 23:56:43 +0000756 case ASTReader::Failure:
757 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000758 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000759 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Daniel Dunbara8a50932009-12-02 08:44:16 +0000762 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
763
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000764 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000765 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000766
Sebastian Redl2c499f62010-08-18 23:56:43 +0000767 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000768 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000769 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000770 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000771 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000772
773 // Unregister the cleanup for ASTReader. It will get cleaned up
774 // by the ASTUnit cleanup.
775 ReaderCleanup.unregister();
776
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000777 Context.setExternalSource(Source);
778
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000779 // Create an AST consumer, even though it isn't used.
780 AST->Consumer.reset(new ASTConsumer);
781
Sebastian Redl2c499f62010-08-18 23:56:43 +0000782 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000783 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
784 AST->TheSema->Initialize();
785 ReaderPtr->InitializeSema(*AST->TheSema);
786
Mike Stump11289f42009-09-09 15:08:12 +0000787 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000788}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000789
790namespace {
791
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000792/// \brief Preprocessor callback class that updates a hash value with the names
793/// of all macros that have been defined by the translation unit.
794class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
795 unsigned &Hash;
796
797public:
798 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
799
800 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
801 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
802 }
803};
804
805/// \brief Add the given declaration to the hash of all top-level entities.
806void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
807 if (!D)
808 return;
809
810 DeclContext *DC = D->getDeclContext();
811 if (!DC)
812 return;
813
814 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
815 return;
816
817 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
818 if (ND->getIdentifier())
819 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
820 else if (DeclarationName Name = ND->getDeclName()) {
821 std::string NameStr = Name.getAsString();
822 Hash = llvm::HashString(NameStr, Hash);
823 }
824 return;
825 }
826
827 if (ObjCForwardProtocolDecl *Forward
828 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
829 for (ObjCForwardProtocolDecl::protocol_iterator
830 P = Forward->protocol_begin(),
831 PEnd = Forward->protocol_end();
832 P != PEnd; ++P)
833 AddTopLevelDeclarationToHash(*P, Hash);
834 return;
835 }
836
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000837 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000838 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000839 return;
840 }
841}
842
Daniel Dunbar644dca02009-12-04 08:17:33 +0000843class TopLevelDeclTrackerConsumer : public ASTConsumer {
844 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000845 unsigned &Hash;
846
Daniel Dunbar644dca02009-12-04 08:17:33 +0000847public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
849 : Unit(_Unit), Hash(Hash) {
850 Hash = 0;
851 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000853 void handleTopLevelDecl(Decl *D) {
854 // FIXME: Currently ObjC method declarations are incorrectly being
855 // reported as top-level declarations, even though their DeclContext
856 // is the containing ObjC @interface/@implementation. This is a
857 // fundamental problem in the parser right now.
858 if (isa<ObjCMethodDecl>(D))
859 return;
860
861 AddTopLevelDeclarationToHash(D, Hash);
862 Unit.addTopLevelDecl(D);
863
864 handleFileLevelDecl(D);
865 }
866
867 void handleFileLevelDecl(Decl *D) {
868 Unit.addFileLevelDecl(D);
869 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
870 for (NamespaceDecl::decl_iterator
871 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
872 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000873 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000874 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000875
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000876 void HandleTopLevelDecl(DeclGroupRef D) {
877 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
878 handleTopLevelDecl(*it);
879 }
880
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000881 // We're not interested in "interesting" decls.
882 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000883
884 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
885 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
886 handleTopLevelDecl(*it);
887 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000888};
889
890class TopLevelDeclTrackerAction : public ASTFrontendAction {
891public:
892 ASTUnit &Unit;
893
Daniel Dunbar764c0822009-12-01 09:51:01 +0000894 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000895 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000896 CI.getPreprocessor().addPPCallbacks(
897 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
898 return new TopLevelDeclTrackerConsumer(Unit,
899 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000900 }
901
902public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000903 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
904
Daniel Dunbar764c0822009-12-01 09:51:01 +0000905 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000906 virtual TranslationUnitKind getTranslationUnitKind() {
907 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000908 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000909};
910
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000911class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000912 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000913 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000914 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000915
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000916public:
Douglas Gregor36db4f92011-08-25 22:35:51 +0000917 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000918 StringRef isysroot, raw_ostream *Out)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000919 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000920 Hash(Unit.getCurrentTopLevelHashValue()) {
921 Hash = 0;
922 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000923
Douglas Gregore9db88f2010-08-03 19:06:41 +0000924 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000925 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
926 Decl *D = *it;
927 // FIXME: Currently ObjC method declarations are incorrectly being
928 // reported as top-level declarations, even though their DeclContext
929 // is the containing ObjC @interface/@implementation. This is a
930 // fundamental problem in the parser right now.
931 if (isa<ObjCMethodDecl>(D))
932 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000933 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000934 TopLevelDecls.push_back(D);
935 }
936 }
937
938 virtual void HandleTranslationUnit(ASTContext &Ctx) {
939 PCHGenerator::HandleTranslationUnit(Ctx);
940 if (!Unit.getDiagnostics().hasErrorOccurred()) {
941 // Translate the top-level declarations we captured during
942 // parsing into declaration IDs in the precompiled
943 // preamble. This will allow us to deserialize those top-level
944 // declarations when requested.
945 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
946 Unit.addTopLevelDeclFromPreamble(
947 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000948 }
949 }
950};
951
952class PrecompilePreambleAction : public ASTFrontendAction {
953 ASTUnit &Unit;
954
955public:
956 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
957
958 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000959 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000960 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000961 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000962 raw_ostream *OS = 0;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000963 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
964 OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000965 OS))
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000966 return 0;
967
Douglas Gregorc567ba22011-07-22 16:35:34 +0000968 if (!CI.getFrontendOpts().RelocatablePCH)
969 Sysroot.clear();
970
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000971 CI.getPreprocessor().addPPCallbacks(
972 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor36db4f92011-08-25 22:35:51 +0000973 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
974 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000975 }
976
977 virtual bool hasCodeCompletionSupport() const { return false; }
978 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000979 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000980};
981
Daniel Dunbar764c0822009-12-01 09:51:01 +0000982}
983
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000984/// Parse the source file into a translation unit using the given compiler
985/// invocation, replacing the current translation unit.
986///
987/// \returns True if a failure occurred that causes the ASTUnit not to
988/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000989bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000990 delete SavedMainFileBuffer;
991 SavedMainFileBuffer = 0;
992
Ted Kremenek5e14d392011-03-21 18:40:17 +0000993 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000994 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000995 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000996 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000997
Daniel Dunbar764c0822009-12-01 09:51:01 +0000998 // Create the compiler instance to use for building the AST.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000999 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1000
1001 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001002 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1003 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001004
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001005 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1006 CCInvocation(new CompilerInvocation(*Invocation));
1007
1008 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001009 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001010
Douglas Gregor8e984da2010-08-04 16:47:14 +00001011 // Set up diagnostics, capturing any diagnostics that would
1012 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001013 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001014
Daniel Dunbar764c0822009-12-01 09:51:01 +00001015 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001016 Clang->getTargetOpts().Features = TargetFeatures;
1017 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001018 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001019 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001020 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001021 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001022 }
1023
Daniel Dunbar764c0822009-12-01 09:51:01 +00001024 // Inform the target of the language options.
1025 //
1026 // FIXME: We shouldn't need to do this, the target should be immutable once
1027 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001028 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001029
Ted Kremenek84de4a12011-03-21 18:40:07 +00001030 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001031 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001032 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001033 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001034 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001035 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001036
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001037 // Configure the various subsystems.
1038 // FIXME: Should we retain the previous file manager?
Ted Kremenek84de4a12011-03-21 18:40:07 +00001039 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001040 FileMgr = new FileManager(FileSystemOpts);
1041 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001042 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001043 Ctx = 0;
1044 PP = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001045
1046 // Clear out old caches and data.
1047 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001048 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001049 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001050
Douglas Gregor7b02b582010-08-20 00:02:33 +00001051 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001052 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregor7b02b582010-08-20 00:02:33 +00001053 TopLevelDeclsInPreamble.clear();
1054 }
1055
Daniel Dunbar764c0822009-12-01 09:51:01 +00001056 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001057 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001058
Daniel Dunbar764c0822009-12-01 09:51:01 +00001059 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001060 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001061
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001062 // If the main file has been overridden due to the use of a preamble,
1063 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001064 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthde81fc82011-07-14 09:02:10 +00001065 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1066 = NestedMacroExpansions;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001067 if (OverrideMainBuffer) {
1068 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1069 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1070 PreprocessorOpts.PrecompiledPreambleBytes.second
1071 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001072 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001073 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001074
Douglas Gregord9a30af2010-08-02 20:51:39 +00001075 // The stored diagnostic has the old source manager in it; update
1076 // the locations to refer into the new source manager. Since we've
1077 // been careful to make sure that the source manager's state
1078 // before and after are identical, so that we can reuse the source
1079 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001080 for (unsigned I = NumStoredDiagnosticsFromDriver,
1081 N = StoredDiagnostics.size();
1082 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001083 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1084 getSourceManager());
1085 StoredDiagnostics[I].setLocation(Loc);
1086 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001087
1088 // Keep track of the override buffer;
1089 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001090 }
1091
Ted Kremenek022a4902011-03-22 01:15:24 +00001092 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1093 new TopLevelDeclTrackerAction(*this));
1094
1095 // Recover resources if we crash before exiting this method.
1096 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1097 ActCleanup(Act.get());
1098
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1100 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001101 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001102
1103 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001104 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001105 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1106 getSourceManager(), PreambleDiagnostics,
1107 StoredDiagnostics);
1108 }
1109
Daniel Dunbar644dca02009-12-04 08:17:33 +00001110 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001111
Ted Kremenek5e14d392011-03-21 18:40:17 +00001112 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001113 TheSema.reset(Clang->takeSema());
1114 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +00001115 Ctx = &Clang->getASTContext();
1116 PP = &Clang->getPreprocessor();
1117 Clang->setSourceManager(0);
1118 Clang->setFileManager(0);
1119 Target = &Clang->getTarget();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001120
Daniel Dunbar644dca02009-12-04 08:17:33 +00001121 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001122
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001123 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001124
Daniel Dunbar764c0822009-12-01 09:51:01 +00001125error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001126 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001127 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001128 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001129 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001130 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001131
Douglas Gregorefc46952010-10-12 16:25:54 +00001132 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001133 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001134 return true;
1135}
1136
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001137/// \brief Simple function to retrieve a path for a preamble precompiled header.
1138static std::string GetPreamblePCHPath() {
1139 // FIXME: This is lame; sys::Path should provide this function (in particular,
1140 // it should know how to find the temporary files dir).
1141 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001142 // FIXME: This is a hack so that we can override the preamble file during
1143 // crash-recovery testing, which is the only case where the preamble files
1144 // are not necessarily cleaned up.
1145 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1146 if (TmpFile)
1147 return TmpFile;
1148
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001149 std::string Error;
1150 const char *TmpDir = ::getenv("TMPDIR");
1151 if (!TmpDir)
1152 TmpDir = ::getenv("TEMP");
1153 if (!TmpDir)
1154 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001155#ifdef LLVM_ON_WIN32
1156 if (!TmpDir)
1157 TmpDir = ::getenv("USERPROFILE");
1158#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001159 if (!TmpDir)
1160 TmpDir = "/tmp";
1161 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001162 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001163 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001164 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001165 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001166 return std::string();
1167
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001168 return P.str();
1169}
1170
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001171/// \brief Compute the preamble for the main file, providing the source buffer
1172/// that corresponds to the main file along with a pair (bytes, start-of-line)
1173/// that describes the preamble.
1174std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001175ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1176 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001177 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001178 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001179 CreatedBuffer = false;
1180
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001181 // Try to determine if the main file has been remapped, either from the
1182 // command line (to another file) or directly through the compiler invocation
1183 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001184 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001185 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1186 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1187 // Check whether there is a file-file remapping of the main file
1188 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001189 M = PreprocessorOpts.remapped_file_begin(),
1190 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191 M != E;
1192 ++M) {
1193 llvm::sys::PathWithStatus MPath(M->first);
1194 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1195 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1196 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001197 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001198 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001199 CreatedBuffer = false;
1200 }
1201
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001202 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001203 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001204 return std::make_pair((llvm::MemoryBuffer*)0,
1205 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001206 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207 }
1208 }
1209 }
1210
1211 // Check whether there is a file-buffer remapping. It supercedes the
1212 // file-file remapping.
1213 for (PreprocessorOptions::remapped_file_buffer_iterator
1214 M = PreprocessorOpts.remapped_file_buffer_begin(),
1215 E = PreprocessorOpts.remapped_file_buffer_end();
1216 M != E;
1217 ++M) {
1218 llvm::sys::PathWithStatus MPath(M->first);
1219 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1220 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1221 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001222 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001223 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001224 CreatedBuffer = false;
1225 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001226
Douglas Gregor4dde7492010-07-23 23:58:40 +00001227 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001228 }
1229 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001230 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001231 }
1232
1233 // If the main source file was not remapped, load it now.
1234 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001235 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001237 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001238
1239 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001240 }
1241
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001242 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1243 Invocation.getLangOpts(),
1244 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001245}
1246
Douglas Gregor6481ef12010-07-24 00:38:13 +00001247static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001248 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001249 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001250 llvm::MemoryBuffer *Result
1251 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1252 memcpy(const_cast<char*>(Result->getBufferStart()),
1253 Old->getBufferStart(), Old->getBufferSize());
1254 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001255 ' ', NewSize - Old->getBufferSize() - 1);
1256 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001257
Douglas Gregor6481ef12010-07-24 00:38:13 +00001258 return Result;
1259}
1260
Douglas Gregor4dde7492010-07-23 23:58:40 +00001261/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1262/// the source file.
1263///
1264/// This routine will compute the preamble of the main source file. If a
1265/// non-trivial preamble is found, it will precompile that preamble into a
1266/// precompiled header so that the precompiled preamble can be used to reduce
1267/// reparsing time. If a precompiled preamble has already been constructed,
1268/// this routine will determine if it is still valid and, if so, avoid
1269/// rebuilding the precompiled preamble.
1270///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001271/// \param AllowRebuild When true (the default), this routine is
1272/// allowed to rebuild the precompiled preamble if it is found to be
1273/// out-of-date.
1274///
1275/// \param MaxLines When non-zero, the maximum number of lines that
1276/// can occur within the preamble.
1277///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001278/// \returns If the precompiled preamble can be used, returns a newly-allocated
1279/// buffer that should be used in place of the main file when doing so.
1280/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001281llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001282 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001283 bool AllowRebuild,
1284 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001285
1286 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1287 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1288 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001289 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001290 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001291
1292 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001293 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001294 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001295
Douglas Gregor925296b2011-07-19 16:10:42 +00001296 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor3edb1672010-11-16 20:45:51 +00001297 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1298 if (CreatedPreambleBuffer)
1299 OwnedPreambleBuffer.reset(NewPreamble.first);
1300
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001301 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001302 // We couldn't find a preamble in the main source. Clear out the current
1303 // preamble, if we have one. It's obviously no good any more.
1304 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001305 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001306
1307 // The next time we actually see a preamble, precompile it.
1308 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001309 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001310 }
1311
1312 if (!Preamble.empty()) {
1313 // We've previously computed a preamble. Check whether we have the same
1314 // preamble now that we did before, and that there's enough space in
1315 // the main-file buffer within the precompiled preamble to fit the
1316 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001317 if (Preamble.size() == NewPreamble.second.first &&
1318 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001319 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001320 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001321 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322 // The preamble has not changed. We may be able to re-use the precompiled
1323 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001324
Douglas Gregor0e119552010-07-31 00:40:00 +00001325 // Check that none of the files used by the preamble have changed.
1326 bool AnyFileChanged = false;
1327
1328 // First, make a record of those files that have been overridden via
1329 // remapping or unsaved_files.
1330 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1331 for (PreprocessorOptions::remapped_file_iterator
1332 R = PreprocessorOpts.remapped_file_begin(),
1333 REnd = PreprocessorOpts.remapped_file_end();
1334 !AnyFileChanged && R != REnd;
1335 ++R) {
1336 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001337 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001338 // If we can't stat the file we're remapping to, assume that something
1339 // horrible happened.
1340 AnyFileChanged = true;
1341 break;
1342 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001343
Douglas Gregor0e119552010-07-31 00:40:00 +00001344 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1345 StatBuf.st_mtime);
1346 }
1347 for (PreprocessorOptions::remapped_file_buffer_iterator
1348 R = PreprocessorOpts.remapped_file_buffer_begin(),
1349 REnd = PreprocessorOpts.remapped_file_buffer_end();
1350 !AnyFileChanged && R != REnd;
1351 ++R) {
1352 // FIXME: Should we actually compare the contents of file->buffer
1353 // remappings?
1354 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1355 0);
1356 }
1357
1358 // Check whether anything has changed.
1359 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1360 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1361 !AnyFileChanged && F != FEnd;
1362 ++F) {
1363 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1364 = OverriddenFiles.find(F->first());
1365 if (Overridden != OverriddenFiles.end()) {
1366 // This file was remapped; check whether the newly-mapped file
1367 // matches up with the previous mapping.
1368 if (Overridden->second != F->second)
1369 AnyFileChanged = true;
1370 continue;
1371 }
1372
1373 // The file was not remapped; check whether it has changed on disk.
1374 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001375 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001376 // If we can't stat the file, assume that something horrible happened.
1377 AnyFileChanged = true;
1378 } else if (StatBuf.st_size != F->second.first ||
1379 StatBuf.st_mtime != F->second.second)
1380 AnyFileChanged = true;
1381 }
1382
1383 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001384 // Okay! We can re-use the precompiled preamble.
1385
1386 // Set the state of the diagnostic object to mimic its state
1387 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001388 // FIXME: This won't catch any #pragma push warning changes that
1389 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001390 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001391 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001392 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001393 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001394
1395 // Create a version of the main file buffer that is padded to
1396 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001397 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001398 PreambleReservedSize,
1399 FrontendOpts.Inputs[0].second);
1400 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001401 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001402
1403 // If we aren't allowed to rebuild the precompiled preamble, just
1404 // return now.
1405 if (!AllowRebuild)
1406 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001407
Douglas Gregor4dde7492010-07-23 23:58:40 +00001408 // We can't reuse the previously-computed preamble. Build a new one.
1409 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001410 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001411 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001412 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001413 } else if (!AllowRebuild) {
1414 // We aren't allowed to rebuild the precompiled preamble; just
1415 // return now.
1416 return 0;
1417 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001418
1419 // If the preamble rebuild counter > 1, it's because we previously
1420 // failed to build a preamble and we're not yet ready to try
1421 // again. Decrement the counter and return a failure.
1422 if (PreambleRebuildCounter > 1) {
1423 --PreambleRebuildCounter;
1424 return 0;
1425 }
1426
Douglas Gregore10f0e52010-09-11 17:56:52 +00001427 // Create a temporary file for the precompiled preamble. In rare
1428 // circumstances, this can fail.
1429 std::string PreamblePCHPath = GetPreamblePCHPath();
1430 if (PreamblePCHPath.empty()) {
1431 // Try again next time.
1432 PreambleRebuildCounter = 1;
1433 return 0;
1434 }
1435
Douglas Gregor4dde7492010-07-23 23:58:40 +00001436 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001437 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001438 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001439
1440 // Create a new buffer that stores the preamble. The buffer also contains
1441 // extra space for the original contents of the file (which will be present
1442 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001443 // grows.
1444 PreambleReservedSize = NewPreamble.first->getBufferSize();
1445 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001446 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001447 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001448 PreambleReservedSize *= 2;
1449
Douglas Gregord9a30af2010-08-02 20:51:39 +00001450 // Save the preamble text for later; we'll need to compare against it for
1451 // subsequent reparses.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001452 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1453 Preamble.assign(FileMgr->getFile(MainFilename),
1454 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001455 NewPreamble.first->getBufferStart()
1456 + NewPreamble.second.first);
1457 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1458
Douglas Gregora0734c52010-08-19 01:33:06 +00001459 delete PreambleBuffer;
1460 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001461 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001462 FrontendOpts.Inputs[0].second);
1463 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001464 NewPreamble.first->getBufferStart(), Preamble.size());
1465 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001466 ' ', PreambleReservedSize - Preamble.size() - 1);
1467 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001468
1469 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001470 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001471 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1472
1473 // Tell the compiler invocation to generate a temporary precompiled header.
1474 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001475 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001476 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001477 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1478 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001479
1480 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001481 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1482
1483 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001484 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1485 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001486
Douglas Gregor3cc15812011-07-01 18:22:13 +00001487 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00001488 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001489
Douglas Gregor8e984da2010-08-04 16:47:14 +00001490 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001491 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001492
1493 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001494 Clang->getTargetOpts().Features = TargetFeatures;
1495 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1496 Clang->getTargetOpts()));
1497 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001498 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1499 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001500 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001501 PreprocessorOpts.eraseRemappedFile(
1502 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001503 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001504 }
1505
1506 // Inform the target of the language options.
1507 //
1508 // FIXME: We shouldn't need to do this, the target should be immutable once
1509 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001510 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001511
Ted Kremenek84de4a12011-03-21 18:40:07 +00001512 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001513 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001514 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001515 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001516 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001517 "IR inputs not support here!");
1518
1519 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001520 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001521 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001522 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001523 TopLevelDecls.clear();
1524 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001525
1526 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001527 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001528
1529 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001530 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001531 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001532
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001533 llvm::OwningPtr<PrecompilePreambleAction> Act;
1534 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001535 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1536 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001537 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1538 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001539 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001540 PreprocessorOpts.eraseRemappedFile(
1541 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001542 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001543 }
1544
1545 Act->Execute();
1546 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001547
Douglas Gregore9db88f2010-08-03 19:06:41 +00001548 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001549 // There were errors parsing the preamble, so no precompiled header was
1550 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001551 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001552 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1553 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001554 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001555 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001556 PreprocessorOpts.eraseRemappedFile(
1557 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001558 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001559 }
1560
Douglas Gregor925296b2011-07-19 16:10:42 +00001561 // Transfer any diagnostics generated when parsing the preamble into the set
1562 // of preamble diagnostics.
1563 PreambleDiagnostics.clear();
1564 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001565 stored_diag_afterDriver_begin(), stored_diag_end());
1566 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregor925296b2011-07-19 16:10:42 +00001567
Douglas Gregor4dde7492010-07-23 23:58:40 +00001568 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001569 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001570 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001571
1572 // Keep track of all of the files that the source manager knows about,
1573 // so we can verify whether they have changed or not.
1574 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001575 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001576 const llvm::MemoryBuffer *MainFileBuffer
1577 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1578 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1579 FEnd = SourceMgr.fileinfo_end();
1580 F != FEnd;
1581 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001582 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001583 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1584 continue;
1585
1586 FilesInPreamble[File->getName()]
1587 = std::make_pair(F->second->getSize(), File->getModificationTime());
1588 }
1589
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001590 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001591 PreprocessorOpts.eraseRemappedFile(
1592 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001593
1594 // If the hash of top-level entities differs from the hash of the top-level
1595 // entities the last time we rebuilt the preamble, clear out the completion
1596 // cache.
1597 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1598 CompletionCacheTopLevelHashValue = 0;
1599 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1600 }
1601
Douglas Gregor6481ef12010-07-24 00:38:13 +00001602 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001603 PreambleReservedSize,
1604 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001605}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001606
Douglas Gregore9db88f2010-08-03 19:06:41 +00001607void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1608 std::vector<Decl *> Resolved;
1609 Resolved.reserve(TopLevelDeclsInPreamble.size());
1610 ExternalASTSource &Source = *getASTContext().getExternalSource();
1611 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1612 // Resolve the declaration ID to an actual declaration, possibly
1613 // deserializing the declaration in the process.
1614 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1615 if (D)
1616 Resolved.push_back(D);
1617 }
1618 TopLevelDeclsInPreamble.clear();
1619 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1620}
1621
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001622StringRef ASTUnit::getMainFileName() const {
Douglas Gregor16896c42010-10-28 15:44:59 +00001623 return Invocation->getFrontendOpts().Inputs[0].second;
1624}
1625
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001626ASTUnit *ASTUnit::create(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001627 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001628 llvm::OwningPtr<ASTUnit> AST;
1629 AST.reset(new ASTUnit(false));
1630 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1631 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001632 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001633 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001634 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001635 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001636
1637 return AST.take();
1638}
1639
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001640ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001641 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001642 ASTFrontendAction *Action,
1643 ASTUnit *Unit) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001644 assert(CI && "A CompilerInvocation is required");
1645
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001646 llvm::OwningPtr<ASTUnit> OwnAST;
1647 ASTUnit *AST = Unit;
1648 if (!AST) {
1649 // Create the AST unit.
1650 OwnAST.reset(create(CI, Diags));
1651 AST = OwnAST.get();
1652 }
1653
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001654 AST->OnlyLocalDecls = false;
1655 AST->CaptureDiagnostics = false;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001656 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001657 AST->ShouldCacheCodeCompletionResults = false;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001658
1659 // Recover resources if we crash before exiting this method.
1660 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001661 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001662 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1663 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001664 DiagCleanup(Diags.getPtr());
1665
1666 // We'll manage file buffers ourselves.
1667 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1668 CI->getFrontendOpts().DisableFree = false;
1669 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1670
1671 // Save the target features.
1672 AST->TargetFeatures = CI->getTargetOpts().Features;
1673
1674 // Create the compiler instance to use for building the AST.
1675 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1676
1677 // Recover resources if we crash before exiting this method.
1678 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1679 CICleanup(Clang.get());
1680
1681 Clang->setInvocation(CI);
1682 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1683
1684 // Set up diagnostics, capturing any diagnostics that would
1685 // otherwise be dropped.
1686 Clang->setDiagnostics(&AST->getDiagnostics());
1687
1688 // Create the target instance.
1689 Clang->getTargetOpts().Features = AST->TargetFeatures;
1690 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1691 Clang->getTargetOpts()));
1692 if (!Clang->hasTarget())
1693 return 0;
1694
1695 // Inform the target of the language options.
1696 //
1697 // FIXME: We shouldn't need to do this, the target should be immutable once
1698 // created. This complexity should be lifted elsewhere.
1699 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1700
1701 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1702 "Invocation must have exactly one source file!");
1703 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1704 "FIXME: AST inputs not yet supported here!");
1705 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1706 "IR inputs not supported here!");
1707
1708 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001709 AST->TheSema.reset();
1710 AST->Ctx = 0;
1711 AST->PP = 0;
1712
1713 // Create a file manager object to provide access to and cache the filesystem.
1714 Clang->setFileManager(&AST->getFileManager());
1715
1716 // Create the source manager.
1717 Clang->setSourceManager(&AST->getSourceManager());
1718
1719 ASTFrontendAction *Act = Action;
1720
1721 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1722 if (!Act) {
1723 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1724 Act = TrackerAct.get();
1725 }
1726
1727 // Recover resources if we crash before exiting this method.
1728 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1729 ActCleanup(TrackerAct.get());
1730
1731 if (!Act->BeginSourceFile(*Clang.get(),
1732 Clang->getFrontendOpts().Inputs[0].second,
1733 Clang->getFrontendOpts().Inputs[0].first))
1734 return 0;
1735
1736 Act->Execute();
1737
1738 // Steal the created target, context, and preprocessor.
1739 AST->TheSema.reset(Clang->takeSema());
1740 AST->Consumer.reset(Clang->takeASTConsumer());
1741 AST->Ctx = &Clang->getASTContext();
1742 AST->PP = &Clang->getPreprocessor();
1743 Clang->setSourceManager(0);
1744 Clang->setFileManager(0);
1745 AST->Target = &Clang->getTarget();
1746
1747 Act->EndSourceFile();
1748
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001749 if (OwnAST)
1750 return OwnAST.take();
1751 else
1752 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001753}
1754
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001755bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1756 if (!Invocation)
1757 return true;
1758
1759 // We'll manage file buffers ourselves.
1760 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1761 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001762 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001763
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001764 // Save the target features.
1765 TargetFeatures = Invocation->getTargetOpts().Features;
1766
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001767 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001768 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001769 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001770 OverrideMainBuffer
1771 = getMainBufferWithPrecompiledPreamble(*Invocation);
1772 }
1773
Douglas Gregor16896c42010-10-28 15:44:59 +00001774 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001775 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001776
Ted Kremenek022a4902011-03-22 01:15:24 +00001777 // Recover resources if we crash before exiting this method.
1778 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1779 MemBufferCleanup(OverrideMainBuffer);
1780
Douglas Gregor16896c42010-10-28 15:44:59 +00001781 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001782}
1783
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001784ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001785 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001786 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001787 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001788 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001789 TranslationUnitKind TUKind,
Douglas Gregor998caea2011-05-06 16:33:08 +00001790 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001791 bool NestedMacroExpansions) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001792 // Create the AST unit.
1793 llvm::OwningPtr<ASTUnit> AST;
1794 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001795 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001796 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001797 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001798 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001799 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001800 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001801 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001802 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001803
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001804 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001805 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1806 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001807 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1808 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001809 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001810
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001811 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001812}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001813
1814ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1815 const char **ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00001816 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001817 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001818 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001819 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001820 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001821 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001822 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001823 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001824 TranslationUnitKind TUKind,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001825 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001826 bool NestedMacroExpansions) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001827 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001828 // No diagnostics engine was provided, so create our own diagnostics object
1829 // with the default options.
1830 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001831 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1832 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001833 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001834
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001835 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001836
Ted Kremenek5e14d392011-03-21 18:40:17 +00001837 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001838
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001839 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001840
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001841 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001842 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001843
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001844 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001845 llvm::makeArrayRef(ArgBegin, ArgEnd),
1846 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001847 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001848 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001849 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001850
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001851 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001852 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1853 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1854 if (const llvm::MemoryBuffer *
1855 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1856 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1857 } else {
1858 const char *fname = fileOrBuf.get<const char *>();
1859 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1860 }
1861 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001862 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1863 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001864
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001865 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001866 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001867
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001868 // Create the AST unit.
1869 llvm::OwningPtr<ASTUnit> AST;
1870 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001871 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001872 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001873
1874 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001875 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001876 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001877 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001878 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001879 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1880 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001881 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001882 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001883 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001884
1885 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001886 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1887 ASTUnitCleanup(AST.get());
1888 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1889 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1890 CICleanup(CI.getPtr());
David Blaikie9c902b52011-09-25 23:23:43 +00001891 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1892 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001893 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001894
Chris Lattner5159f612010-11-23 08:35:12 +00001895 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001896}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001897
1898bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001899 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001900 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001901
1902 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001903
Douglas Gregor16896c42010-10-28 15:44:59 +00001904 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001905 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001906
Douglas Gregor0e119552010-07-31 00:40:00 +00001907 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001908 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001909 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001910 for (PreprocessorOptions::remapped_file_buffer_iterator
1911 R = PPOpts.remapped_file_buffer_begin(),
1912 REnd = PPOpts.remapped_file_buffer_end();
1913 R != REnd;
1914 ++R) {
1915 delete R->second;
1916 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001917 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001918 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1919 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1920 if (const llvm::MemoryBuffer *
1921 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1922 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1923 memBuf);
1924 } else {
1925 const char *fname = fileOrBuf.get<const char *>();
1926 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1927 fname);
1928 }
1929 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001930
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001931 // If we have a preamble file lying around, or if we might try to
1932 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001933 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001934 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001935 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001936
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001937 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001938 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001939 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001940 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1941 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001942
Douglas Gregor4dde7492010-07-23 23:58:40 +00001943 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001944 bool Result = Parse(OverrideMainBuffer);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001945
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001946 // We now need to clear out the completion allocator for
1947 // clang_getCursorCompletionString; it'll be recreated if necessary.
1948 CursorCompletionAllocator = 0;
1949
Douglas Gregor4dde7492010-07-23 23:58:40 +00001950 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001951}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001952
Douglas Gregorb14904c2010-08-13 22:48:40 +00001953//----------------------------------------------------------------------------//
1954// Code completion
1955//----------------------------------------------------------------------------//
1956
1957namespace {
1958 /// \brief Code completion consumer that combines the cached code-completion
1959 /// results from an ASTUnit with the code-completion results provided to it,
1960 /// then passes the result on to
1961 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00001962 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001963 ASTUnit &AST;
1964 CodeCompleteConsumer &Next;
1965
1966 public:
1967 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001968 bool IncludeMacros, bool IncludeCodePatterns,
1969 bool IncludeGlobals)
1970 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001971 Next.isOutputBinary()), AST(AST), Next(Next)
1972 {
1973 // Compute the set of contexts in which we will look when we don't have
1974 // any information about the specific context.
1975 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00001976 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1977 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1978 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1979 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1980 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1981 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1982 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1983 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1984 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1985 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1986 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1987 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1988 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001989
Douglas Gregorb14904c2010-08-13 22:48:40 +00001990 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00001991 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1992 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1993 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00001994 }
1995
1996 virtual void ProcessCodeCompleteResults(Sema &S,
1997 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001998 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001999 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002000
2001 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2002 OverloadCandidate *Candidates,
2003 unsigned NumCandidates) {
2004 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2005 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002006
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002007 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002008 return Next.getAllocator();
2009 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002010 };
2011}
Douglas Gregord46cf182010-08-16 20:01:48 +00002012
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002013/// \brief Helper function that computes which global names are hidden by the
2014/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002015static void CalculateHiddenNames(const CodeCompletionContext &Context,
2016 CodeCompletionResult *Results,
2017 unsigned NumResults,
2018 ASTContext &Ctx,
2019 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002020 bool OnlyTagNames = false;
2021 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002022 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002023 case CodeCompletionContext::CCC_TopLevel:
2024 case CodeCompletionContext::CCC_ObjCInterface:
2025 case CodeCompletionContext::CCC_ObjCImplementation:
2026 case CodeCompletionContext::CCC_ObjCIvarList:
2027 case CodeCompletionContext::CCC_ClassStructUnion:
2028 case CodeCompletionContext::CCC_Statement:
2029 case CodeCompletionContext::CCC_Expression:
2030 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002031 case CodeCompletionContext::CCC_DotMemberAccess:
2032 case CodeCompletionContext::CCC_ArrowMemberAccess:
2033 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002034 case CodeCompletionContext::CCC_Namespace:
2035 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002036 case CodeCompletionContext::CCC_Name:
2037 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002038 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002039 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002040 break;
2041
2042 case CodeCompletionContext::CCC_EnumTag:
2043 case CodeCompletionContext::CCC_UnionTag:
2044 case CodeCompletionContext::CCC_ClassOrStructTag:
2045 OnlyTagNames = true;
2046 break;
2047
2048 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002049 case CodeCompletionContext::CCC_MacroName:
2050 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002051 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002052 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002053 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002054 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002055 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002056 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002057 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002058 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2059 case CodeCompletionContext::CCC_ObjCClassMessage:
2060 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002061 // We're looking for nothing, or we're looking for names that cannot
2062 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002063 return;
2064 }
2065
John McCall276321a2010-08-25 06:19:51 +00002066 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002067 for (unsigned I = 0; I != NumResults; ++I) {
2068 if (Results[I].Kind != Result::RK_Declaration)
2069 continue;
2070
2071 unsigned IDNS
2072 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2073
2074 bool Hiding = false;
2075 if (OnlyTagNames)
2076 Hiding = (IDNS & Decl::IDNS_Tag);
2077 else {
2078 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002079 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2080 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002081 if (Ctx.getLangOptions().CPlusPlus)
2082 HiddenIDNS |= Decl::IDNS_Tag;
2083 Hiding = (IDNS & HiddenIDNS);
2084 }
2085
2086 if (!Hiding)
2087 continue;
2088
2089 DeclarationName Name = Results[I].Declaration->getDeclName();
2090 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2091 HiddenNames.insert(Identifier->getName());
2092 else
2093 HiddenNames.insert(Name.getAsString());
2094 }
2095}
2096
2097
Douglas Gregord46cf182010-08-16 20:01:48 +00002098void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2099 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002100 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002101 unsigned NumResults) {
2102 // Merge the results we were given with the results we cached.
2103 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002104 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00002105 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi203f87c2011-08-17 01:46:16 +00002106 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002107 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002108 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002109 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002110 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002111 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002112 C = AST.cached_completion_begin(),
2113 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002114 C != CEnd; ++C) {
2115 // If the context we are in matches any of the contexts we are
2116 // interested in, we'll add this result.
2117 if ((C->ShowInContexts & InContexts) == 0)
2118 continue;
2119
2120 // If we haven't added any results previously, do so now.
2121 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002122 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2123 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002124 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2125 AddedResult = true;
2126 }
2127
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002128 // Determine whether this global completion result is hidden by a local
2129 // completion result. If so, skip it.
2130 if (C->Kind != CXCursor_MacroDefinition &&
2131 HiddenNames.count(C->Completion->getTypedText()))
2132 continue;
2133
Douglas Gregord46cf182010-08-16 20:01:48 +00002134 // Adjust priority based on similar type classes.
2135 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002136 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002137 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002138 if (!Context.getPreferredType().isNull()) {
2139 if (C->Kind == CXCursor_MacroDefinition) {
2140 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002141 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00002142 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002143 } else if (C->Type) {
2144 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002145 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002146 Context.getPreferredType().getUnqualifiedType());
2147 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2148 if (ExpectedSTC == C->TypeClass) {
2149 // We know this type is similar; check for an exact match.
2150 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002151 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002152 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002153 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002154 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2155 Priority /= CCF_ExactTypeMatch;
2156 else
2157 Priority /= CCF_SimilarTypeMatch;
2158 }
2159 }
2160 }
2161
Douglas Gregor12785102010-08-24 20:21:13 +00002162 // Adjust the completion string, if required.
2163 if (C->Kind == CXCursor_MacroDefinition &&
2164 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2165 // Create a new code-completion string that just contains the
2166 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002167 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2168 C->Availability);
2169 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002170 CursorKind = CXCursor_NotImplemented;
2171 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002172 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002173 }
2174
Douglas Gregor8850aa32010-08-25 18:03:13 +00002175 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002176 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002177 }
2178
2179 // If we did not add any cached completion results, just forward the
2180 // results we were given to the next consumer.
2181 if (!AddedResult) {
2182 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2183 return;
2184 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002185
Douglas Gregord46cf182010-08-16 20:01:48 +00002186 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2187 AllResults.size());
2188}
2189
2190
2191
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002192void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002193 RemappedFile *RemappedFiles,
2194 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002195 bool IncludeMacros,
2196 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002197 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002198 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002199 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002200 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2201 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002202 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002203 return;
Argyrios Kyrtzidis1b544e32011-10-31 07:20:19 +00002204
2205 // If we're caching global code-completion results, and the top-level
2206 // declarations have changed, clear out the code-completion cache.
2207 if (ShouldCacheCodeCompletionResults &&
2208 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2209 CacheCodeCompletionResults();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002210
Douglas Gregor16896c42010-10-28 15:44:59 +00002211 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002212 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002213 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002214
Ted Kremenek5e14d392011-03-21 18:40:17 +00002215 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2216 CCInvocation(new CompilerInvocation(*Invocation));
2217
2218 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2219 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002220
Douglas Gregorb14904c2010-08-13 22:48:40 +00002221 FrontendOpts.ShowMacrosInCodeCompletion
2222 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002223 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002224 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2225 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002226 FrontendOpts.CodeCompletionAt.FileName = File;
2227 FrontendOpts.CodeCompletionAt.Line = Line;
2228 FrontendOpts.CodeCompletionAt.Column = Column;
2229
2230 // Set the language options appropriately.
Ted Kremenek5e14d392011-03-21 18:40:17 +00002231 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002232
Ted Kremenek84de4a12011-03-21 18:40:07 +00002233 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2234
2235 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002236 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2237 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002238
Ted Kremenek5e14d392011-03-21 18:40:17 +00002239 Clang->setInvocation(&*CCInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002240 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002241
2242 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002243 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002244 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002245 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002246 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002247 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002248
2249 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002250 Clang->getTargetOpts().Features = TargetFeatures;
2251 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2252 Clang->getTargetOpts()));
2253 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002254 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002255 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002256 }
2257
2258 // Inform the target of the language options.
2259 //
2260 // FIXME: We shouldn't need to do this, the target should be immutable once
2261 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002262 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002263
Ted Kremenek84de4a12011-03-21 18:40:07 +00002264 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002265 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002266 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002267 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002268 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002269 "IR inputs not support here!");
2270
2271
2272 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002273 Clang->setFileManager(&FileMgr);
2274 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002275
2276 // Remap files.
2277 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002278 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002279 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002280 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2281 if (const llvm::MemoryBuffer *
2282 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2283 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2284 OwnedBuffers.push_back(memBuf);
2285 } else {
2286 const char *fname = fileOrBuf.get<const char *>();
2287 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2288 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002289 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002290
Douglas Gregorb14904c2010-08-13 22:48:40 +00002291 // Use the code completion consumer we were given, but adding any cached
2292 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002293 AugmentedCodeCompleteConsumer *AugmentedConsumer
2294 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2295 FrontendOpts.ShowMacrosInCodeCompletion,
2296 FrontendOpts.ShowCodePatternsInCodeCompletion,
2297 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002298 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002299
Douglas Gregor028d3e42010-08-09 20:45:32 +00002300 // If we have a precompiled preamble, try to use it. We only allow
2301 // the use of the precompiled preamble if we're if the completion
2302 // point is within the main file, after the end of the precompiled
2303 // preamble.
2304 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002305 if (!getPreambleFile(this).empty()) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002306 using llvm::sys::FileStatus;
2307 llvm::sys::PathWithStatus CompleteFilePath(File);
2308 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2309 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2310 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +00002311 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2312 Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002313 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002314 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002315 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002316 }
2317
2318 // If the main file has been overridden due to the use of a preamble,
2319 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002320 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002321 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00002322 stored_diag_begin(),
2323 stored_diag_afterDriver_begin());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002324 if (OverrideMainBuffer) {
2325 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2326 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2327 PreprocessorOpts.PrecompiledPreambleBytes.second
2328 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002329 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002330 PreprocessorOpts.DisablePCHValidation = true;
2331
Douglas Gregorb97b6662010-08-20 00:59:43 +00002332 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002333 } else {
2334 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2335 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002336 }
2337
Douglas Gregor998caea2011-05-06 16:33:08 +00002338 // Disable the preprocessing record
2339 PreprocessorOpts.DetailedRecord = false;
2340
Douglas Gregor8e984da2010-08-04 16:47:14 +00002341 llvm::OwningPtr<SyntaxOnlyAction> Act;
2342 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002343 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2344 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002345 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00002346 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00002347 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2348 getSourceManager(), PreambleDiagnostics,
2349 StoredDiagnostics);
2350 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002351 Act->Execute();
2352 Act->EndSourceFile();
2353 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002354}
Douglas Gregore9386682010-08-13 05:36:37 +00002355
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002356CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor8a60bbe2011-07-06 17:40:26 +00002357 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor30c80fa2011-07-06 16:43:36 +00002358 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002359
2360 // Write to a temporary file and later rename it to the actual file, to avoid
2361 // possible race conditions.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002362 llvm::SmallString<128> TempPath;
2363 TempPath = File;
2364 TempPath += "-%%%%%%%%";
2365 int fd;
2366 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2367 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002368 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002369
Douglas Gregore9386682010-08-13 05:36:37 +00002370 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2371 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002372 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002373
2374 serialize(Out);
2375 Out.close();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002376 if (Out.has_error())
2377 return CXSaveError_Unknown;
2378
2379 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2380 bool exists;
2381 llvm::sys::fs::remove(TempPath.str(), exists);
2382 return CXSaveError_Unknown;
2383 }
2384
2385 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002386}
2387
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002388bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002389 if (getDiagnostics().hasErrorOccurred())
2390 return true;
2391
Douglas Gregore9386682010-08-13 05:36:37 +00002392 std::vector<unsigned char> Buffer;
2393 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002394 ASTWriter Writer(Stream);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002395 // FIXME: Handle modules
2396 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregore9386682010-08-13 05:36:37 +00002397
2398 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002399 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002400 OS.write((char *)&Buffer.front(), Buffer.size());
2401
2402 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002403}
Douglas Gregor925296b2011-07-19 16:10:42 +00002404
2405typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2406
2407static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2408 unsigned Raw = L.getRawEncoding();
2409 const unsigned MacroBit = 1U << 31;
2410 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2411 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2412}
2413
2414void ASTUnit::TranslateStoredDiagnostics(
2415 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002416 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002417 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002418 const SmallVectorImpl<StoredDiagnostic> &Diags,
2419 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002420 // The stored diagnostic has the old source manager in it; update
2421 // the locations to refer into the new source manager. We also need to remap
2422 // all the locations to the new view. This includes the diag location, any
2423 // associated source ranges, and the source ranges of associated fix-its.
2424 // FIXME: There should be a cleaner way to do this.
2425
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002426 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002427 Result.reserve(Diags.size());
2428 assert(MMan && "Don't have a module manager");
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00002429 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002430 assert(Mod && "Don't have preamble module");
2431 SLocRemap &Remap = Mod->SLocRemap;
2432 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2433 // Rebuild the StoredDiagnostic.
2434 const StoredDiagnostic &SD = Diags[I];
2435 SourceLocation L = SD.getLocation();
2436 TranslateSLoc(L, Remap);
2437 FullSourceLoc Loc(L, SrcMgr);
2438
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002439 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002440 Ranges.reserve(SD.range_size());
2441 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2442 E = SD.range_end();
2443 I != E; ++I) {
2444 SourceLocation BL = I->getBegin();
2445 TranslateSLoc(BL, Remap);
2446 SourceLocation EL = I->getEnd();
2447 TranslateSLoc(EL, Remap);
2448 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2449 }
2450
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002451 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002452 FixIts.reserve(SD.fixit_size());
2453 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2454 E = SD.fixit_end();
2455 I != E; ++I) {
2456 FixIts.push_back(FixItHint());
2457 FixItHint &FH = FixIts.back();
2458 FH.CodeToInsert = I->CodeToInsert;
2459 SourceLocation BL = I->RemoveRange.getBegin();
2460 TranslateSLoc(BL, Remap);
2461 SourceLocation EL = I->RemoveRange.getEnd();
2462 TranslateSLoc(EL, Remap);
2463 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2464 I->RemoveRange.isTokenRange());
2465 }
2466
2467 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2468 SD.getMessage(), Loc, Ranges, FixIts));
2469 }
2470 Result.swap(Out);
2471}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002472
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002473static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2474 std::pair<unsigned, Decl *> R) {
2475 return L.first < R.first;
2476}
2477
2478void ASTUnit::addFileLevelDecl(Decl *D) {
2479 assert(D);
2480 assert(!D->isFromASTFile() && "This is only for local decl");
2481
2482 SourceManager &SM = *SourceMgr;
2483 SourceLocation Loc = D->getLocation();
2484 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2485 return;
2486
2487 // We only keep track of the file-level declarations of each file.
2488 if (!D->getLexicalDeclContext()->isFileContext())
2489 return;
2490
2491 SourceLocation FileLoc = SM.getFileLoc(Loc);
2492 assert(SM.isLocalSourceLocation(FileLoc));
2493 FileID FID;
2494 unsigned Offset;
2495 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2496 if (FID.isInvalid())
2497 return;
2498
2499 LocDeclsTy *&Decls = FileDecls[FID];
2500 if (!Decls)
2501 Decls = new LocDeclsTy();
2502
2503 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2504
2505 if (Decls->empty() || Decls->back().first <= Offset) {
2506 Decls->push_back(LocDecl);
2507 return;
2508 }
2509
2510 LocDeclsTy::iterator
2511 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2512
2513 Decls->insert(I, LocDecl);
2514}
2515
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002516SourceLocation ASTUnit::getLocation(const FileEntry *File,
2517 unsigned Line, unsigned Col) const {
2518 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002519 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002520 return SM.getMacroArgExpandedLocation(Loc);
2521}
2522
2523SourceLocation ASTUnit::getLocation(const FileEntry *File,
2524 unsigned Offset) const {
2525 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002526 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002527 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2528}
2529
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002530/// \brief If \arg Loc is a loaded location from the preamble, returns
2531/// the corresponding local location of the main file, otherwise it returns
2532/// \arg Loc.
2533SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2534 FileID PreambleID;
2535 if (SourceMgr)
2536 PreambleID = SourceMgr->getPreambleFileID();
2537
2538 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2539 return Loc;
2540
2541 unsigned Offs;
2542 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2543 SourceLocation FileLoc
2544 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2545 return FileLoc.getLocWithOffset(Offs);
2546 }
2547
2548 return Loc;
2549}
2550
2551/// \brief If \arg Loc is a local location of the main file but inside the
2552/// preamble chunk, returns the corresponding loaded location from the
2553/// preamble, otherwise it returns \arg Loc.
2554SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2555 FileID PreambleID;
2556 if (SourceMgr)
2557 PreambleID = SourceMgr->getPreambleFileID();
2558
2559 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2560 return Loc;
2561
2562 unsigned Offs;
2563 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2564 Offs < Preamble.size()) {
2565 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2566 return FileLoc.getLocWithOffset(Offs);
2567 }
2568
2569 return Loc;
2570}
2571
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002572bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2573 FileID FID;
2574 if (SourceMgr)
2575 FID = SourceMgr->getPreambleFileID();
2576
2577 if (Loc.isInvalid() || FID.isInvalid())
2578 return false;
2579
2580 return SourceMgr->isInFileID(Loc, FID);
2581}
2582
2583bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2584 FileID FID;
2585 if (SourceMgr)
2586 FID = SourceMgr->getMainFileID();
2587
2588 if (Loc.isInvalid() || FID.isInvalid())
2589 return false;
2590
2591 return SourceMgr->isInFileID(Loc, FID);
2592}
2593
2594SourceLocation ASTUnit::getEndOfPreambleFileID() {
2595 FileID FID;
2596 if (SourceMgr)
2597 FID = SourceMgr->getPreambleFileID();
2598
2599 if (FID.isInvalid())
2600 return SourceLocation();
2601
2602 return SourceMgr->getLocForEndOfFile(FID);
2603}
2604
2605SourceLocation ASTUnit::getStartOfMainFileID() {
2606 FileID FID;
2607 if (SourceMgr)
2608 FID = SourceMgr->getMainFileID();
2609
2610 if (FID.isInvalid())
2611 return SourceLocation();
2612
2613 return SourceMgr->getLocForStartOfFile(FID);
2614}
2615
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002616void ASTUnit::PreambleData::countLines() const {
2617 NumLines = 0;
2618 if (empty())
2619 return;
2620
2621 for (std::vector<char>::const_iterator
2622 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2623 if (*I == '\n')
2624 ++NumLines;
2625 }
2626 if (Buffer.back() != '\n')
2627 ++NumLines;
2628}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002629
2630#ifndef NDEBUG
2631ASTUnit::ConcurrencyState::ConcurrencyState() {
2632 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2633}
2634
2635ASTUnit::ConcurrencyState::~ConcurrencyState() {
2636 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2637}
2638
2639void ASTUnit::ConcurrencyState::start() {
2640 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2641 assert(acquired && "Concurrent access to ASTUnit!");
2642}
2643
2644void ASTUnit::ConcurrencyState::finish() {
2645 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2646}
2647
2648#else // NDEBUG
2649
2650ASTUnit::ConcurrencyState::ConcurrencyState() {}
2651ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2652void ASTUnit::ConcurrencyState::start() {}
2653void ASTUnit::ConcurrencyState::finish() {}
2654
2655#endif