blob: e602d30374b2fc57e29f5862cb64822d6485ef6a [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000033#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000036#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000042#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000045#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000046#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000048#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000049using namespace clang;
50
Douglas Gregor213f18b2010-10-28 15:44:59 +000051using llvm::TimeRecord;
52
53namespace {
54 class SimpleTimer {
55 bool WantTiming;
56 TimeRecord Start;
57 std::string Output;
58
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000059 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000060 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 }
64
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000067 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 }
69
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 ~SimpleTimer() {
71 if (WantTiming) {
72 TimeRecord Elapsed = TimeRecord::getCurrentTime();
73 Elapsed -= Start;
74 llvm::errs() << Output << ':';
75 Elapsed.print(Elapsed, llvm::errs());
76 llvm::errs() << '\n';
77 }
78 }
79 };
Ted Kremenek1872b312011-10-27 17:55:18 +000080
81 struct OnDiskData {
82 /// \brief The file in which the precompiled preamble is stored.
83 std::string PreambleFile;
84
85 /// \brief Temporary files that should be removed when the ASTUnit is
86 /// destroyed.
87 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
88
89 /// \brief Erase temporary files.
90 void CleanTemporaryFiles();
91
92 /// \brief Erase the preamble file.
93 void CleanPreambleFile();
94
95 /// \brief Erase temporary files and the preamble file.
96 void Cleanup();
97 };
98}
99
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000100static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
101 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
102 return M;
103}
104
Ted Kremenek1872b312011-10-27 17:55:18 +0000105static void cleanupOnDiskMapAtExit(void);
106
107typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
108static OnDiskDataMap &getOnDiskDataMap() {
109 static OnDiskDataMap M;
110 static bool hasRegisteredAtExit = false;
111 if (!hasRegisteredAtExit) {
112 hasRegisteredAtExit = true;
113 atexit(cleanupOnDiskMapAtExit);
114 }
115 return M;
116}
117
118static void cleanupOnDiskMapAtExit(void) {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000119 // Use the mutex because there can be an alive thread destroying an ASTUnit.
120 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000121 OnDiskDataMap &M = getOnDiskDataMap();
122 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
123 // We don't worry about freeing the memory associated with OnDiskDataMap.
124 // All we care about is erasing stale files.
125 I->second->Cleanup();
126 }
127}
128
129static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000130 // We require the mutex since we are modifying the structure of the
131 // DenseMap.
132 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000133 OnDiskDataMap &M = getOnDiskDataMap();
134 OnDiskData *&D = M[AU];
135 if (!D)
136 D = new OnDiskData();
137 return *D;
138}
139
140static void erasePreambleFile(const ASTUnit *AU) {
141 getOnDiskData(AU).CleanPreambleFile();
142}
143
144static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000145 // We require the mutex since we are modifying the structure of the
146 // DenseMap.
147 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000148 OnDiskDataMap &M = getOnDiskDataMap();
149 OnDiskDataMap::iterator I = M.find(AU);
150 if (I != M.end()) {
151 I->second->Cleanup();
152 delete I->second;
153 M.erase(AU);
154 }
155}
156
157static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
158 getOnDiskData(AU).PreambleFile = preambleFile;
159}
160
161static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
163}
164
165void OnDiskData::CleanTemporaryFiles() {
166 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
167 TemporaryFiles[I].eraseFromDisk();
168 TemporaryFiles.clear();
169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
173 llvm::sys::Path(PreambleFile).eraseFromDisk();
174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000183struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
186 ASTWriter Writer;
187
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
189};
190
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000191void ASTUnit::clearFileLevelDecls() {
192 for (FileDeclsTy::iterator
193 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
194 delete I->second;
195 FileDecls.clear();
196}
197
Ted Kremenek1872b312011-10-27 17:55:18 +0000198void ASTUnit::CleanTemporaryFiles() {
199 getOnDiskData(this).CleanTemporaryFiles();
200}
201
202void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
203 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000204}
205
Douglas Gregoreababfb2010-08-04 05:53:38 +0000206/// \brief After failing to build a precompiled preamble (due to
207/// errors in the source that occurs in the preamble), the number of
208/// reparses during which we'll skip even trying to precompile the
209/// preamble.
210const unsigned DefaultPreambleRebuildInterval = 5;
211
Douglas Gregore3c60a72010-11-17 00:13:31 +0000212/// \brief Tracks the number of ASTUnit objects that are currently active.
213///
214/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000215static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000216
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000217ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000218 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000224 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000232 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000233 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
234 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000235}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000236
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000237ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000238 clearFileLevelDecls();
239
Ted Kremenek1872b312011-10-27 17:55:18 +0000240 // Clean up the temporary files and the preamble file.
241 removeOnDiskEntry(this);
242
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000243 // Free the buffers associated with remapped files. We are required to
244 // perform this operation here because we explicitly request that the
245 // compiler instance *not* free these buffers for each invocation of the
246 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000247 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000248 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
249 for (PreprocessorOptions::remapped_file_buffer_iterator
250 FB = PPOpts.remapped_file_buffer_begin(),
251 FBEnd = PPOpts.remapped_file_buffer_end();
252 FB != FBEnd;
253 ++FB)
254 delete FB->second;
255 }
Douglas Gregor28233422010-07-27 14:52:07 +0000256
257 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000258 delete PreambleBuffer;
259
Douglas Gregor213f18b2010-10-28 15:44:59 +0000260 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000261
262 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000263 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000264 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
265 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000266}
267
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000268void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
269
Douglas Gregor8071e422010-08-15 06:18:01 +0000270/// \brief Determine the set of code-completion contexts in which this
271/// declaration should be shown.
272static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000273 const LangOptions &LangOpts,
274 bool &IsNestedNameSpecifier) {
275 IsNestedNameSpecifier = false;
276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 if (isa<UsingShadowDecl>(ND))
278 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
279 if (!ND)
280 return 0;
281
Richard Smith026b3582012-08-14 03:13:00 +0000282 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
284 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
285 // Types can appear in these contexts.
286 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000287 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
288 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
289 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
290 | (1LL << CodeCompletionContext::CCC_Statement)
291 | (1LL << CodeCompletionContext::CCC_Type)
292 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000293
294 // In C++, types can appear in expressions contexts (for functional casts).
295 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000296 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000297
298 // In Objective-C, message sends can send interfaces. In Objective-C++,
299 // all types are available due to functional casts.
300 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000302
303 // In Objective-C, you can only be a subclass of another Objective-C class
304 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000306
307 // Deal with tag names.
308 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000310
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000311 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000314 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
315 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000316 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000317 else
Richard Smith026b3582012-08-14 03:13:00 +0000318 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000319
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000321 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000322 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000323 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000324 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
325 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000326 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
327 | (1LL << CodeCompletionContext::CCC_Expression)
328 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
329 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000332 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000333 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000334 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000335 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336
337 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000338 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000339 }
340
341 return Contexts;
342}
343
Douglas Gregor87c08a52010-08-13 22:48:40 +0000344void ASTUnit::CacheCodeCompletionResults() {
345 if (!TheSema)
346 return;
347
Douglas Gregor213f18b2010-10-28 15:44:59 +0000348 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000349 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350
351 // Clear out the previous results.
352 ClearCachedCompletionResults();
353
354 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000355 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000356 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000357 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000358 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
359 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000360
361 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000362 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
363
Douglas Gregor87c08a52010-08-13 22:48:40 +0000364 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
365 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000367 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000369 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000370 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000371 getCodeCompletionTUInfo(),
372 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000374 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000375 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000376 CachedResult.Priority = Results[I].Priority;
377 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000378 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000379
Douglas Gregorf5586f62010-08-16 18:08:11 +0000380 // Keep track of the type of this completion in an ASTContext-agnostic
381 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000382 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000383 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000384 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000385 CachedResult.Type = 0;
386 } else {
387 CanQualType CanUsageType
388 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
389 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
390
391 // Determine whether we have already seen this type. If so, we save
392 // ourselves the work of formatting the type string by using the
393 // temporary, CanQualType-based hash table to find the associated value.
394 unsigned &TypeValue = CompletionTypes[CanUsageType];
395 if (TypeValue == 0) {
396 TypeValue = CompletionTypes.size();
397 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
398 = TypeValue;
399 }
400
401 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000402 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000403
Douglas Gregor8071e422010-08-15 06:18:01 +0000404 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000405
406 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000407 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000408 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
409 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000410 uint64_t NNSContexts
411 = (1LL << CodeCompletionContext::CCC_TopLevel)
412 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
413 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
414 | (1LL << CodeCompletionContext::CCC_Statement)
415 | (1LL << CodeCompletionContext::CCC_Expression)
416 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
417 | (1LL << CodeCompletionContext::CCC_EnumTag)
418 | (1LL << CodeCompletionContext::CCC_UnionTag)
419 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
420 | (1LL << CodeCompletionContext::CCC_Type)
421 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
422 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000423
424 if (isa<NamespaceDecl>(Results[I].Declaration) ||
425 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000426 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000427
428 if (unsigned RemainingContexts
429 = NNSContexts & ~CachedResult.ShowInContexts) {
430 // If there any contexts where this completion can be a
431 // nested-name-specifier but isn't already an option, create a
432 // nested-name-specifier completion.
433 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000434 CachedResult.Completion
435 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000436 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000437 getCodeCompletionTUInfo(),
438 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000439 CachedResult.ShowInContexts = RemainingContexts;
440 CachedResult.Priority = CCP_NestedNameSpecifier;
441 CachedResult.TypeClass = STC_Void;
442 CachedResult.Type = 0;
443 CachedCompletionResults.push_back(CachedResult);
444 }
445 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000446 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000447 }
448
Douglas Gregor87c08a52010-08-13 22:48:40 +0000449 case Result::RK_Keyword:
450 case Result::RK_Pattern:
451 // Ignore keywords and patterns; we don't care, since they are so
452 // easily regenerated.
453 break;
454
455 case Result::RK_Macro: {
456 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000457 CachedResult.Completion
458 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000459 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000460 getCodeCompletionTUInfo(),
461 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000462 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000463 = (1LL << CodeCompletionContext::CCC_TopLevel)
464 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
465 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
466 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
467 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
468 | (1LL << CodeCompletionContext::CCC_Statement)
469 | (1LL << CodeCompletionContext::CCC_Expression)
470 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
471 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
472 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
473 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
474 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000475
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476 CachedResult.Priority = Results[I].Priority;
477 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000478 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000479 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000480 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481 CachedCompletionResults.push_back(CachedResult);
482 break;
483 }
484 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000486
487 // Save the current top-level hash value.
488 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000489}
490
491void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000493 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000494 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000495}
496
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497namespace {
498
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000499/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000501class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000502 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000503 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504 LangOptions &LangOpt;
505 HeaderSearch &HSI;
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000506 TargetOptions &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000507 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000508 std::string &Predefines;
509 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000515 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000516 HeaderSearch &HSI, TargetOptions &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000517 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000518 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000520 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
521 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000522 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000523 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000525 virtual bool ReadLanguageOptions(const serialization::ModuleFile &M,
526 const LangOptions &LangOpts) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000527 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000528 return false;
529
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000530 assert(M.Kind == serialization::MK_MainFile);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000531
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000532 LangOpt = LangOpts;
533 InitializedLanguage = true;
534
535 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000536 return false;
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000539 virtual bool ReadTargetTriple(const serialization::ModuleFile &M,
540 StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000541 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000542 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000543 return false;
544
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000545 assert(M.Kind == serialization::MK_MainFile);
546
Douglas Gregor998b3d32011-09-01 23:39:15 +0000547 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Douglas Gregor998b3d32011-09-01 23:39:15 +0000548 TargetOpts.ABI = "";
549 TargetOpts.CXXABI = "";
550 TargetOpts.CPU = "";
551 TargetOpts.Features.clear();
552 TargetOpts.Triple = Triple;
553 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000554
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000555 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 return false;
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000559 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000560 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000561 std::string &SuggestedPredefines,
562 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000563 Predefines = Buffers[0].Data;
564 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
565 Predefines += Buffers[I].Data;
566 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000567 return false;
568 }
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000570 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000571 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000574 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000575 Counter = Value;
576 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000577
578private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000579 void updated() {
580 if (!Target || !InitializedLanguage)
581 return;
582
583 // Inform the target of the language options.
584 //
585 // FIXME: We shouldn't need to do this, the target should be immutable once
586 // created. This complexity should be lifted elsewhere.
587 Target->setForcedLangOptions(LangOpt);
588
589 // Initialize the preprocessor.
590 PP.Initialize(*Target);
591
592 // Initialize the ASTContext
593 Context.InitBuiltinTypes(*Target);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000594 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000595};
596
David Blaikie26e7a902011-09-26 00:01:39 +0000597class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000598 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000599
600public:
David Blaikie26e7a902011-09-26 00:01:39 +0000601 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000602 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000603 : StoredDiags(StoredDiags) { }
604
David Blaikied6471f72011-09-25 23:23:43 +0000605 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000606 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000607
608 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
609 // Just drop any diagnostics that come from cloned consumers; they'll
610 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000611 // FIXME: We'd like to be able to capture these somehow, even if it's just
612 // file/line/column, because they could occur when parsing module maps or
613 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000614 return new IgnoringDiagConsumer();
615 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000616};
617
618/// \brief RAII object that optionally captures diagnostics, if
619/// there is no diagnostic client to capture them already.
620class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000621 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000622 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000623 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000624
625public:
David Blaikied6471f72011-09-25 23:23:43 +0000626 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000627 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000628 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000629 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000630 if (RequestCapture || Diags.getClient() == 0) {
631 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000632 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000633 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000634 }
635
636 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000637 if (Diags.getClient() == &Client) {
638 Diags.takeClient();
639 Diags.setClient(PreviousClient);
640 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000641 }
642};
643
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000644} // anonymous namespace
645
David Blaikie26e7a902011-09-26 00:01:39 +0000646void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000647 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000648 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000649 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000650
Douglas Gregora88084b2010-02-18 18:08:43 +0000651 StoredDiags.push_back(StoredDiagnostic(Level, Info));
652}
653
Steve Naroff77accc12009-09-03 18:19:54 +0000654const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000655 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000656}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000657
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000658ASTDeserializationListener *ASTUnit::getDeserializationListener() {
659 if (WriterData)
660 return &WriterData->Writer;
661 return 0;
662}
663
Chris Lattner5f9e2722011-07-23 10:55:15 +0000664llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000665 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000666 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000667 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000668}
669
Douglas Gregore47be3e2010-11-11 00:39:14 +0000670/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000671void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000672 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000673 ASTUnit &AST, bool CaptureDiagnostics) {
674 if (!Diags.getPtr()) {
675 // No diagnostics engine was provided, so create our own diagnostics object
676 // with the default options.
677 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000678 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000679 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000680 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000681 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
682 ArgBegin, Client,
683 /*ShouldOwnClient=*/true,
684 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000685 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000686 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000687 }
688}
689
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000690ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000691 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000692 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000693 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000694 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000695 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000696 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000697 bool AllowPCHWithCompilerErrors,
698 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000699 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000700
701 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000702 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
703 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000704 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
705 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000706 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000707
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000708 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000709
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000710 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000711 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000712 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000713 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000714 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000715 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000716 AST->getFileManager(),
717 UserFilesAreVolatile);
Douglas Gregor8e238062011-11-11 00:35:06 +0000718 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000719 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000720 AST->ASTFileLangOpts,
721 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000722
Douglas Gregor4db64a42010-01-23 00:14:00 +0000723 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000724 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
725 if (const llvm::MemoryBuffer *
726 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
727 // Create the file entry for the file that we're mapping from.
728 const FileEntry *FromFile
729 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
730 memBuf->getBufferSize(),
731 0);
732 if (!FromFile) {
733 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
734 << RemappedFiles[I].first;
735 delete memBuf;
736 continue;
737 }
738
739 // Override the contents of the "from" file with the contents of
740 // the "to" file.
741 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
742
743 } else {
744 const char *fname = fileOrBuf.get<const char *>();
745 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
746 if (!ToFile) {
747 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
748 << RemappedFiles[I].first << fname;
749 continue;
750 }
751
752 // Create the file entry for the file that we're mapping from.
753 const FileEntry *FromFile
754 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
755 ToFile->getSize(),
756 0);
757 if (!FromFile) {
758 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
759 << RemappedFiles[I].first;
760 delete memBuf;
761 continue;
762 }
763
764 // Override the contents of the "from" file with the contents of
765 // the "to" file.
766 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000767 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000768 }
769
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000770 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000772 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000773 std::string Predefines;
774 unsigned Counter;
775
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000776 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000777
Douglas Gregor998b3d32011-09-01 23:39:15 +0000778 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
779 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
780 *AST,
781 /*IILookup=*/0,
782 /*OwnsHeaderSearch=*/false,
783 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000784 Preprocessor &PP = *AST->PP;
785
786 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
787 AST->getSourceManager(),
788 /*Target=*/0,
789 PP.getIdentifierTable(),
790 PP.getSelectorTable(),
791 PP.getBuiltinInfo(),
792 /* size_reserve = */0,
793 /*DelayInitialization=*/true);
794 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000795
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000796 bool disableValid = false;
797 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
798 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000799 Reader.reset(new ASTReader(PP, Context,
800 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000801 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000802 /*DisableStatCache=*/false,
803 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000804
805 // Recover resources if we crash before exiting this method.
806 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
807 ReaderCleanup(Reader.get());
808
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000809 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000810 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000811 AST->TargetOpts, AST->Target,
812 Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000813
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000814 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000815 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000816 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000818 case ASTReader::Failure:
819 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000820 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000821 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000822 }
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000824 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
825
Daniel Dunbard5b61262009-09-21 03:03:47 +0000826 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000827 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000829 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000830 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000831 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000832 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000833 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000834
835 // Unregister the cleanup for ASTReader. It will get cleaned up
836 // by the ASTUnit cleanup.
837 ReaderCleanup.unregister();
838
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000839 Context.setExternalSource(Source);
840
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000841 // Create an AST consumer, even though it isn't used.
842 AST->Consumer.reset(new ASTConsumer);
843
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000844 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000845 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
846 AST->TheSema->Initialize();
847 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000848 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000849
Mike Stump1eb44332009-09-09 15:08:12 +0000850 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000851}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000852
853namespace {
854
Douglas Gregor9b7db622011-02-16 18:16:54 +0000855/// \brief Preprocessor callback class that updates a hash value with the names
856/// of all macros that have been defined by the translation unit.
857class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
858 unsigned &Hash;
859
860public:
861 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
862
863 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
864 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
865 }
866};
867
868/// \brief Add the given declaration to the hash of all top-level entities.
869void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
870 if (!D)
871 return;
872
873 DeclContext *DC = D->getDeclContext();
874 if (!DC)
875 return;
876
877 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
878 return;
879
880 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
881 if (ND->getIdentifier())
882 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
883 else if (DeclarationName Name = ND->getDeclName()) {
884 std::string NameStr = Name.getAsString();
885 Hash = llvm::HashString(NameStr, Hash);
886 }
887 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000888 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000889}
890
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000891class TopLevelDeclTrackerConsumer : public ASTConsumer {
892 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000893 unsigned &Hash;
894
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000895public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000896 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
897 : Unit(_Unit), Hash(Hash) {
898 Hash = 0;
899 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000900
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000901 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000902 if (!D)
903 return;
904
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000905 // FIXME: Currently ObjC method declarations are incorrectly being
906 // reported as top-level declarations, even though their DeclContext
907 // is the containing ObjC @interface/@implementation. This is a
908 // fundamental problem in the parser right now.
909 if (isa<ObjCMethodDecl>(D))
910 return;
911
912 AddTopLevelDeclarationToHash(D, Hash);
913 Unit.addTopLevelDecl(D);
914
915 handleFileLevelDecl(D);
916 }
917
918 void handleFileLevelDecl(Decl *D) {
919 Unit.addFileLevelDecl(D);
920 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
921 for (NamespaceDecl::decl_iterator
922 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
923 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000924 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000925 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000926
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000927 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000928 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
929 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000930 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000931 }
932
Sebastian Redl27372b42010-08-11 18:52:41 +0000933 // We're not interested in "interesting" decls.
934 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000935
936 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
937 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
938 handleTopLevelDecl(*it);
939 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000940
941 virtual ASTDeserializationListener *GetASTDeserializationListener() {
942 return Unit.getDeserializationListener();
943 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000944};
945
946class TopLevelDeclTrackerAction : public ASTFrontendAction {
947public:
948 ASTUnit &Unit;
949
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000950 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000951 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000952 CI.getPreprocessor().addPPCallbacks(
953 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
954 return new TopLevelDeclTrackerConsumer(Unit,
955 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000956 }
957
958public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000959 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
960
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000961 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000962 virtual TranslationUnitKind getTranslationUnitKind() {
963 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000964 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000965};
966
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000967class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000968 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000969 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000970 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000971
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000972public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000973 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000974 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000975 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000976 Hash(Unit.getCurrentTopLevelHashValue()) {
977 Hash = 0;
978 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000979
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000980 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000981 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
982 Decl *D = *it;
983 // FIXME: Currently ObjC method declarations are incorrectly being
984 // reported as top-level declarations, even though their DeclContext
985 // is the containing ObjC @interface/@implementation. This is a
986 // fundamental problem in the parser right now.
987 if (isa<ObjCMethodDecl>(D))
988 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000989 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000990 TopLevelDecls.push_back(D);
991 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000992 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000993 }
994
995 virtual void HandleTranslationUnit(ASTContext &Ctx) {
996 PCHGenerator::HandleTranslationUnit(Ctx);
997 if (!Unit.getDiagnostics().hasErrorOccurred()) {
998 // Translate the top-level declarations we captured during
999 // parsing into declaration IDs in the precompiled
1000 // preamble. This will allow us to deserialize those top-level
1001 // declarations when requested.
1002 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1003 Unit.addTopLevelDeclFromPreamble(
1004 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001005 }
1006 }
1007};
1008
1009class PrecompilePreambleAction : public ASTFrontendAction {
1010 ASTUnit &Unit;
1011
1012public:
1013 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1014
1015 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001016 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001017 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001018 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001019 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001020 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1021 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001022 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001023 return 0;
1024
Douglas Gregor832d6202011-07-22 16:35:34 +00001025 if (!CI.getFrontendOpts().RelocatablePCH)
1026 Sysroot.clear();
1027
Douglas Gregor9b7db622011-02-16 18:16:54 +00001028 CI.getPreprocessor().addPPCallbacks(
1029 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001030 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1031 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001032 }
1033
1034 virtual bool hasCodeCompletionSupport() const { return false; }
1035 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001036 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001037};
1038
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001039}
1040
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001041static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1042 StoredDiagnostics) {
1043 // Get rid of stored diagnostics except the ones from the driver which do not
1044 // have a source location.
1045 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1046 if (StoredDiagnostics[I].getLocation().isValid()) {
1047 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1048 --I;
1049 }
1050 }
1051}
1052
1053static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1054 StoredDiagnostics,
1055 SourceManager &SM) {
1056 // The stored diagnostic has the old source manager in it; update
1057 // the locations to refer into the new source manager. Since we've
1058 // been careful to make sure that the source manager's state
1059 // before and after are identical, so that we can reuse the source
1060 // location itself.
1061 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1062 if (StoredDiagnostics[I].getLocation().isValid()) {
1063 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1064 StoredDiagnostics[I].setLocation(Loc);
1065 }
1066 }
1067}
1068
Douglas Gregorabc563f2010-07-19 21:46:24 +00001069/// Parse the source file into a translation unit using the given compiler
1070/// invocation, replacing the current translation unit.
1071///
1072/// \returns True if a failure occurred that causes the ASTUnit not to
1073/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001074bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001075 delete SavedMainFileBuffer;
1076 SavedMainFileBuffer = 0;
1077
Ted Kremenek4f327862011-03-21 18:40:17 +00001078 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001079 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001080 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001081 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001083 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001084 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001085
1086 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001087 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1088 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001089
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001090 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001091 CCInvocation(new CompilerInvocation(*Invocation));
1092
1093 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001094 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001095
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001096 // Set up diagnostics, capturing any diagnostics that would
1097 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001098 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001099
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001100 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001101 Clang->getTargetOpts().Features = TargetFeatures;
1102 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001103 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001104 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001105 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001106 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001107 }
1108
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001109 // Inform the target of the language options.
1110 //
1111 // FIXME: We shouldn't need to do this, the target should be immutable once
1112 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001113 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001114
Ted Kremenek03201fb2011-03-21 18:40:07 +00001115 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001116 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001117 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001118 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001119 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001120 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001121
Douglas Gregorabc563f2010-07-19 21:46:24 +00001122 // Configure the various subsystems.
1123 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001124 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001125 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001126 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001127 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1128 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001129 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001130 Ctx = 0;
1131 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001132 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001133
1134 // Clear out old caches and data.
1135 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001136 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001137 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001138
Douglas Gregorf128fed2010-08-20 00:02:33 +00001139 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001140 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001141 TopLevelDeclsInPreamble.clear();
1142 }
1143
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001144 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001145 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001146
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001147 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001148 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001149
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001150 // If the main file has been overridden due to the use of a preamble,
1151 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001152 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001153 if (OverrideMainBuffer) {
1154 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1155 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1156 PreprocessorOpts.PrecompiledPreambleBytes.second
1157 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001158 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001159 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001160
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001161 // The stored diagnostic has the old source manager in it; update
1162 // the locations to refer into the new source manager. Since we've
1163 // been careful to make sure that the source manager's state
1164 // before and after are identical, so that we can reuse the source
1165 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001166 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001167
1168 // Keep track of the override buffer;
1169 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001170 }
1171
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001172 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001173 new TopLevelDeclTrackerAction(*this));
1174
1175 // Recover resources if we crash before exiting this method.
1176 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1177 ActCleanup(Act.get());
1178
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001179 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001180 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001181
1182 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001183 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001184 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1185 getSourceManager(), PreambleDiagnostics,
1186 StoredDiagnostics);
1187 }
1188
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001189 if (!Act->Execute())
1190 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001191
1192 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001193
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001194 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001195
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001196 FailedParseDiagnostics.clear();
1197
Douglas Gregorabc563f2010-07-19 21:46:24 +00001198 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001199
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001200error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001201 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001202 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001203 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001204 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001205 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001206
1207 // Keep the ownership of the data in the ASTUnit because the client may
1208 // want to see the diagnostics.
1209 transferASTDataFromCompilerInstance(*Clang);
1210 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001211 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001212 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001213 return true;
1214}
1215
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216/// \brief Simple function to retrieve a path for a preamble precompiled header.
1217static std::string GetPreamblePCHPath() {
1218 // FIXME: This is lame; sys::Path should provide this function (in particular,
1219 // it should know how to find the temporary files dir).
1220 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001221 // FIXME: This is a hack so that we can override the preamble file during
1222 // crash-recovery testing, which is the only case where the preamble files
1223 // are not necessarily cleaned up.
1224 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1225 if (TmpFile)
1226 return TmpFile;
1227
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 std::string Error;
1229 const char *TmpDir = ::getenv("TMPDIR");
1230 if (!TmpDir)
1231 TmpDir = ::getenv("TEMP");
1232 if (!TmpDir)
1233 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001234#ifdef LLVM_ON_WIN32
1235 if (!TmpDir)
1236 TmpDir = ::getenv("USERPROFILE");
1237#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001238 if (!TmpDir)
1239 TmpDir = "/tmp";
1240 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001241 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001242 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001243 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001244 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001245 return std::string();
1246
Douglas Gregor44c181a2010-07-23 00:33:23 +00001247 return P.str();
1248}
1249
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001250/// \brief Compute the preamble for the main file, providing the source buffer
1251/// that corresponds to the main file along with a pair (bytes, start-of-line)
1252/// that describes the preamble.
1253std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001254ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1255 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001257 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001258 CreatedBuffer = false;
1259
Douglas Gregor44c181a2010-07-23 00:33:23 +00001260 // Try to determine if the main file has been remapped, either from the
1261 // command line (to another file) or directly through the compiler invocation
1262 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001263 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001264 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001265 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1266 // Check whether there is a file-file remapping of the main file
1267 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001268 M = PreprocessorOpts.remapped_file_begin(),
1269 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001270 M != E;
1271 ++M) {
1272 llvm::sys::PathWithStatus MPath(M->first);
1273 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1274 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1275 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001277 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001278 CreatedBuffer = false;
1279 }
1280
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001281 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001282 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001283 return std::make_pair((llvm::MemoryBuffer*)0,
1284 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001285 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286 }
1287 }
1288 }
1289
1290 // Check whether there is a file-buffer remapping. It supercedes the
1291 // file-file remapping.
1292 for (PreprocessorOptions::remapped_file_buffer_iterator
1293 M = PreprocessorOpts.remapped_file_buffer_begin(),
1294 E = PreprocessorOpts.remapped_file_buffer_end();
1295 M != E;
1296 ++M) {
1297 llvm::sys::PathWithStatus MPath(M->first);
1298 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1299 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1300 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001301 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001302 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001303 CreatedBuffer = false;
1304 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001305
Douglas Gregor175c4a92010-07-23 23:58:40 +00001306 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001307 }
1308 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001309 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001310 }
1311
1312 // If the main source file was not remapped, load it now.
1313 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001314 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001315 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001316 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001317
1318 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001319 }
1320
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001321 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001322 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001323 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001324}
1325
Douglas Gregor754f3492010-07-24 00:38:13 +00001326static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001327 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001328 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001329 llvm::MemoryBuffer *Result
1330 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1331 memcpy(const_cast<char*>(Result->getBufferStart()),
1332 Old->getBufferStart(), Old->getBufferSize());
1333 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001334 ' ', NewSize - Old->getBufferSize() - 1);
1335 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001336
Douglas Gregor754f3492010-07-24 00:38:13 +00001337 return Result;
1338}
1339
Douglas Gregor175c4a92010-07-23 23:58:40 +00001340/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1341/// the source file.
1342///
1343/// This routine will compute the preamble of the main source file. If a
1344/// non-trivial preamble is found, it will precompile that preamble into a
1345/// precompiled header so that the precompiled preamble can be used to reduce
1346/// reparsing time. If a precompiled preamble has already been constructed,
1347/// this routine will determine if it is still valid and, if so, avoid
1348/// rebuilding the precompiled preamble.
1349///
Douglas Gregordf95a132010-08-09 20:45:32 +00001350/// \param AllowRebuild When true (the default), this routine is
1351/// allowed to rebuild the precompiled preamble if it is found to be
1352/// out-of-date.
1353///
1354/// \param MaxLines When non-zero, the maximum number of lines that
1355/// can occur within the preamble.
1356///
Douglas Gregor754f3492010-07-24 00:38:13 +00001357/// \returns If the precompiled preamble can be used, returns a newly-allocated
1358/// buffer that should be used in place of the main file when doing so.
1359/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001360llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001361 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001362 bool AllowRebuild,
1363 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001364
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001365 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001366 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1367 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001368 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001369 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001370
1371 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001372 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001373 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001374
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001375 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001376 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001377 if (CreatedPreambleBuffer)
1378 OwnedPreambleBuffer.reset(NewPreamble.first);
1379
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001380 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001381 // We couldn't find a preamble in the main source. Clear out the current
1382 // preamble, if we have one. It's obviously no good any more.
1383 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001384 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001385
1386 // The next time we actually see a preamble, precompile it.
1387 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001388 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001389 }
1390
1391 if (!Preamble.empty()) {
1392 // We've previously computed a preamble. Check whether we have the same
1393 // preamble now that we did before, and that there's enough space in
1394 // the main-file buffer within the precompiled preamble to fit the
1395 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001396 if (Preamble.size() == NewPreamble.second.first &&
1397 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001398 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001399 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001400 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001401 // The preamble has not changed. We may be able to re-use the precompiled
1402 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001403
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001404 // Check that none of the files used by the preamble have changed.
1405 bool AnyFileChanged = false;
1406
1407 // First, make a record of those files that have been overridden via
1408 // remapping or unsaved_files.
1409 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1410 for (PreprocessorOptions::remapped_file_iterator
1411 R = PreprocessorOpts.remapped_file_begin(),
1412 REnd = PreprocessorOpts.remapped_file_end();
1413 !AnyFileChanged && R != REnd;
1414 ++R) {
1415 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001416 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001417 // If we can't stat the file we're remapping to, assume that something
1418 // horrible happened.
1419 AnyFileChanged = true;
1420 break;
1421 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001422
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001423 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1424 StatBuf.st_mtime);
1425 }
1426 for (PreprocessorOptions::remapped_file_buffer_iterator
1427 R = PreprocessorOpts.remapped_file_buffer_begin(),
1428 REnd = PreprocessorOpts.remapped_file_buffer_end();
1429 !AnyFileChanged && R != REnd;
1430 ++R) {
1431 // FIXME: Should we actually compare the contents of file->buffer
1432 // remappings?
1433 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1434 0);
1435 }
1436
1437 // Check whether anything has changed.
1438 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1439 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1440 !AnyFileChanged && F != FEnd;
1441 ++F) {
1442 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1443 = OverriddenFiles.find(F->first());
1444 if (Overridden != OverriddenFiles.end()) {
1445 // This file was remapped; check whether the newly-mapped file
1446 // matches up with the previous mapping.
1447 if (Overridden->second != F->second)
1448 AnyFileChanged = true;
1449 continue;
1450 }
1451
1452 // The file was not remapped; check whether it has changed on disk.
1453 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001454 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001455 // If we can't stat the file, assume that something horrible happened.
1456 AnyFileChanged = true;
1457 } else if (StatBuf.st_size != F->second.first ||
1458 StatBuf.st_mtime != F->second.second)
1459 AnyFileChanged = true;
1460 }
1461
1462 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001463 // Okay! We can re-use the precompiled preamble.
1464
1465 // Set the state of the diagnostic object to mimic its state
1466 // after parsing the preamble.
1467 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001468 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001469 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001470 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001471
1472 // Create a version of the main file buffer that is padded to
1473 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001474 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001475 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001476 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001477 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001478 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001479
1480 // If we aren't allowed to rebuild the precompiled preamble, just
1481 // return now.
1482 if (!AllowRebuild)
1483 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001484
Douglas Gregor175c4a92010-07-23 23:58:40 +00001485 // We can't reuse the previously-computed preamble. Build a new one.
1486 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001487 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001488 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001489 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001490 } else if (!AllowRebuild) {
1491 // We aren't allowed to rebuild the precompiled preamble; just
1492 // return now.
1493 return 0;
1494 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001495
1496 // If the preamble rebuild counter > 1, it's because we previously
1497 // failed to build a preamble and we're not yet ready to try
1498 // again. Decrement the counter and return a failure.
1499 if (PreambleRebuildCounter > 1) {
1500 --PreambleRebuildCounter;
1501 return 0;
1502 }
1503
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001504 // Create a temporary file for the precompiled preamble. In rare
1505 // circumstances, this can fail.
1506 std::string PreamblePCHPath = GetPreamblePCHPath();
1507 if (PreamblePCHPath.empty()) {
1508 // Try again next time.
1509 PreambleRebuildCounter = 1;
1510 return 0;
1511 }
1512
Douglas Gregor175c4a92010-07-23 23:58:40 +00001513 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001514 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001515 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516
1517 // Create a new buffer that stores the preamble. The buffer also contains
1518 // extra space for the original contents of the file (which will be present
1519 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001520 // grows.
1521 PreambleReservedSize = NewPreamble.first->getBufferSize();
1522 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001523 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001524 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001525 PreambleReservedSize *= 2;
1526
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001527 // Save the preamble text for later; we'll need to compare against it for
1528 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001529 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001530 Preamble.assign(FileMgr->getFile(MainFilename),
1531 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001532 NewPreamble.first->getBufferStart()
1533 + NewPreamble.second.first);
1534 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1535
Douglas Gregor671947b2010-08-19 01:33:06 +00001536 delete PreambleBuffer;
1537 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001538 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001539 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001540 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001541 NewPreamble.first->getBufferStart(), Preamble.size());
1542 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001543 ' ', PreambleReservedSize - Preamble.size() - 1);
1544 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001545
1546 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001547 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1549
1550 // Tell the compiler invocation to generate a temporary precompiled header.
1551 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001553 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001554 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1555 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001556
1557 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001558 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001559
1560 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001561 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1562 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001563
Douglas Gregor01b6e312011-07-01 18:22:13 +00001564 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001565 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001566
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001567 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001568 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001569
1570 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001571 Clang->getTargetOpts().Features = TargetFeatures;
1572 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1573 Clang->getTargetOpts()));
1574 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001575 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1576 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001577 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001578 PreprocessorOpts.eraseRemappedFile(
1579 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001580 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001581 }
1582
1583 // Inform the target of the language options.
1584 //
1585 // FIXME: We shouldn't need to do this, the target should be immutable once
1586 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001587 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001588
Ted Kremenek03201fb2011-03-21 18:40:07 +00001589 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001591 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001592 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001593 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001594 "IR inputs not support here!");
1595
1596 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001597 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001598 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001599 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001600 TopLevelDecls.clear();
1601 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001602
1603 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001604 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001605
1606 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001607 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001608 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001609
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001610 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001611 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001612 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001613 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1614 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001615 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001616 PreprocessorOpts.eraseRemappedFile(
1617 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001618 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001619 }
1620
1621 Act->Execute();
1622 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001623
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001624 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001625 // There were errors parsing the preamble, so no precompiled header was
1626 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001627 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001628 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1629 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001630 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001631 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001632 PreprocessorOpts.eraseRemappedFile(
1633 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001634 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001635 }
1636
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001637 // Transfer any diagnostics generated when parsing the preamble into the set
1638 // of preamble diagnostics.
1639 PreambleDiagnostics.clear();
1640 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001641 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001642 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001643
Douglas Gregor175c4a92010-07-23 23:58:40 +00001644 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001645 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001646 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001647
1648 // Keep track of all of the files that the source manager knows about,
1649 // so we can verify whether they have changed or not.
1650 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001651 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001652 const llvm::MemoryBuffer *MainFileBuffer
1653 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1654 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1655 FEnd = SourceMgr.fileinfo_end();
1656 F != FEnd;
1657 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001658 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001659 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1660 continue;
1661
1662 FilesInPreamble[File->getName()]
1663 = std::make_pair(F->second->getSize(), File->getModificationTime());
1664 }
1665
Douglas Gregoreababfb2010-08-04 05:53:38 +00001666 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001667 PreprocessorOpts.eraseRemappedFile(
1668 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001669
1670 // If the hash of top-level entities differs from the hash of the top-level
1671 // entities the last time we rebuilt the preamble, clear out the completion
1672 // cache.
1673 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1674 CompletionCacheTopLevelHashValue = 0;
1675 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1676 }
1677
Douglas Gregor754f3492010-07-24 00:38:13 +00001678 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001679 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001680 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001681}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001682
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001683void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1684 std::vector<Decl *> Resolved;
1685 Resolved.reserve(TopLevelDeclsInPreamble.size());
1686 ExternalASTSource &Source = *getASTContext().getExternalSource();
1687 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1688 // Resolve the declaration ID to an actual declaration, possibly
1689 // deserializing the declaration in the process.
1690 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1691 if (D)
1692 Resolved.push_back(D);
1693 }
1694 TopLevelDeclsInPreamble.clear();
1695 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1696}
1697
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001698void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1699 // Steal the created target, context, and preprocessor.
1700 TheSema.reset(CI.takeSema());
1701 Consumer.reset(CI.takeASTConsumer());
1702 Ctx = &CI.getASTContext();
1703 PP = &CI.getPreprocessor();
1704 CI.setSourceManager(0);
1705 CI.setFileManager(0);
1706 Target = &CI.getTarget();
1707 Reader = CI.getModuleManager();
1708}
1709
Chris Lattner5f9e2722011-07-23 10:55:15 +00001710StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001711 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001712}
1713
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001714ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001715 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001716 bool CaptureDiagnostics,
1717 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001718 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001719 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001720 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001721 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001722 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001723 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001724 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001725 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1726 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1727 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001728
1729 return AST.take();
1730}
1731
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001732ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001733 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001734 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001735 ASTUnit *Unit,
1736 bool Persistent,
1737 StringRef ResourceFilesPath,
1738 bool OnlyLocalDecls,
1739 bool CaptureDiagnostics,
1740 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001741 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001742 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001743 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001744 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001745 assert(CI && "A CompilerInvocation is required");
1746
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001747 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001748 ASTUnit *AST = Unit;
1749 if (!AST) {
1750 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001751 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001752 AST = OwnAST.get();
1753 }
1754
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001755 if (!ResourceFilesPath.empty()) {
1756 // Override the resources path.
1757 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1758 }
1759 AST->OnlyLocalDecls = OnlyLocalDecls;
1760 AST->CaptureDiagnostics = CaptureDiagnostics;
1761 if (PrecompilePreamble)
1762 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001763 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001764 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001765 AST->IncludeBriefCommentsInCodeCompletion
1766 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001767
1768 // Recover resources if we crash before exiting this method.
1769 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001770 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001771 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1772 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001773 DiagCleanup(Diags.getPtr());
1774
1775 // We'll manage file buffers ourselves.
1776 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1777 CI->getFrontendOpts().DisableFree = false;
1778 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1779
1780 // Save the target features.
1781 AST->TargetFeatures = CI->getTargetOpts().Features;
1782
1783 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001784 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001785
1786 // Recover resources if we crash before exiting this method.
1787 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1788 CICleanup(Clang.get());
1789
1790 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001791 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001792
1793 // Set up diagnostics, capturing any diagnostics that would
1794 // otherwise be dropped.
1795 Clang->setDiagnostics(&AST->getDiagnostics());
1796
1797 // Create the target instance.
1798 Clang->getTargetOpts().Features = AST->TargetFeatures;
1799 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1800 Clang->getTargetOpts()));
1801 if (!Clang->hasTarget())
1802 return 0;
1803
1804 // Inform the target of the language options.
1805 //
1806 // FIXME: We shouldn't need to do this, the target should be immutable once
1807 // created. This complexity should be lifted elsewhere.
1808 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1809
1810 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1811 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001812 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001814 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001815 "IR inputs not supported here!");
1816
1817 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001818 AST->TheSema.reset();
1819 AST->Ctx = 0;
1820 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001821 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001822
1823 // Create a file manager object to provide access to and cache the filesystem.
1824 Clang->setFileManager(&AST->getFileManager());
1825
1826 // Create the source manager.
1827 Clang->setSourceManager(&AST->getSourceManager());
1828
1829 ASTFrontendAction *Act = Action;
1830
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001831 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001832 if (!Act) {
1833 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1834 Act = TrackerAct.get();
1835 }
1836
1837 // Recover resources if we crash before exiting this method.
1838 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1839 ActCleanup(TrackerAct.get());
1840
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001841 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1842 AST->transferASTDataFromCompilerInstance(*Clang);
1843 if (OwnAST && ErrAST)
1844 ErrAST->swap(OwnAST);
1845
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001846 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001847 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001848
1849 if (Persistent && !TrackerAct) {
1850 Clang->getPreprocessor().addPPCallbacks(
1851 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1852 std::vector<ASTConsumer*> Consumers;
1853 if (Clang->hasASTConsumer())
1854 Consumers.push_back(Clang->takeASTConsumer());
1855 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1856 AST->getCurrentTopLevelHashValue()));
1857 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1858 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001859 if (!Act->Execute()) {
1860 AST->transferASTDataFromCompilerInstance(*Clang);
1861 if (OwnAST && ErrAST)
1862 ErrAST->swap(OwnAST);
1863
1864 return 0;
1865 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001866
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001867 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001868 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001869
1870 Act->EndSourceFile();
1871
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001872 if (OwnAST)
1873 return OwnAST.take();
1874 else
1875 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001876}
1877
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001878bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1879 if (!Invocation)
1880 return true;
1881
1882 // We'll manage file buffers ourselves.
1883 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1884 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001885 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001886
Douglas Gregor1aa27302011-01-27 18:02:58 +00001887 // Save the target features.
1888 TargetFeatures = Invocation->getTargetOpts().Features;
1889
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001890 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001891 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001892 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001893 OverrideMainBuffer
1894 = getMainBufferWithPrecompiledPreamble(*Invocation);
1895 }
1896
Douglas Gregor213f18b2010-10-28 15:44:59 +00001897 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001898 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001899
Ted Kremenek25a11e12011-03-22 01:15:24 +00001900 // Recover resources if we crash before exiting this method.
1901 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1902 MemBufferCleanup(OverrideMainBuffer);
1903
Douglas Gregor213f18b2010-10-28 15:44:59 +00001904 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001905}
1906
Douglas Gregorabc563f2010-07-19 21:46:24 +00001907ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001908 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001909 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001910 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001911 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001912 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001913 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001914 bool IncludeBriefCommentsInCodeCompletion,
1915 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001916 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001917 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001918 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001919 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001920 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001921 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001922 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001923 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001924 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001925 AST->IncludeBriefCommentsInCodeCompletion
1926 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001927 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001928 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001929
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001930 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001931 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1932 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001933 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1934 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001935 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001936
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001937 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001938}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001939
1940ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1941 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001942 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001943 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001944 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001945 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001946 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001947 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001948 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001949 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001950 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001951 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001952 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001953 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001954 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001955 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001956 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001957 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001958 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001959 // No diagnostics engine was provided, so create our own diagnostics object
1960 // with the default options.
1961 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001962 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1963 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001964 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001965
Chris Lattner5f9e2722011-07-23 10:55:15 +00001966 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001967
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001968 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001969
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001970 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001971
Douglas Gregore47be3e2010-11-11 00:39:14 +00001972 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001973 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001974
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001975 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001976 llvm::makeArrayRef(ArgBegin, ArgEnd),
1977 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001978 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001979 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001980 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001981
Douglas Gregor4db64a42010-01-23 00:14:00 +00001982 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001983 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1984 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1985 if (const llvm::MemoryBuffer *
1986 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1987 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1988 } else {
1989 const char *fname = fileOrBuf.get<const char *>();
1990 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1991 }
1992 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001993 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1994 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1995 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001996
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001997 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001998 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001999
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002000 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2001
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002002 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002003 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002004 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002005 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002006 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002007 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002008 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002009 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002010 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002011 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002012 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002013 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002014 AST->IncludeBriefCommentsInCodeCompletion
2015 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002016 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002017 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002018 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002019 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002020 if (ForSerialization)
2021 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002022 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002023
2024 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002025 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2026 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002027
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002028 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2029 // Some error occurred, if caller wants to examine diagnostics, pass it the
2030 // ASTUnit.
2031 if (ErrAST) {
2032 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2033 ErrAST->swap(AST);
2034 }
2035 return 0;
2036 }
2037
2038 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002039}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002040
2041bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002042 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002043 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002044
2045 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002046
Douglas Gregor213f18b2010-10-28 15:44:59 +00002047 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002048 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002049
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002050 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002051 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002052 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002053 for (PreprocessorOptions::remapped_file_buffer_iterator
2054 R = PPOpts.remapped_file_buffer_begin(),
2055 REnd = PPOpts.remapped_file_buffer_end();
2056 R != REnd;
2057 ++R) {
2058 delete R->second;
2059 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002060 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002061 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2062 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2063 if (const llvm::MemoryBuffer *
2064 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2065 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2066 memBuf);
2067 } else {
2068 const char *fname = fileOrBuf.get<const char *>();
2069 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2070 fname);
2071 }
2072 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002073
Douglas Gregoreababfb2010-08-04 05:53:38 +00002074 // If we have a preamble file lying around, or if we might try to
2075 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002076 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002077 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002078 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002079
Douglas Gregorabc563f2010-07-19 21:46:24 +00002080 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002081 getDiagnostics().Reset();
2082 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002083 if (OverrideMainBuffer)
2084 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002085
Douglas Gregor175c4a92010-07-23 23:58:40 +00002086 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002087 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002088
2089 // If we're caching global code-completion results, and the top-level
2090 // declarations have changed, clear out the code-completion cache.
2091 if (!Result && ShouldCacheCodeCompletionResults &&
2092 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2093 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002094
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002095 // We now need to clear out the completion info related to this translation
2096 // unit; it'll be recreated if necessary.
2097 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002098
Douglas Gregor175c4a92010-07-23 23:58:40 +00002099 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002100}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002101
Douglas Gregor87c08a52010-08-13 22:48:40 +00002102//----------------------------------------------------------------------------//
2103// Code completion
2104//----------------------------------------------------------------------------//
2105
2106namespace {
2107 /// \brief Code completion consumer that combines the cached code-completion
2108 /// results from an ASTUnit with the code-completion results provided to it,
2109 /// then passes the result on to
2110 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002111 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002112 ASTUnit &AST;
2113 CodeCompleteConsumer &Next;
2114
2115 public:
2116 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002117 const CodeCompleteOptions &CodeCompleteOpts)
2118 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2119 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002120 {
2121 // Compute the set of contexts in which we will look when we don't have
2122 // any information about the specific context.
2123 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002124 = (1LL << CodeCompletionContext::CCC_TopLevel)
2125 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2126 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2127 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2128 | (1LL << CodeCompletionContext::CCC_Statement)
2129 | (1LL << CodeCompletionContext::CCC_Expression)
2130 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2131 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2132 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2133 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2134 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2135 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2136 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002137
David Blaikie4e4d0842012-03-11 07:00:24 +00002138 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002139 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2140 | (1LL << CodeCompletionContext::CCC_UnionTag)
2141 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002142 }
2143
2144 virtual void ProcessCodeCompleteResults(Sema &S,
2145 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002146 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002147 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002148
2149 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2150 OverloadCandidate *Candidates,
2151 unsigned NumCandidates) {
2152 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2153 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002154
Douglas Gregordae68752011-02-01 22:57:45 +00002155 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002156 return Next.getAllocator();
2157 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002158
2159 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2160 return Next.getCodeCompletionTUInfo();
2161 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002162 };
2163}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002164
Douglas Gregor5f808c22010-08-16 21:18:39 +00002165/// \brief Helper function that computes which global names are hidden by the
2166/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002167static void CalculateHiddenNames(const CodeCompletionContext &Context,
2168 CodeCompletionResult *Results,
2169 unsigned NumResults,
2170 ASTContext &Ctx,
2171 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002172 bool OnlyTagNames = false;
2173 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002174 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002175 case CodeCompletionContext::CCC_TopLevel:
2176 case CodeCompletionContext::CCC_ObjCInterface:
2177 case CodeCompletionContext::CCC_ObjCImplementation:
2178 case CodeCompletionContext::CCC_ObjCIvarList:
2179 case CodeCompletionContext::CCC_ClassStructUnion:
2180 case CodeCompletionContext::CCC_Statement:
2181 case CodeCompletionContext::CCC_Expression:
2182 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002183 case CodeCompletionContext::CCC_DotMemberAccess:
2184 case CodeCompletionContext::CCC_ArrowMemberAccess:
2185 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002186 case CodeCompletionContext::CCC_Namespace:
2187 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002188 case CodeCompletionContext::CCC_Name:
2189 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002190 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002191 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002192 break;
2193
2194 case CodeCompletionContext::CCC_EnumTag:
2195 case CodeCompletionContext::CCC_UnionTag:
2196 case CodeCompletionContext::CCC_ClassOrStructTag:
2197 OnlyTagNames = true;
2198 break;
2199
2200 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002201 case CodeCompletionContext::CCC_MacroName:
2202 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002203 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002204 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002205 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002206 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002207 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002208 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002209 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002210 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2211 case CodeCompletionContext::CCC_ObjCClassMessage:
2212 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002213 // We're looking for nothing, or we're looking for names that cannot
2214 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002215 return;
2216 }
2217
John McCall0a2c5e22010-08-25 06:19:51 +00002218 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002219 for (unsigned I = 0; I != NumResults; ++I) {
2220 if (Results[I].Kind != Result::RK_Declaration)
2221 continue;
2222
2223 unsigned IDNS
2224 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2225
2226 bool Hiding = false;
2227 if (OnlyTagNames)
2228 Hiding = (IDNS & Decl::IDNS_Tag);
2229 else {
2230 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002231 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2232 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002233 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002234 HiddenIDNS |= Decl::IDNS_Tag;
2235 Hiding = (IDNS & HiddenIDNS);
2236 }
2237
2238 if (!Hiding)
2239 continue;
2240
2241 DeclarationName Name = Results[I].Declaration->getDeclName();
2242 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2243 HiddenNames.insert(Identifier->getName());
2244 else
2245 HiddenNames.insert(Name.getAsString());
2246 }
2247}
2248
2249
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002250void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2251 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002252 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002253 unsigned NumResults) {
2254 // Merge the results we were given with the results we cached.
2255 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002256 uint64_t InContexts =
2257 Context.getKind() == CodeCompletionContext::CCC_Recovery
2258 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002259 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002260 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002261 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002262 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002263 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002264 C = AST.cached_completion_begin(),
2265 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002266 C != CEnd; ++C) {
2267 // If the context we are in matches any of the contexts we are
2268 // interested in, we'll add this result.
2269 if ((C->ShowInContexts & InContexts) == 0)
2270 continue;
2271
2272 // If we haven't added any results previously, do so now.
2273 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002274 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2275 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002276 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2277 AddedResult = true;
2278 }
2279
Douglas Gregor5f808c22010-08-16 21:18:39 +00002280 // Determine whether this global completion result is hidden by a local
2281 // completion result. If so, skip it.
2282 if (C->Kind != CXCursor_MacroDefinition &&
2283 HiddenNames.count(C->Completion->getTypedText()))
2284 continue;
2285
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002286 // Adjust priority based on similar type classes.
2287 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002288 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002289 if (!Context.getPreferredType().isNull()) {
2290 if (C->Kind == CXCursor_MacroDefinition) {
2291 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002292 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002293 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002294 } else if (C->Type) {
2295 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002296 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002297 Context.getPreferredType().getUnqualifiedType());
2298 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2299 if (ExpectedSTC == C->TypeClass) {
2300 // We know this type is similar; check for an exact match.
2301 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002302 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002303 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002304 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002305 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2306 Priority /= CCF_ExactTypeMatch;
2307 else
2308 Priority /= CCF_SimilarTypeMatch;
2309 }
2310 }
2311 }
2312
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002313 // Adjust the completion string, if required.
2314 if (C->Kind == CXCursor_MacroDefinition &&
2315 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2316 // Create a new code-completion string that just contains the
2317 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002318 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2319 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002320 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002321 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002322 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002323 }
2324
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002325 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002326 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002327 }
2328
2329 // If we did not add any cached completion results, just forward the
2330 // results we were given to the next consumer.
2331 if (!AddedResult) {
2332 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2333 return;
2334 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002335
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002336 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2337 AllResults.size());
2338}
2339
2340
2341
Chris Lattner5f9e2722011-07-23 10:55:15 +00002342void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002343 RemappedFile *RemappedFiles,
2344 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002345 bool IncludeMacros,
2346 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002347 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002349 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002350 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002351 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2352 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002353 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354 return;
2355
Douglas Gregor213f18b2010-10-28 15:44:59 +00002356 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002357 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002358 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002359
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002360 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002361 CCInvocation(new CompilerInvocation(*Invocation));
2362
2363 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002364 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002365 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002366
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002367 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2368 CachedCompletionResults.empty();
2369 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2370 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2371 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2372
2373 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2374
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 FrontendOpts.CodeCompletionAt.FileName = File;
2376 FrontendOpts.CodeCompletionAt.Line = Line;
2377 FrontendOpts.CodeCompletionAt.Column = Column;
2378
2379 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002380 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002381
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002382 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002383
2384 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002385 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2386 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002387
Ted Kremenek4f327862011-03-21 18:40:17 +00002388 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002389 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390
2391 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002392 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002393 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002394 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002395 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002396 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002397
2398 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002399 Clang->getTargetOpts().Features = TargetFeatures;
2400 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2401 Clang->getTargetOpts()));
2402 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002403 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002404 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002405 }
2406
2407 // Inform the target of the language options.
2408 //
2409 // FIXME: We shouldn't need to do this, the target should be immutable once
2410 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002411 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002412
Ted Kremenek03201fb2011-03-21 18:40:07 +00002413 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002414 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002415 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002417 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418 "IR inputs not support here!");
2419
2420
2421 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002422 Clang->setFileManager(&FileMgr);
2423 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002424
2425 // Remap files.
2426 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002427 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002428 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002429 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2430 if (const llvm::MemoryBuffer *
2431 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2432 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2433 OwnedBuffers.push_back(memBuf);
2434 } else {
2435 const char *fname = fileOrBuf.get<const char *>();
2436 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2437 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002438 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002439
Douglas Gregor87c08a52010-08-13 22:48:40 +00002440 // Use the code completion consumer we were given, but adding any cached
2441 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002442 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002443 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002444 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002445
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002446 Clang->getFrontendOpts().SkipFunctionBodies = true;
2447
Douglas Gregordf95a132010-08-09 20:45:32 +00002448 // If we have a precompiled preamble, try to use it. We only allow
2449 // the use of the precompiled preamble if we're if the completion
2450 // point is within the main file, after the end of the precompiled
2451 // preamble.
2452 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002453 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002454 using llvm::sys::FileStatus;
2455 llvm::sys::PathWithStatus CompleteFilePath(File);
2456 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2457 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2458 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002459 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2460 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002461 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002462 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002463 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002464 }
2465
2466 // If the main file has been overridden due to the use of a preamble,
2467 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002468 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002469 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002470 stored_diag_begin(),
2471 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002472 if (OverrideMainBuffer) {
2473 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2474 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2475 PreprocessorOpts.PrecompiledPreambleBytes.second
2476 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002477 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002478 PreprocessorOpts.DisablePCHValidation = true;
2479
Douglas Gregor2283d792010-08-20 00:59:43 +00002480 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002481 } else {
2482 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2483 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002484 }
2485
Douglas Gregordca8ee82011-05-06 16:33:08 +00002486 // Disable the preprocessing record
2487 PreprocessorOpts.DetailedRecord = false;
2488
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002489 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002490 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002491 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002492 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002493 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002494 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2495 getSourceManager(), PreambleDiagnostics,
2496 StoredDiagnostics);
2497 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002498 Act->Execute();
2499 Act->EndSourceFile();
2500 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002501
2502 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002503}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002504
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002505bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002506 // Write to a temporary file and later rename it to the actual file, to avoid
2507 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002508 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002509 TempPath = File;
2510 TempPath += "-%%%%%%%%";
2511 int fd;
2512 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2513 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002514 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002515
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002516 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2517 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002518 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002519
2520 serialize(Out);
2521 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002522 if (Out.has_error()) {
2523 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002524 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002525 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002526
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002527 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002528 bool exists;
2529 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002530 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002531 }
2532
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002533 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002534}
2535
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002536static bool serializeUnit(ASTWriter &Writer,
2537 SmallVectorImpl<char> &Buffer,
2538 Sema &S,
2539 bool hasErrors,
2540 raw_ostream &OS) {
2541 Writer.WriteAST(S, 0, std::string(), 0, "", hasErrors);
2542
2543 // Write the generated bitstream to "Out".
2544 if (!Buffer.empty())
2545 OS.write(Buffer.data(), Buffer.size());
2546
2547 return false;
2548}
2549
Chris Lattner5f9e2722011-07-23 10:55:15 +00002550bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002551 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002552
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002553 if (WriterData)
2554 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2555 getSema(), hasErrors, OS);
2556
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002557 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002558 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002559 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002560 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002561}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002562
2563typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2564
2565static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2566 unsigned Raw = L.getRawEncoding();
2567 const unsigned MacroBit = 1U << 31;
2568 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2569 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2570}
2571
2572void ASTUnit::TranslateStoredDiagnostics(
2573 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002575 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002576 const SmallVectorImpl<StoredDiagnostic> &Diags,
2577 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002578 // The stored diagnostic has the old source manager in it; update
2579 // the locations to refer into the new source manager. We also need to remap
2580 // all the locations to the new view. This includes the diag location, any
2581 // associated source ranges, and the source ranges of associated fix-its.
2582 // FIXME: There should be a cleaner way to do this.
2583
Chris Lattner5f9e2722011-07-23 10:55:15 +00002584 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002585 Result.reserve(Diags.size());
2586 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002587 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002588 assert(Mod && "Don't have preamble module");
2589 SLocRemap &Remap = Mod->SLocRemap;
2590 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2591 // Rebuild the StoredDiagnostic.
2592 const StoredDiagnostic &SD = Diags[I];
2593 SourceLocation L = SD.getLocation();
2594 TranslateSLoc(L, Remap);
2595 FullSourceLoc Loc(L, SrcMgr);
2596
Chris Lattner5f9e2722011-07-23 10:55:15 +00002597 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002598 Ranges.reserve(SD.range_size());
2599 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2600 E = SD.range_end();
2601 I != E; ++I) {
2602 SourceLocation BL = I->getBegin();
2603 TranslateSLoc(BL, Remap);
2604 SourceLocation EL = I->getEnd();
2605 TranslateSLoc(EL, Remap);
2606 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2607 }
2608
Chris Lattner5f9e2722011-07-23 10:55:15 +00002609 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002610 FixIts.reserve(SD.fixit_size());
2611 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2612 E = SD.fixit_end();
2613 I != E; ++I) {
2614 FixIts.push_back(FixItHint());
2615 FixItHint &FH = FixIts.back();
2616 FH.CodeToInsert = I->CodeToInsert;
2617 SourceLocation BL = I->RemoveRange.getBegin();
2618 TranslateSLoc(BL, Remap);
2619 SourceLocation EL = I->RemoveRange.getEnd();
2620 TranslateSLoc(EL, Remap);
2621 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2622 I->RemoveRange.isTokenRange());
2623 }
2624
2625 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2626 SD.getMessage(), Loc, Ranges, FixIts));
2627 }
2628 Result.swap(Out);
2629}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002630
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002631static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2632 std::pair<unsigned, Decl *> R) {
2633 return L.first < R.first;
2634}
2635
2636void ASTUnit::addFileLevelDecl(Decl *D) {
2637 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002638
2639 // We only care about local declarations.
2640 if (D->isFromASTFile())
2641 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002642
2643 SourceManager &SM = *SourceMgr;
2644 SourceLocation Loc = D->getLocation();
2645 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2646 return;
2647
2648 // We only keep track of the file-level declarations of each file.
2649 if (!D->getLexicalDeclContext()->isFileContext())
2650 return;
2651
2652 SourceLocation FileLoc = SM.getFileLoc(Loc);
2653 assert(SM.isLocalSourceLocation(FileLoc));
2654 FileID FID;
2655 unsigned Offset;
2656 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2657 if (FID.isInvalid())
2658 return;
2659
2660 LocDeclsTy *&Decls = FileDecls[FID];
2661 if (!Decls)
2662 Decls = new LocDeclsTy();
2663
2664 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2665
2666 if (Decls->empty() || Decls->back().first <= Offset) {
2667 Decls->push_back(LocDecl);
2668 return;
2669 }
2670
2671 LocDeclsTy::iterator
2672 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2673
2674 Decls->insert(I, LocDecl);
2675}
2676
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002677void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2678 SmallVectorImpl<Decl *> &Decls) {
2679 if (File.isInvalid())
2680 return;
2681
2682 if (SourceMgr->isLoadedFileID(File)) {
2683 assert(Ctx->getExternalSource() && "No external source!");
2684 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2685 Decls);
2686 }
2687
2688 FileDeclsTy::iterator I = FileDecls.find(File);
2689 if (I == FileDecls.end())
2690 return;
2691
2692 LocDeclsTy &LocDecls = *I->second;
2693 if (LocDecls.empty())
2694 return;
2695
2696 LocDeclsTy::iterator
2697 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2698 std::make_pair(Offset, (Decl*)0), compLocDecl);
2699 if (BeginIt != LocDecls.begin())
2700 --BeginIt;
2701
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002702 // If we are pointing at a top-level decl inside an objc container, we need
2703 // to backtrack until we find it otherwise we will fail to report that the
2704 // region overlaps with an objc container.
2705 while (BeginIt != LocDecls.begin() &&
2706 BeginIt->second->isTopLevelDeclInObjCContainer())
2707 --BeginIt;
2708
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002709 LocDeclsTy::iterator
2710 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2711 std::make_pair(Offset+Length, (Decl*)0),
2712 compLocDecl);
2713 if (EndIt != LocDecls.end())
2714 ++EndIt;
2715
2716 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2717 Decls.push_back(DIt->second);
2718}
2719
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002720SourceLocation ASTUnit::getLocation(const FileEntry *File,
2721 unsigned Line, unsigned Col) const {
2722 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002723 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002724 return SM.getMacroArgExpandedLocation(Loc);
2725}
2726
2727SourceLocation ASTUnit::getLocation(const FileEntry *File,
2728 unsigned Offset) const {
2729 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002730 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002731 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2732}
2733
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002734/// \brief If \arg Loc is a loaded location from the preamble, returns
2735/// the corresponding local location of the main file, otherwise it returns
2736/// \arg Loc.
2737SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2738 FileID PreambleID;
2739 if (SourceMgr)
2740 PreambleID = SourceMgr->getPreambleFileID();
2741
2742 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2743 return Loc;
2744
2745 unsigned Offs;
2746 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2747 SourceLocation FileLoc
2748 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2749 return FileLoc.getLocWithOffset(Offs);
2750 }
2751
2752 return Loc;
2753}
2754
2755/// \brief If \arg Loc is a local location of the main file but inside the
2756/// preamble chunk, returns the corresponding loaded location from the
2757/// preamble, otherwise it returns \arg Loc.
2758SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2759 FileID PreambleID;
2760 if (SourceMgr)
2761 PreambleID = SourceMgr->getPreambleFileID();
2762
2763 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2764 return Loc;
2765
2766 unsigned Offs;
2767 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2768 Offs < Preamble.size()) {
2769 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2770 return FileLoc.getLocWithOffset(Offs);
2771 }
2772
2773 return Loc;
2774}
2775
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002776bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2777 FileID FID;
2778 if (SourceMgr)
2779 FID = SourceMgr->getPreambleFileID();
2780
2781 if (Loc.isInvalid() || FID.isInvalid())
2782 return false;
2783
2784 return SourceMgr->isInFileID(Loc, FID);
2785}
2786
2787bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2788 FileID FID;
2789 if (SourceMgr)
2790 FID = SourceMgr->getMainFileID();
2791
2792 if (Loc.isInvalid() || FID.isInvalid())
2793 return false;
2794
2795 return SourceMgr->isInFileID(Loc, FID);
2796}
2797
2798SourceLocation ASTUnit::getEndOfPreambleFileID() {
2799 FileID FID;
2800 if (SourceMgr)
2801 FID = SourceMgr->getPreambleFileID();
2802
2803 if (FID.isInvalid())
2804 return SourceLocation();
2805
2806 return SourceMgr->getLocForEndOfFile(FID);
2807}
2808
2809SourceLocation ASTUnit::getStartOfMainFileID() {
2810 FileID FID;
2811 if (SourceMgr)
2812 FID = SourceMgr->getMainFileID();
2813
2814 if (FID.isInvalid())
2815 return SourceLocation();
2816
2817 return SourceMgr->getLocForStartOfFile(FID);
2818}
2819
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002820std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2821ASTUnit::getLocalPreprocessingEntities() const {
2822 if (isMainFileAST()) {
2823 serialization::ModuleFile &
2824 Mod = Reader->getModuleManager().getPrimaryModule();
2825 return Reader->getModulePreprocessedEntities(Mod);
2826 }
2827
2828 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2829 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2830
2831 return std::make_pair(PreprocessingRecord::iterator(),
2832 PreprocessingRecord::iterator());
2833}
2834
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002835bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002836 if (isMainFileAST()) {
2837 serialization::ModuleFile &
2838 Mod = Reader->getModuleManager().getPrimaryModule();
2839 ASTReader::ModuleDeclIterator MDI, MDE;
2840 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2841 for (; MDI != MDE; ++MDI) {
2842 if (!Fn(context, *MDI))
2843 return false;
2844 }
2845
2846 return true;
2847 }
2848
2849 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2850 TLEnd = top_level_end();
2851 TL != TLEnd; ++TL) {
2852 if (!Fn(context, *TL))
2853 return false;
2854 }
2855
2856 return true;
2857}
2858
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002859namespace {
2860struct PCHLocatorInfo {
2861 serialization::ModuleFile *Mod;
2862 PCHLocatorInfo() : Mod(0) {}
2863};
2864}
2865
2866static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2867 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2868 switch (M.Kind) {
2869 case serialization::MK_Module:
2870 return true; // skip dependencies.
2871 case serialization::MK_PCH:
2872 Info.Mod = &M;
2873 return true; // found it.
2874 case serialization::MK_Preamble:
2875 return false; // look in dependencies.
2876 case serialization::MK_MainFile:
2877 return false; // look in dependencies.
2878 }
2879
2880 return true;
2881}
2882
2883const FileEntry *ASTUnit::getPCHFile() {
2884 if (!Reader)
2885 return 0;
2886
2887 PCHLocatorInfo Info;
2888 Reader->getModuleManager().visit(PCHLocator, &Info);
2889 if (Info.Mod)
2890 return Info.Mod->File;
2891
2892 return 0;
2893}
2894
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002895bool ASTUnit::isModuleFile() {
2896 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2897}
2898
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002899void ASTUnit::PreambleData::countLines() const {
2900 NumLines = 0;
2901 if (empty())
2902 return;
2903
2904 for (std::vector<char>::const_iterator
2905 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2906 if (*I == '\n')
2907 ++NumLines;
2908 }
2909 if (Buffer.back() != '\n')
2910 ++NumLines;
2911}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002912
2913#ifndef NDEBUG
2914ASTUnit::ConcurrencyState::ConcurrencyState() {
2915 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2916}
2917
2918ASTUnit::ConcurrencyState::~ConcurrencyState() {
2919 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2920}
2921
2922void ASTUnit::ConcurrencyState::start() {
2923 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2924 assert(acquired && "Concurrent access to ASTUnit!");
2925}
2926
2927void ASTUnit::ConcurrencyState::finish() {
2928 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2929}
2930
2931#else // NDEBUG
2932
2933ASTUnit::ConcurrencyState::ConcurrencyState() {}
2934ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2935void ASTUnit::ConcurrencyState::start() {}
2936void ASTUnit::ConcurrencyState::finish() {}
2937
2938#endif