blob: 8fe4baa5e301eeb5c98a13203f07a7e9c04faedd [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"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Serialization/ASTReader.h"
33#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000034#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000035#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000037#include "llvm/Support/Atomic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000039#include "llvm/Support/FileSystem.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000048#include <cstdlib>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000049#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor213f18b2010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek1872b312011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
86 /// \brief Temporary files that should be removed when the ASTUnit is
87 /// destroyed.
88 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
89
90 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000107
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 M.erase(AU);
155 }
156}
157
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
168 TemporaryFiles[I].eraseFromDisk();
169 TemporaryFiles.clear();
170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::Path(PreambleFile).eraseFromDisk();
175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
193 for (FileDeclsTy::iterator
194 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
195 delete I->second;
196 FileDecls.clear();
197}
198
Ted Kremenek1872b312011-10-27 17:55:18 +0000199void ASTUnit::CleanTemporaryFiles() {
200 getOnDiskData(this).CleanTemporaryFiles();
201}
202
203void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
204 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000205}
206
Douglas Gregoreababfb2010-08-04 05:53:38 +0000207/// \brief After failing to build a precompiled preamble (due to
208/// errors in the source that occurs in the preamble), the number of
209/// reparses during which we'll skip even trying to precompile the
210/// preamble.
211const unsigned DefaultPreambleRebuildInterval = 5;
212
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213/// \brief Tracks the number of ASTUnit objects that are currently active.
214///
215/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000216static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000217
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000218ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000219 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000220 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000221 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000222 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000223 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000224 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000225 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000226 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000227 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000228 CompletionCacheTopLevelHashValue(0),
229 PreambleTopLevelHashValue(0),
230 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000231 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000232 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000233 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000234 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
235 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000236}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000237
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000238ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000239 // If we loaded from an AST file, balance out the BeginSourceFile call.
240 if (MainFileIsAST && getDiagnostics().getClient()) {
241 getDiagnostics().getClient()->EndSourceFile();
242 }
243
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000244 clearFileLevelDecls();
245
Ted Kremenek1872b312011-10-27 17:55:18 +0000246 // Clean up the temporary files and the preamble file.
247 removeOnDiskEntry(this);
248
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 // Free the buffers associated with remapped files. We are required to
250 // perform this operation here because we explicitly request that the
251 // compiler instance *not* free these buffers for each invocation of the
252 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000253 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000254 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
255 for (PreprocessorOptions::remapped_file_buffer_iterator
256 FB = PPOpts.remapped_file_buffer_begin(),
257 FBEnd = PPOpts.remapped_file_buffer_end();
258 FB != FBEnd;
259 ++FB)
260 delete FB->second;
261 }
Douglas Gregor28233422010-07-27 14:52:07 +0000262
263 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000264 delete PreambleBuffer;
265
Douglas Gregor213f18b2010-10-28 15:44:59 +0000266 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000267
268 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000269 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000270 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
271 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000272}
273
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000274void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
275
Douglas Gregor8071e422010-08-15 06:18:01 +0000276/// \brief Determine the set of code-completion contexts in which this
277/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000278static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000279 const LangOptions &LangOpts,
280 bool &IsNestedNameSpecifier) {
281 IsNestedNameSpecifier = false;
282
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<UsingShadowDecl>(ND))
284 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
285 if (!ND)
286 return 0;
287
Richard Smith026b3582012-08-14 03:13:00 +0000288 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000289 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
290 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
291 // Types can appear in these contexts.
292 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
294 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
295 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
296 | (1LL << CodeCompletionContext::CCC_Statement)
297 | (1LL << CodeCompletionContext::CCC_Type)
298 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000299
300 // In C++, types can appear in expressions contexts (for functional casts).
301 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000303
304 // In Objective-C, message sends can send interfaces. In Objective-C++,
305 // all types are available due to functional casts.
306 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000307 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000308
309 // In Objective-C, you can only be a subclass of another Objective-C class
310 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000312
313 // Deal with tag names.
314 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000315 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000316
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000318 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000320 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000322 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 else
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000325
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000327 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000328 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
331 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
333 | (1LL << CodeCompletionContext::CCC_Expression)
334 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
335 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000337 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000338 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000342
343 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000344 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000345 }
346
347 return Contexts;
348}
349
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350void ASTUnit::CacheCodeCompletionResults() {
351 if (!TheSema)
352 return;
353
Douglas Gregor213f18b2010-10-28 15:44:59 +0000354 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000355 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356
357 // Clear out the previous results.
358 ClearCachedCompletionResults();
359
360 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000361 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000362 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000363 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000364 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000365 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000366 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000367
368 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
370
Douglas Gregor87c08a52010-08-13 22:48:40 +0000371 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
372 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000374 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000376 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000377 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000378 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000379 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000380 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000381 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000382 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000383 CachedResult.Priority = Results[I].Priority;
384 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000385 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000386
Douglas Gregorf5586f62010-08-16 18:08:11 +0000387 // Keep track of the type of this completion in an ASTContext-agnostic
388 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000389 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000390 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392 CachedResult.Type = 0;
393 } else {
394 CanQualType CanUsageType
395 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
396 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
397
398 // Determine whether we have already seen this type. If so, we save
399 // ourselves the work of formatting the type string by using the
400 // temporary, CanQualType-based hash table to find the associated value.
401 unsigned &TypeValue = CompletionTypes[CanUsageType];
402 if (TypeValue == 0) {
403 TypeValue = CompletionTypes.size();
404 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
405 = TypeValue;
406 }
407
408 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000409 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000410
Douglas Gregor8071e422010-08-15 06:18:01 +0000411 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000412
413 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000414 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
416 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000417 uint64_t NNSContexts
418 = (1LL << CodeCompletionContext::CCC_TopLevel)
419 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
420 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
421 | (1LL << CodeCompletionContext::CCC_Statement)
422 | (1LL << CodeCompletionContext::CCC_Expression)
423 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
424 | (1LL << CodeCompletionContext::CCC_EnumTag)
425 | (1LL << CodeCompletionContext::CCC_UnionTag)
426 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
427 | (1LL << CodeCompletionContext::CCC_Type)
428 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
429 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000430
431 if (isa<NamespaceDecl>(Results[I].Declaration) ||
432 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000433 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000434
435 if (unsigned RemainingContexts
436 = NNSContexts & ~CachedResult.ShowInContexts) {
437 // If there any contexts where this completion can be a
438 // nested-name-specifier but isn't already an option, create a
439 // nested-name-specifier completion.
440 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000441 CachedResult.Completion
442 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000443 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000444 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000445 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000446 CachedResult.ShowInContexts = RemainingContexts;
447 CachedResult.Priority = CCP_NestedNameSpecifier;
448 CachedResult.TypeClass = STC_Void;
449 CachedResult.Type = 0;
450 CachedCompletionResults.push_back(CachedResult);
451 }
452 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000453 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000454 }
455
Douglas Gregor87c08a52010-08-13 22:48:40 +0000456 case Result::RK_Keyword:
457 case Result::RK_Pattern:
458 // Ignore keywords and patterns; we don't care, since they are so
459 // easily regenerated.
460 break;
461
462 case Result::RK_Macro: {
463 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000464 CachedResult.Completion
465 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000466 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000467 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000468 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000469 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000470 = (1LL << CodeCompletionContext::CCC_TopLevel)
471 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
472 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
473 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
474 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
475 | (1LL << CodeCompletionContext::CCC_Statement)
476 | (1LL << CodeCompletionContext::CCC_Expression)
477 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
478 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
479 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
480 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
481 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000482
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedResult.Priority = Results[I].Priority;
484 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000485 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000486 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000487 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000488 CachedCompletionResults.push_back(CachedResult);
489 break;
490 }
491 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000493
494 // Save the current top-level hash value.
495 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000496}
497
498void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000499 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000500 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000501 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000502}
503
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504namespace {
505
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000506/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000508class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 LangOptions &LangOpt;
512 HeaderSearch &HSI;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000513 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000514 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000517 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000519 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000521 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000522 HeaderSearch &HSI,
523 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000524 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000525 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000526 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
527 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor43998902012-10-25 00:09:28 +0000528 Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000529 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000531 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000532 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000533 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000534 return false;
535
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000536 LangOpt = LangOpts;
537 InitializedLanguage = true;
538
539 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000540 return false;
541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000543 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000544 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000545 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000546 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000547 return false;
548
Douglas Gregor57016dd2012-10-16 23:40:58 +0000549 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000550 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
551 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000552
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000553 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 return false;
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000557 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000558 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000561 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000562 Counter = Value;
563 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000564
565private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000566 void updated() {
567 if (!Target || !InitializedLanguage)
568 return;
569
570 // Inform the target of the language options.
571 //
572 // FIXME: We shouldn't need to do this, the target should be immutable once
573 // created. This complexity should be lifted elsewhere.
574 Target->setForcedLangOptions(LangOpt);
575
576 // Initialize the preprocessor.
577 PP.Initialize(*Target);
578
579 // Initialize the ASTContext
580 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000581
582 // We didn't have access to the comment options when the ASTContext was
583 // constructed, so register them now.
584 Context.getCommentCommandTraits().registerCommentOptions(
585 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000586 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000587};
588
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000589 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000590class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000591 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000592 SourceManager *SourceMgr;
593
Douglas Gregora88084b2010-02-18 18:08:43 +0000594public:
David Blaikie26e7a902011-09-26 00:01:39 +0000595 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000596 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000597 : StoredDiags(StoredDiags), SourceMgr(0) { }
598
599 virtual void BeginSourceFile(const LangOptions &LangOpts,
600 const Preprocessor *PP = 0) {
601 if (PP)
602 SourceMgr = &PP->getSourceManager();
603 }
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 Gregora88084b2010-02-18 18:08:43 +0000607};
608
609/// \brief RAII object that optionally captures diagnostics, if
610/// there is no diagnostic client to capture them already.
611class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000612 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000613 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000614 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000615
616public:
David Blaikied6471f72011-09-25 23:23:43 +0000617 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000618 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000619 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000620 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000621 if (RequestCapture || Diags.getClient() == 0) {
622 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000623 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000624 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000625 }
626
627 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000628 if (Diags.getClient() == &Client) {
629 Diags.takeClient();
630 Diags.setClient(PreviousClient);
631 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000632 }
633};
634
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000635} // anonymous namespace
636
David Blaikie26e7a902011-09-26 00:01:39 +0000637void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000638 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000639 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000640 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000641
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000642 // Only record the diagnostic if it's part of the source manager we know
643 // about. This effectively drops diagnostics from modules we're building.
644 // FIXME: In the long run, ee don't want to drop source managers from modules.
645 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
646 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000647}
648
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000649ASTDeserializationListener *ASTUnit::getDeserializationListener() {
650 if (WriterData)
651 return &WriterData->Writer;
652 return 0;
653}
654
Chris Lattner5f9e2722011-07-23 10:55:15 +0000655llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000656 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000657 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000658 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000659}
660
Douglas Gregore47be3e2010-11-11 00:39:14 +0000661/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000662void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000663 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000664 ASTUnit &AST, bool CaptureDiagnostics) {
665 if (!Diags.getPtr()) {
666 // No diagnostics engine was provided, so create our own diagnostics object
667 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000668 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000669 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000670 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000671 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000672 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000673 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000675 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000676 }
677}
678
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000679ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000680 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000681 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000682 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000683 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000684 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000685 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000686 bool AllowPCHWithCompilerErrors,
687 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000688 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000689
690 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000691 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
692 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000693 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
694 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000695 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000696
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000697 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000698
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000699 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000700 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000701 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000702 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000703 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000704 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000705 AST->getFileManager(),
706 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000707 AST->HSOpts = new HeaderSearchOptions();
708
709 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
710 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000711 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000712 AST->ASTFileLangOpts,
713 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000714
Douglas Gregor4db64a42010-01-23 00:14:00 +0000715 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000716 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
717 if (const llvm::MemoryBuffer *
718 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
719 // Create the file entry for the file that we're mapping from.
720 const FileEntry *FromFile
721 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
722 memBuf->getBufferSize(),
723 0);
724 if (!FromFile) {
725 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
726 << RemappedFiles[I].first;
727 delete memBuf;
728 continue;
729 }
730
731 // Override the contents of the "from" file with the contents of
732 // the "to" file.
733 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
734
735 } else {
736 const char *fname = fileOrBuf.get<const char *>();
737 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
738 if (!ToFile) {
739 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
740 << RemappedFiles[I].first << fname;
741 continue;
742 }
743
744 // Create the file entry for the file that we're mapping from.
745 const FileEntry *FromFile
746 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
747 ToFile->getSize(),
748 0);
749 if (!FromFile) {
750 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
751 << RemappedFiles[I].first;
752 delete memBuf;
753 continue;
754 }
755
756 // Override the contents of the "from" file with the contents of
757 // the "to" file.
758 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000759 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000760 }
761
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000764 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000765 unsigned Counter;
766
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000767 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768
Douglas Gregor36a16492012-10-24 17:46:57 +0000769 AST->PP = new Preprocessor(new PreprocessorOptions(),
770 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000771 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
772 *AST,
773 /*IILookup=*/0,
774 /*OwnsHeaderSearch=*/false,
775 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000776 Preprocessor &PP = *AST->PP;
777
778 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
779 AST->getSourceManager(),
780 /*Target=*/0,
781 PP.getIdentifierTable(),
782 PP.getSelectorTable(),
783 PP.getBuiltinInfo(),
784 /* size_reserve = */0,
785 /*DelayInitialization=*/true);
786 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000787
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000788 bool disableValid = false;
789 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
790 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000791 Reader.reset(new ASTReader(PP, Context,
792 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000793 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000794 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000795
796 // Recover resources if we crash before exiting this method.
797 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
798 ReaderCleanup(Reader.get());
799
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000800 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000801 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000802 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000803 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000804
Douglas Gregor38295be2012-10-22 23:51:00 +0000805 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000806 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000807 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000808 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000810 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000811 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000812 case ASTReader::OutOfDate:
813 case ASTReader::VersionMismatch:
814 case ASTReader::ConfigurationMismatch:
815 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000816 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000817 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000820 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
821
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000822 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000824 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000825 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000826 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000827 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000828 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000829
830 // Unregister the cleanup for ASTReader. It will get cleaned up
831 // by the ASTUnit cleanup.
832 ReaderCleanup.unregister();
833
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000834 Context.setExternalSource(Source);
835
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000836 // Create an AST consumer, even though it isn't used.
837 AST->Consumer.reset(new ASTConsumer);
838
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000839 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000840 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
841 AST->TheSema->Initialize();
842 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000843 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000844
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000845 // Tell the diagnostic client that we have started a source file.
846 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000849}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000850
851namespace {
852
Douglas Gregor9b7db622011-02-16 18:16:54 +0000853/// \brief Preprocessor callback class that updates a hash value with the names
854/// of all macros that have been defined by the translation unit.
855class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
856 unsigned &Hash;
857
858public:
859 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
860
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000861 virtual void MacroDefined(const Token &MacroNameTok,
862 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000863 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
864 }
865};
866
867/// \brief Add the given declaration to the hash of all top-level entities.
868void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
869 if (!D)
870 return;
871
872 DeclContext *DC = D->getDeclContext();
873 if (!DC)
874 return;
875
876 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
877 return;
878
879 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
880 if (ND->getIdentifier())
881 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
882 else if (DeclarationName Name = ND->getDeclName()) {
883 std::string NameStr = Name.getAsString();
884 Hash = llvm::HashString(NameStr, Hash);
885 }
886 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000887 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000888}
889
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000890class TopLevelDeclTrackerConsumer : public ASTConsumer {
891 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000892 unsigned &Hash;
893
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000894public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000895 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
896 : Unit(_Unit), Hash(Hash) {
897 Hash = 0;
898 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000899
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000900 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000901 if (!D)
902 return;
903
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000904 // FIXME: Currently ObjC method declarations are incorrectly being
905 // reported as top-level declarations, even though their DeclContext
906 // is the containing ObjC @interface/@implementation. This is a
907 // fundamental problem in the parser right now.
908 if (isa<ObjCMethodDecl>(D))
909 return;
910
911 AddTopLevelDeclarationToHash(D, Hash);
912 Unit.addTopLevelDecl(D);
913
914 handleFileLevelDecl(D);
915 }
916
917 void handleFileLevelDecl(Decl *D) {
918 Unit.addFileLevelDecl(D);
919 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
920 for (NamespaceDecl::decl_iterator
921 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
922 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000923 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000924 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000925
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000926 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000927 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
928 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000929 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000930 }
931
Sebastian Redl27372b42010-08-11 18:52:41 +0000932 // We're not interested in "interesting" decls.
933 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000934
935 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
936 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
937 handleTopLevelDecl(*it);
938 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000939
940 virtual ASTDeserializationListener *GetASTDeserializationListener() {
941 return Unit.getDeserializationListener();
942 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000943};
944
945class TopLevelDeclTrackerAction : public ASTFrontendAction {
946public:
947 ASTUnit &Unit;
948
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000949 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000950 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000951 CI.getPreprocessor().addPPCallbacks(
952 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
953 return new TopLevelDeclTrackerConsumer(Unit,
954 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000955 }
956
957public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000958 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
959
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000960 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000961 virtual TranslationUnitKind getTranslationUnitKind() {
962 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000963 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000964};
965
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000966class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000967 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000968 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000969 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000970
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000971public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000972 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000973 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000974 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000975 Hash(Unit.getCurrentTopLevelHashValue()) {
976 Hash = 0;
977 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000978
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000979 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000980 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
981 Decl *D = *it;
982 // FIXME: Currently ObjC method declarations are incorrectly being
983 // reported as top-level declarations, even though their DeclContext
984 // is the containing ObjC @interface/@implementation. This is a
985 // fundamental problem in the parser right now.
986 if (isa<ObjCMethodDecl>(D))
987 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000988 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000989 TopLevelDecls.push_back(D);
990 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000991 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000992 }
993
994 virtual void HandleTranslationUnit(ASTContext &Ctx) {
995 PCHGenerator::HandleTranslationUnit(Ctx);
996 if (!Unit.getDiagnostics().hasErrorOccurred()) {
997 // Translate the top-level declarations we captured during
998 // parsing into declaration IDs in the precompiled
999 // preamble. This will allow us to deserialize those top-level
1000 // declarations when requested.
1001 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1002 Unit.addTopLevelDeclFromPreamble(
1003 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001004 }
1005 }
1006};
1007
1008class PrecompilePreambleAction : public ASTFrontendAction {
1009 ASTUnit &Unit;
1010
1011public:
1012 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1013
1014 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001015 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001016 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001017 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001018 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001019 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1020 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001021 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001022 return 0;
1023
Douglas Gregor832d6202011-07-22 16:35:34 +00001024 if (!CI.getFrontendOpts().RelocatablePCH)
1025 Sysroot.clear();
1026
Douglas Gregor9b7db622011-02-16 18:16:54 +00001027 CI.getPreprocessor().addPPCallbacks(
1028 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001029 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1030 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001031 }
1032
1033 virtual bool hasCodeCompletionSupport() const { return false; }
1034 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001035 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001036};
1037
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001038}
1039
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001040static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1041 StoredDiagnostics) {
1042 // Get rid of stored diagnostics except the ones from the driver which do not
1043 // have a source location.
1044 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1045 if (StoredDiagnostics[I].getLocation().isValid()) {
1046 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1047 --I;
1048 }
1049 }
1050}
1051
1052static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1053 StoredDiagnostics,
1054 SourceManager &SM) {
1055 // The stored diagnostic has the old source manager in it; update
1056 // the locations to refer into the new source manager. Since we've
1057 // been careful to make sure that the source manager's state
1058 // before and after are identical, so that we can reuse the source
1059 // location itself.
1060 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1061 if (StoredDiagnostics[I].getLocation().isValid()) {
1062 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1063 StoredDiagnostics[I].setLocation(Loc);
1064 }
1065 }
1066}
1067
Douglas Gregorabc563f2010-07-19 21:46:24 +00001068/// Parse the source file into a translation unit using the given compiler
1069/// invocation, replacing the current translation unit.
1070///
1071/// \returns True if a failure occurred that causes the ASTUnit not to
1072/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001073bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001074 delete SavedMainFileBuffer;
1075 SavedMainFileBuffer = 0;
1076
Ted Kremenek4f327862011-03-21 18:40:17 +00001077 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001078 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001079 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001080 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001081
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001082 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001083 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001084
1085 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001086 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1087 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001088
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001089 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001090 CCInvocation(new CompilerInvocation(*Invocation));
1091
1092 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001093 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001094
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001095 // Set up diagnostics, capturing any diagnostics that would
1096 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001097 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001098
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001099 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001100 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001101 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001102 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001103 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001104 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001105 }
1106
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001107 // Inform the target of the language options.
1108 //
1109 // FIXME: We shouldn't need to do this, the target should be immutable once
1110 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001111 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001112
Ted Kremenek03201fb2011-03-21 18:40:07 +00001113 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001114 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001115 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001116 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001117 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001118 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001119
Douglas Gregorabc563f2010-07-19 21:46:24 +00001120 // Configure the various subsystems.
1121 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001122 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001123 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001124 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001125 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1126 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001127 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001128 Ctx = 0;
1129 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001130 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001131
1132 // Clear out old caches and data.
1133 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001134 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001135 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001136
Douglas Gregorf128fed2010-08-20 00:02:33 +00001137 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001138 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001139 TopLevelDeclsInPreamble.clear();
1140 }
1141
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001142 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001143 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001144
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001145 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001146 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001147
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001148 // If the main file has been overridden due to the use of a preamble,
1149 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001150 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001151 if (OverrideMainBuffer) {
1152 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1153 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1154 PreprocessorOpts.PrecompiledPreambleBytes.second
1155 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001156 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001157 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001158
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001159 // The stored diagnostic has the old source manager in it; update
1160 // the locations to refer into the new source manager. Since we've
1161 // been careful to make sure that the source manager's state
1162 // before and after are identical, so that we can reuse the source
1163 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001164 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001165
1166 // Keep track of the override buffer;
1167 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001168 }
1169
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001170 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001171 new TopLevelDeclTrackerAction(*this));
1172
1173 // Recover resources if we crash before exiting this method.
1174 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1175 ActCleanup(Act.get());
1176
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001177 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001178 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001179
1180 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001181 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001182 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1183 getSourceManager(), PreambleDiagnostics,
1184 StoredDiagnostics);
1185 }
1186
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001187 if (!Act->Execute())
1188 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001189
1190 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001191
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001192 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001193
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001194 FailedParseDiagnostics.clear();
1195
Douglas Gregorabc563f2010-07-19 21:46:24 +00001196 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001197
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001198error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001199 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001200 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001201 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001202 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001203 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001204
1205 // Keep the ownership of the data in the ASTUnit because the client may
1206 // want to see the diagnostics.
1207 transferASTDataFromCompilerInstance(*Clang);
1208 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001209 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001210 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001211 return true;
1212}
1213
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214/// \brief Simple function to retrieve a path for a preamble precompiled header.
1215static std::string GetPreamblePCHPath() {
1216 // FIXME: This is lame; sys::Path should provide this function (in particular,
1217 // it should know how to find the temporary files dir).
1218 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001219 // FIXME: This is a hack so that we can override the preamble file during
1220 // crash-recovery testing, which is the only case where the preamble files
1221 // are not necessarily cleaned up.
1222 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1223 if (TmpFile)
1224 return TmpFile;
1225
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226 std::string Error;
1227 const char *TmpDir = ::getenv("TMPDIR");
1228 if (!TmpDir)
1229 TmpDir = ::getenv("TEMP");
1230 if (!TmpDir)
1231 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001232#ifdef LLVM_ON_WIN32
1233 if (!TmpDir)
1234 TmpDir = ::getenv("USERPROFILE");
1235#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 if (!TmpDir)
1237 TmpDir = "/tmp";
1238 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001239 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001240 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001241 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001242 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001243 return std::string();
1244
Douglas Gregor44c181a2010-07-23 00:33:23 +00001245 return P.str();
1246}
1247
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001248/// \brief Compute the preamble for the main file, providing the source buffer
1249/// that corresponds to the main file along with a pair (bytes, start-of-line)
1250/// that describes the preamble.
1251std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001252ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1253 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001254 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001255 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 CreatedBuffer = false;
1257
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 // Try to determine if the main file has been remapped, either from the
1259 // command line (to another file) or directly through the compiler invocation
1260 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001261 llvm::MemoryBuffer *Buffer = 0;
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001262 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1264 // Check whether there is a file-file remapping of the main file
1265 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001266 M = PreprocessorOpts.remapped_file_begin(),
1267 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 M != E;
1269 ++M) {
1270 llvm::sys::PathWithStatus MPath(M->first);
1271 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1272 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1273 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001274 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001275 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276 CreatedBuffer = false;
1277 }
1278
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001279 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001280 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001281 return std::make_pair((llvm::MemoryBuffer*)0,
1282 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001284 }
1285 }
1286 }
1287
1288 // Check whether there is a file-buffer remapping. It supercedes the
1289 // file-file remapping.
1290 for (PreprocessorOptions::remapped_file_buffer_iterator
1291 M = PreprocessorOpts.remapped_file_buffer_begin(),
1292 E = PreprocessorOpts.remapped_file_buffer_end();
1293 M != E;
1294 ++M) {
1295 llvm::sys::PathWithStatus MPath(M->first);
1296 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1297 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1298 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001299 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001300 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001301 CreatedBuffer = false;
1302 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001303
Douglas Gregor175c4a92010-07-23 23:58:40 +00001304 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001305 }
1306 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001307 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308 }
1309
1310 // If the main source file was not remapped, load it now.
1311 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001312 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001313 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001314 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001315
1316 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001317 }
1318
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001319 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001320 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001321 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001322}
1323
Douglas Gregor754f3492010-07-24 00:38:13 +00001324static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001325 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001326 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001327 llvm::MemoryBuffer *Result
1328 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1329 memcpy(const_cast<char*>(Result->getBufferStart()),
1330 Old->getBufferStart(), Old->getBufferSize());
1331 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001332 ' ', NewSize - Old->getBufferSize() - 1);
1333 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001334
Douglas Gregor754f3492010-07-24 00:38:13 +00001335 return Result;
1336}
1337
Douglas Gregor175c4a92010-07-23 23:58:40 +00001338/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1339/// the source file.
1340///
1341/// This routine will compute the preamble of the main source file. If a
1342/// non-trivial preamble is found, it will precompile that preamble into a
1343/// precompiled header so that the precompiled preamble can be used to reduce
1344/// reparsing time. If a precompiled preamble has already been constructed,
1345/// this routine will determine if it is still valid and, if so, avoid
1346/// rebuilding the precompiled preamble.
1347///
Douglas Gregordf95a132010-08-09 20:45:32 +00001348/// \param AllowRebuild When true (the default), this routine is
1349/// allowed to rebuild the precompiled preamble if it is found to be
1350/// out-of-date.
1351///
1352/// \param MaxLines When non-zero, the maximum number of lines that
1353/// can occur within the preamble.
1354///
Douglas Gregor754f3492010-07-24 00:38:13 +00001355/// \returns If the precompiled preamble can be used, returns a newly-allocated
1356/// buffer that should be used in place of the main file when doing so.
1357/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001358llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001359 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001360 bool AllowRebuild,
1361 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001362
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001363 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001364 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1365 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001366 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001367 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001368
1369 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001370 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001371 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001372
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001373 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001374 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001375 if (CreatedPreambleBuffer)
1376 OwnedPreambleBuffer.reset(NewPreamble.first);
1377
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001378 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001379 // We couldn't find a preamble in the main source. Clear out the current
1380 // preamble, if we have one. It's obviously no good any more.
1381 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001382 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001383
1384 // The next time we actually see a preamble, precompile it.
1385 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001386 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001387 }
1388
1389 if (!Preamble.empty()) {
1390 // We've previously computed a preamble. Check whether we have the same
1391 // preamble now that we did before, and that there's enough space in
1392 // the main-file buffer within the precompiled preamble to fit the
1393 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001394 if (Preamble.size() == NewPreamble.second.first &&
1395 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001396 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001397 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001398 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001399 // The preamble has not changed. We may be able to re-use the precompiled
1400 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001401
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001402 // Check that none of the files used by the preamble have changed.
1403 bool AnyFileChanged = false;
1404
1405 // First, make a record of those files that have been overridden via
1406 // remapping or unsaved_files.
1407 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1408 for (PreprocessorOptions::remapped_file_iterator
1409 R = PreprocessorOpts.remapped_file_begin(),
1410 REnd = PreprocessorOpts.remapped_file_end();
1411 !AnyFileChanged && R != REnd;
1412 ++R) {
1413 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001414 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001415 // If we can't stat the file we're remapping to, assume that something
1416 // horrible happened.
1417 AnyFileChanged = true;
1418 break;
1419 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001420
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001421 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1422 StatBuf.st_mtime);
1423 }
1424 for (PreprocessorOptions::remapped_file_buffer_iterator
1425 R = PreprocessorOpts.remapped_file_buffer_begin(),
1426 REnd = PreprocessorOpts.remapped_file_buffer_end();
1427 !AnyFileChanged && R != REnd;
1428 ++R) {
1429 // FIXME: Should we actually compare the contents of file->buffer
1430 // remappings?
1431 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1432 0);
1433 }
1434
1435 // Check whether anything has changed.
1436 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1437 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1438 !AnyFileChanged && F != FEnd;
1439 ++F) {
1440 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1441 = OverriddenFiles.find(F->first());
1442 if (Overridden != OverriddenFiles.end()) {
1443 // This file was remapped; check whether the newly-mapped file
1444 // matches up with the previous mapping.
1445 if (Overridden->second != F->second)
1446 AnyFileChanged = true;
1447 continue;
1448 }
1449
1450 // The file was not remapped; check whether it has changed on disk.
1451 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001452 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001453 // If we can't stat the file, assume that something horrible happened.
1454 AnyFileChanged = true;
1455 } else if (StatBuf.st_size != F->second.first ||
1456 StatBuf.st_mtime != F->second.second)
1457 AnyFileChanged = true;
1458 }
1459
1460 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001461 // Okay! We can re-use the precompiled preamble.
1462
1463 // Set the state of the diagnostic object to mimic its state
1464 // after parsing the preamble.
1465 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001466 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001467 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001468 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001469
1470 // Create a version of the main file buffer that is padded to
1471 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001472 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001473 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001474 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001475 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001476 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001477
1478 // If we aren't allowed to rebuild the precompiled preamble, just
1479 // return now.
1480 if (!AllowRebuild)
1481 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001482
Douglas Gregor175c4a92010-07-23 23:58:40 +00001483 // We can't reuse the previously-computed preamble. Build a new one.
1484 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001485 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001486 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001487 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001488 } else if (!AllowRebuild) {
1489 // We aren't allowed to rebuild the precompiled preamble; just
1490 // return now.
1491 return 0;
1492 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001493
1494 // If the preamble rebuild counter > 1, it's because we previously
1495 // failed to build a preamble and we're not yet ready to try
1496 // again. Decrement the counter and return a failure.
1497 if (PreambleRebuildCounter > 1) {
1498 --PreambleRebuildCounter;
1499 return 0;
1500 }
1501
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001502 // Create a temporary file for the precompiled preamble. In rare
1503 // circumstances, this can fail.
1504 std::string PreamblePCHPath = GetPreamblePCHPath();
1505 if (PreamblePCHPath.empty()) {
1506 // Try again next time.
1507 PreambleRebuildCounter = 1;
1508 return 0;
1509 }
1510
Douglas Gregor175c4a92010-07-23 23:58:40 +00001511 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001512 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001513 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001514
1515 // Create a new buffer that stores the preamble. The buffer also contains
1516 // extra space for the original contents of the file (which will be present
1517 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001518 // grows.
1519 PreambleReservedSize = NewPreamble.first->getBufferSize();
1520 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001521 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001523 PreambleReservedSize *= 2;
1524
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001525 // Save the preamble text for later; we'll need to compare against it for
1526 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001527 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001528 Preamble.assign(FileMgr->getFile(MainFilename),
1529 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001530 NewPreamble.first->getBufferStart()
1531 + NewPreamble.second.first);
1532 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1533
Douglas Gregor671947b2010-08-19 01:33:06 +00001534 delete PreambleBuffer;
1535 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001536 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001537 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001538 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001539 NewPreamble.first->getBufferStart(), Preamble.size());
1540 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001541 ' ', PreambleReservedSize - Preamble.size() - 1);
1542 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001543
1544 // Remap the main source file to the preamble buffer.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001545 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001546 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1547
1548 // Tell the compiler invocation to generate a temporary precompiled header.
1549 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001550 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001551 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001552 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1553 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001554
1555 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001556 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001557
1558 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001559 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1560 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001561
Douglas Gregor01b6e312011-07-01 18:22:13 +00001562 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001563 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001564
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001565 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001566 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001567
1568 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001569 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001570 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001571 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001572 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1573 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001574 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001575 PreprocessorOpts.eraseRemappedFile(
1576 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001577 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001578 }
1579
1580 // Inform the target of the language options.
1581 //
1582 // FIXME: We shouldn't need to do this, the target should be immutable once
1583 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001584 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001585
Ted Kremenek03201fb2011-03-21 18:40:07 +00001586 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001587 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001588 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001589 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001590 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001591 "IR inputs not support here!");
1592
1593 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001594 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001595 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001596 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001597 TopLevelDecls.clear();
1598 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001599
1600 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001601 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001602
1603 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001604 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001605 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001606
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001607 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001608 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001609 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001610 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1611 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001612 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001613 PreprocessorOpts.eraseRemappedFile(
1614 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001615 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001616 }
1617
1618 Act->Execute();
1619 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001620
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001621 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001622 // There were errors parsing the preamble, so no precompiled header was
1623 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001624 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001625 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1626 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001627 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001628 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001629 PreprocessorOpts.eraseRemappedFile(
1630 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001631 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001632 }
1633
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001634 // Transfer any diagnostics generated when parsing the preamble into the set
1635 // of preamble diagnostics.
1636 PreambleDiagnostics.clear();
1637 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001638 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001639 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001640
Douglas Gregor175c4a92010-07-23 23:58:40 +00001641 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001642 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001643 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001644
1645 // Keep track of all of the files that the source manager knows about,
1646 // so we can verify whether they have changed or not.
1647 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001648 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001649 const llvm::MemoryBuffer *MainFileBuffer
1650 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1651 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1652 FEnd = SourceMgr.fileinfo_end();
1653 F != FEnd;
1654 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001655 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001656 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1657 continue;
1658
1659 FilesInPreamble[File->getName()]
1660 = std::make_pair(F->second->getSize(), File->getModificationTime());
1661 }
1662
Douglas Gregoreababfb2010-08-04 05:53:38 +00001663 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001664 PreprocessorOpts.eraseRemappedFile(
1665 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001666
1667 // If the hash of top-level entities differs from the hash of the top-level
1668 // entities the last time we rebuilt the preamble, clear out the completion
1669 // cache.
1670 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1671 CompletionCacheTopLevelHashValue = 0;
1672 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1673 }
1674
Douglas Gregor754f3492010-07-24 00:38:13 +00001675 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001676 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001677 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001678}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001679
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001680void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1681 std::vector<Decl *> Resolved;
1682 Resolved.reserve(TopLevelDeclsInPreamble.size());
1683 ExternalASTSource &Source = *getASTContext().getExternalSource();
1684 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1685 // Resolve the declaration ID to an actual declaration, possibly
1686 // deserializing the declaration in the process.
1687 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1688 if (D)
1689 Resolved.push_back(D);
1690 }
1691 TopLevelDeclsInPreamble.clear();
1692 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1693}
1694
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001695void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1696 // Steal the created target, context, and preprocessor.
1697 TheSema.reset(CI.takeSema());
1698 Consumer.reset(CI.takeASTConsumer());
1699 Ctx = &CI.getASTContext();
1700 PP = &CI.getPreprocessor();
1701 CI.setSourceManager(0);
1702 CI.setFileManager(0);
1703 Target = &CI.getTarget();
1704 Reader = CI.getModuleManager();
1705}
1706
Chris Lattner5f9e2722011-07-23 10:55:15 +00001707StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001708 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1709 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1710 if (Input.isFile())
1711 return Input.getFile();
1712 else
1713 return Input.getBuffer()->getBufferIdentifier();
1714 }
1715
1716 if (SourceMgr) {
1717 if (const FileEntry *
1718 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1719 return FE->getName();
1720 }
1721
1722 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001723}
1724
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001725StringRef ASTUnit::getASTFileName() const {
1726 if (!isMainFileAST())
1727 return StringRef();
1728
1729 serialization::ModuleFile &
1730 Mod = Reader->getModuleManager().getPrimaryModule();
1731 return Mod.FileName;
1732}
1733
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001734ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001735 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001736 bool CaptureDiagnostics,
1737 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001738 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001739 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001740 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001741 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001742 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001743 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001744 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001745 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1746 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1747 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001748
1749 return AST.take();
1750}
1751
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001752ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001753 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001754 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001755 ASTUnit *Unit,
1756 bool Persistent,
1757 StringRef ResourceFilesPath,
1758 bool OnlyLocalDecls,
1759 bool CaptureDiagnostics,
1760 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001761 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001762 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001763 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001764 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765 assert(CI && "A CompilerInvocation is required");
1766
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001767 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001768 ASTUnit *AST = Unit;
1769 if (!AST) {
1770 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001771 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001772 AST = OwnAST.get();
1773 }
1774
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001775 if (!ResourceFilesPath.empty()) {
1776 // Override the resources path.
1777 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1778 }
1779 AST->OnlyLocalDecls = OnlyLocalDecls;
1780 AST->CaptureDiagnostics = CaptureDiagnostics;
1781 if (PrecompilePreamble)
1782 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001783 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001784 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001785 AST->IncludeBriefCommentsInCodeCompletion
1786 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001787
1788 // Recover resources if we crash before exiting this method.
1789 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001790 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001791 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1792 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001793 DiagCleanup(Diags.getPtr());
1794
1795 // We'll manage file buffers ourselves.
1796 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1797 CI->getFrontendOpts().DisableFree = false;
1798 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1799
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001800 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001801 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001802
1803 // Recover resources if we crash before exiting this method.
1804 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1805 CICleanup(Clang.get());
1806
1807 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001808 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001809
1810 // Set up diagnostics, capturing any diagnostics that would
1811 // otherwise be dropped.
1812 Clang->setDiagnostics(&AST->getDiagnostics());
1813
1814 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001815 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001816 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001817 if (!Clang->hasTarget())
1818 return 0;
1819
1820 // Inform the target of the language options.
1821 //
1822 // FIXME: We shouldn't need to do this, the target should be immutable once
1823 // created. This complexity should be lifted elsewhere.
1824 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1825
1826 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1827 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001828 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001829 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001830 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001831 "IR inputs not supported here!");
1832
1833 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001834 AST->TheSema.reset();
1835 AST->Ctx = 0;
1836 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001837 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001838
1839 // Create a file manager object to provide access to and cache the filesystem.
1840 Clang->setFileManager(&AST->getFileManager());
1841
1842 // Create the source manager.
1843 Clang->setSourceManager(&AST->getSourceManager());
1844
1845 ASTFrontendAction *Act = Action;
1846
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001847 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001848 if (!Act) {
1849 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1850 Act = TrackerAct.get();
1851 }
1852
1853 // Recover resources if we crash before exiting this method.
1854 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1855 ActCleanup(TrackerAct.get());
1856
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001857 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1858 AST->transferASTDataFromCompilerInstance(*Clang);
1859 if (OwnAST && ErrAST)
1860 ErrAST->swap(OwnAST);
1861
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001862 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001863 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001864
1865 if (Persistent && !TrackerAct) {
1866 Clang->getPreprocessor().addPPCallbacks(
1867 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1868 std::vector<ASTConsumer*> Consumers;
1869 if (Clang->hasASTConsumer())
1870 Consumers.push_back(Clang->takeASTConsumer());
1871 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1872 AST->getCurrentTopLevelHashValue()));
1873 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1874 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001875 if (!Act->Execute()) {
1876 AST->transferASTDataFromCompilerInstance(*Clang);
1877 if (OwnAST && ErrAST)
1878 ErrAST->swap(OwnAST);
1879
1880 return 0;
1881 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001882
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001883 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001884 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001885
1886 Act->EndSourceFile();
1887
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001888 if (OwnAST)
1889 return OwnAST.take();
1890 else
1891 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001892}
1893
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001894bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1895 if (!Invocation)
1896 return true;
1897
1898 // We'll manage file buffers ourselves.
1899 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1900 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001901 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001902
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001903 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001904 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001905 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001906 OverrideMainBuffer
1907 = getMainBufferWithPrecompiledPreamble(*Invocation);
1908 }
1909
Douglas Gregor213f18b2010-10-28 15:44:59 +00001910 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001911 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001912
Ted Kremenek25a11e12011-03-22 01:15:24 +00001913 // Recover resources if we crash before exiting this method.
1914 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1915 MemBufferCleanup(OverrideMainBuffer);
1916
Douglas Gregor213f18b2010-10-28 15:44:59 +00001917 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001918}
1919
Douglas Gregorabc563f2010-07-19 21:46:24 +00001920ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001921 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001922 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001923 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001924 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001925 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001926 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001927 bool IncludeBriefCommentsInCodeCompletion,
1928 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001929 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001930 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001931 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001932 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001933 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001934 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001935 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001936 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001937 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001938 AST->IncludeBriefCommentsInCodeCompletion
1939 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001940 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001941 AST->FileSystemOpts = CI->getFileSystemOpts();
1942 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001943 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001944
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001945 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001946 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1947 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001948 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1949 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001950 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001951
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001952 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001953}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001954
1955ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1956 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001957 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001958 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001959 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001960 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001961 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001962 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001963 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001964 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001965 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001966 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001967 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001968 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001969 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001970 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001971 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001972 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001973 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001974 // No diagnostics engine was provided, so create our own diagnostics object
1975 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001976 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001977 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001978
Chris Lattner5f9e2722011-07-23 10:55:15 +00001979 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001980
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001981 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001982
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001983 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001984
Douglas Gregore47be3e2010-11-11 00:39:14 +00001985 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001986 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001987
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001988 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001989 llvm::makeArrayRef(ArgBegin, ArgEnd),
1990 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001991 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001992 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001993 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001994
Douglas Gregor4db64a42010-01-23 00:14:00 +00001995 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001996 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1997 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1998 if (const llvm::MemoryBuffer *
1999 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2000 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2001 } else {
2002 const char *fname = fileOrBuf.get<const char *>();
2003 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2004 }
2005 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002006 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2007 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2008 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002009
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002010 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002011 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002012
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002013 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2014
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002015 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002016 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002017 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002018 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002019 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002020 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002021 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002022 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002023 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002024 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002025 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002026 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002027 AST->IncludeBriefCommentsInCodeCompletion
2028 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002029 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002030 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002031 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002032 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002033 if (ForSerialization)
2034 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002035 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002036
2037 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002038 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2039 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002040
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002041 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2042 // Some error occurred, if caller wants to examine diagnostics, pass it the
2043 // ASTUnit.
2044 if (ErrAST) {
2045 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2046 ErrAST->swap(AST);
2047 }
2048 return 0;
2049 }
2050
2051 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002052}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002053
2054bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002055 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002056 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002057
2058 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002059
Douglas Gregor213f18b2010-10-28 15:44:59 +00002060 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002061 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002062
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002063 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002064 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2065 for (PreprocessorOptions::remapped_file_buffer_iterator
2066 R = PPOpts.remapped_file_buffer_begin(),
2067 REnd = PPOpts.remapped_file_buffer_end();
2068 R != REnd;
2069 ++R) {
2070 delete R->second;
2071 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002072 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002073 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2074 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2075 if (const llvm::MemoryBuffer *
2076 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2077 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2078 memBuf);
2079 } else {
2080 const char *fname = fileOrBuf.get<const char *>();
2081 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2082 fname);
2083 }
2084 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002085
Douglas Gregoreababfb2010-08-04 05:53:38 +00002086 // If we have a preamble file lying around, or if we might try to
2087 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002088 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002089 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002090 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002091
Douglas Gregorabc563f2010-07-19 21:46:24 +00002092 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002093 getDiagnostics().Reset();
2094 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002095 if (OverrideMainBuffer)
2096 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002097
Douglas Gregor175c4a92010-07-23 23:58:40 +00002098 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002099 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002100
2101 // If we're caching global code-completion results, and the top-level
2102 // declarations have changed, clear out the code-completion cache.
2103 if (!Result && ShouldCacheCodeCompletionResults &&
2104 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2105 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002106
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002107 // We now need to clear out the completion info related to this translation
2108 // unit; it'll be recreated if necessary.
2109 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002110
Douglas Gregor175c4a92010-07-23 23:58:40 +00002111 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002112}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002113
Douglas Gregor87c08a52010-08-13 22:48:40 +00002114//----------------------------------------------------------------------------//
2115// Code completion
2116//----------------------------------------------------------------------------//
2117
2118namespace {
2119 /// \brief Code completion consumer that combines the cached code-completion
2120 /// results from an ASTUnit with the code-completion results provided to it,
2121 /// then passes the result on to
2122 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002123 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002124 ASTUnit &AST;
2125 CodeCompleteConsumer &Next;
2126
2127 public:
2128 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002129 const CodeCompleteOptions &CodeCompleteOpts)
2130 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2131 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002132 {
2133 // Compute the set of contexts in which we will look when we don't have
2134 // any information about the specific context.
2135 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002136 = (1LL << CodeCompletionContext::CCC_TopLevel)
2137 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2138 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2139 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2140 | (1LL << CodeCompletionContext::CCC_Statement)
2141 | (1LL << CodeCompletionContext::CCC_Expression)
2142 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2143 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2144 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2145 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2146 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2147 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2148 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002149
David Blaikie4e4d0842012-03-11 07:00:24 +00002150 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002151 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2152 | (1LL << CodeCompletionContext::CCC_UnionTag)
2153 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002154 }
2155
2156 virtual void ProcessCodeCompleteResults(Sema &S,
2157 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002158 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002159 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002160
2161 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2162 OverloadCandidate *Candidates,
2163 unsigned NumCandidates) {
2164 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2165 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002166
Douglas Gregordae68752011-02-01 22:57:45 +00002167 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002168 return Next.getAllocator();
2169 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002170
2171 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2172 return Next.getCodeCompletionTUInfo();
2173 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002174 };
2175}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002176
Douglas Gregor5f808c22010-08-16 21:18:39 +00002177/// \brief Helper function that computes which global names are hidden by the
2178/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002179static void CalculateHiddenNames(const CodeCompletionContext &Context,
2180 CodeCompletionResult *Results,
2181 unsigned NumResults,
2182 ASTContext &Ctx,
2183 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002184 bool OnlyTagNames = false;
2185 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002186 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002187 case CodeCompletionContext::CCC_TopLevel:
2188 case CodeCompletionContext::CCC_ObjCInterface:
2189 case CodeCompletionContext::CCC_ObjCImplementation:
2190 case CodeCompletionContext::CCC_ObjCIvarList:
2191 case CodeCompletionContext::CCC_ClassStructUnion:
2192 case CodeCompletionContext::CCC_Statement:
2193 case CodeCompletionContext::CCC_Expression:
2194 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002195 case CodeCompletionContext::CCC_DotMemberAccess:
2196 case CodeCompletionContext::CCC_ArrowMemberAccess:
2197 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002198 case CodeCompletionContext::CCC_Namespace:
2199 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002200 case CodeCompletionContext::CCC_Name:
2201 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002202 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002203 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002204 break;
2205
2206 case CodeCompletionContext::CCC_EnumTag:
2207 case CodeCompletionContext::CCC_UnionTag:
2208 case CodeCompletionContext::CCC_ClassOrStructTag:
2209 OnlyTagNames = true;
2210 break;
2211
2212 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002213 case CodeCompletionContext::CCC_MacroName:
2214 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002215 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002216 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002217 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002218 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002219 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002220 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002221 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002222 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2223 case CodeCompletionContext::CCC_ObjCClassMessage:
2224 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002225 // We're looking for nothing, or we're looking for names that cannot
2226 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002227 return;
2228 }
2229
John McCall0a2c5e22010-08-25 06:19:51 +00002230 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002231 for (unsigned I = 0; I != NumResults; ++I) {
2232 if (Results[I].Kind != Result::RK_Declaration)
2233 continue;
2234
2235 unsigned IDNS
2236 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2237
2238 bool Hiding = false;
2239 if (OnlyTagNames)
2240 Hiding = (IDNS & Decl::IDNS_Tag);
2241 else {
2242 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002243 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2244 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002245 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002246 HiddenIDNS |= Decl::IDNS_Tag;
2247 Hiding = (IDNS & HiddenIDNS);
2248 }
2249
2250 if (!Hiding)
2251 continue;
2252
2253 DeclarationName Name = Results[I].Declaration->getDeclName();
2254 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2255 HiddenNames.insert(Identifier->getName());
2256 else
2257 HiddenNames.insert(Name.getAsString());
2258 }
2259}
2260
2261
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002262void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2263 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002264 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002265 unsigned NumResults) {
2266 // Merge the results we were given with the results we cached.
2267 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002268 uint64_t InContexts =
2269 Context.getKind() == CodeCompletionContext::CCC_Recovery
2270 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002271 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002272 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002273 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002274 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002275 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002276 C = AST.cached_completion_begin(),
2277 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002278 C != CEnd; ++C) {
2279 // If the context we are in matches any of the contexts we are
2280 // interested in, we'll add this result.
2281 if ((C->ShowInContexts & InContexts) == 0)
2282 continue;
2283
2284 // If we haven't added any results previously, do so now.
2285 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002286 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2287 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002288 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2289 AddedResult = true;
2290 }
2291
Douglas Gregor5f808c22010-08-16 21:18:39 +00002292 // Determine whether this global completion result is hidden by a local
2293 // completion result. If so, skip it.
2294 if (C->Kind != CXCursor_MacroDefinition &&
2295 HiddenNames.count(C->Completion->getTypedText()))
2296 continue;
2297
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002298 // Adjust priority based on similar type classes.
2299 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002300 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 if (!Context.getPreferredType().isNull()) {
2302 if (C->Kind == CXCursor_MacroDefinition) {
2303 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002304 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002305 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002306 } else if (C->Type) {
2307 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002308 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002309 Context.getPreferredType().getUnqualifiedType());
2310 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2311 if (ExpectedSTC == C->TypeClass) {
2312 // We know this type is similar; check for an exact match.
2313 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002314 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002315 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002316 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002317 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2318 Priority /= CCF_ExactTypeMatch;
2319 else
2320 Priority /= CCF_SimilarTypeMatch;
2321 }
2322 }
2323 }
2324
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002325 // Adjust the completion string, if required.
2326 if (C->Kind == CXCursor_MacroDefinition &&
2327 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2328 // Create a new code-completion string that just contains the
2329 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002330 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2331 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002332 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002333 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002334 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002335 }
2336
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002337 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002338 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002339 }
2340
2341 // If we did not add any cached completion results, just forward the
2342 // results we were given to the next consumer.
2343 if (!AddedResult) {
2344 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2345 return;
2346 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002347
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002348 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2349 AllResults.size());
2350}
2351
2352
2353
Chris Lattner5f9e2722011-07-23 10:55:15 +00002354void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355 RemappedFile *RemappedFiles,
2356 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002357 bool IncludeMacros,
2358 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002359 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002360 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002361 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002362 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002363 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2364 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002365 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002366 return;
2367
Douglas Gregor213f18b2010-10-28 15:44:59 +00002368 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002369 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002370 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002371
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002372 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002373 CCInvocation(new CompilerInvocation(*Invocation));
2374
2375 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002376 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002377 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002378
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002379 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2380 CachedCompletionResults.empty();
2381 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2382 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2383 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2384
2385 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2386
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002387 FrontendOpts.CodeCompletionAt.FileName = File;
2388 FrontendOpts.CodeCompletionAt.Line = Line;
2389 FrontendOpts.CodeCompletionAt.Column = Column;
2390
2391 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002392 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002393
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002394 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002395
2396 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002397 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2398 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002399
Ted Kremenek4f327862011-03-21 18:40:17 +00002400 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002401 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002402
2403 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002404 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002405 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002406 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002407 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002408 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002409
2410 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002411 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002412 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002413 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002414 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002415 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416 }
2417
2418 // Inform the target of the language options.
2419 //
2420 // FIXME: We shouldn't need to do this, the target should be immutable once
2421 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002422 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002423
Ted Kremenek03201fb2011-03-21 18:40:07 +00002424 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002425 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002426 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002427 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002428 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002429 "IR inputs not support here!");
2430
2431
2432 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002433 Clang->setFileManager(&FileMgr);
2434 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002435
2436 // Remap files.
2437 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002438 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002439 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002440 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2441 if (const llvm::MemoryBuffer *
2442 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2443 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2444 OwnedBuffers.push_back(memBuf);
2445 } else {
2446 const char *fname = fileOrBuf.get<const char *>();
2447 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2448 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002449 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002450
Douglas Gregor87c08a52010-08-13 22:48:40 +00002451 // Use the code completion consumer we were given, but adding any cached
2452 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002453 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002454 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002455 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002456
Douglas Gregordf95a132010-08-09 20:45:32 +00002457 // If we have a precompiled preamble, try to use it. We only allow
2458 // the use of the precompiled preamble if we're if the completion
2459 // point is within the main file, after the end of the precompiled
2460 // preamble.
2461 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002462 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002463 using llvm::sys::FileStatus;
2464 llvm::sys::PathWithStatus CompleteFilePath(File);
2465 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2466 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2467 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002468 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2469 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002470 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002471 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002472 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002473 }
2474
2475 // If the main file has been overridden due to the use of a preamble,
2476 // make that override happen and introduce the preamble.
2477 if (OverrideMainBuffer) {
2478 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2479 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2480 PreprocessorOpts.PrecompiledPreambleBytes.second
2481 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002482 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002483 PreprocessorOpts.DisablePCHValidation = true;
2484
Douglas Gregor2283d792010-08-20 00:59:43 +00002485 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002486 } else {
2487 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2488 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002489 }
2490
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002491 // Disable the preprocessing record if modules are not enabled.
2492 if (!Clang->getLangOpts().Modules)
2493 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002494
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002495 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002496 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002497 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002498 Act->Execute();
2499 Act->EndSourceFile();
2500 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002501}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002502
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002503bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002504 // Write to a temporary file and later rename it to the actual file, to avoid
2505 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002506 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002507 TempPath = File;
2508 TempPath += "-%%%%%%%%";
2509 int fd;
2510 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2511 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002512 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002513
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002514 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2515 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002516 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002517
2518 serialize(Out);
2519 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002520 if (Out.has_error()) {
2521 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002522 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002523 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002524
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002525 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002526 bool exists;
2527 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002528 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002529 }
2530
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002531 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002532}
2533
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002534static bool serializeUnit(ASTWriter &Writer,
2535 SmallVectorImpl<char> &Buffer,
2536 Sema &S,
2537 bool hasErrors,
2538 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002539 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002540
2541 // Write the generated bitstream to "Out".
2542 if (!Buffer.empty())
2543 OS.write(Buffer.data(), Buffer.size());
2544
2545 return false;
2546}
2547
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002549 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002550
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002551 if (WriterData)
2552 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2553 getSema(), hasErrors, OS);
2554
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002555 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002556 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002557 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002558 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002559}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002560
2561typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2562
2563static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2564 unsigned Raw = L.getRawEncoding();
2565 const unsigned MacroBit = 1U << 31;
2566 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2567 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2568}
2569
2570void ASTUnit::TranslateStoredDiagnostics(
2571 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002573 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 const SmallVectorImpl<StoredDiagnostic> &Diags,
2575 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002576 // The stored diagnostic has the old source manager in it; update
2577 // the locations to refer into the new source manager. We also need to remap
2578 // all the locations to the new view. This includes the diag location, any
2579 // associated source ranges, and the source ranges of associated fix-its.
2580 // FIXME: There should be a cleaner way to do this.
2581
Chris Lattner5f9e2722011-07-23 10:55:15 +00002582 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002583 Result.reserve(Diags.size());
2584 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002585 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002586 assert(Mod && "Don't have preamble module");
2587 SLocRemap &Remap = Mod->SLocRemap;
2588 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2589 // Rebuild the StoredDiagnostic.
2590 const StoredDiagnostic &SD = Diags[I];
2591 SourceLocation L = SD.getLocation();
2592 TranslateSLoc(L, Remap);
2593 FullSourceLoc Loc(L, SrcMgr);
2594
Chris Lattner5f9e2722011-07-23 10:55:15 +00002595 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002596 Ranges.reserve(SD.range_size());
2597 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2598 E = SD.range_end();
2599 I != E; ++I) {
2600 SourceLocation BL = I->getBegin();
2601 TranslateSLoc(BL, Remap);
2602 SourceLocation EL = I->getEnd();
2603 TranslateSLoc(EL, Remap);
2604 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2605 }
2606
Chris Lattner5f9e2722011-07-23 10:55:15 +00002607 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002608 FixIts.reserve(SD.fixit_size());
2609 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2610 E = SD.fixit_end();
2611 I != E; ++I) {
2612 FixIts.push_back(FixItHint());
2613 FixItHint &FH = FixIts.back();
2614 FH.CodeToInsert = I->CodeToInsert;
2615 SourceLocation BL = I->RemoveRange.getBegin();
2616 TranslateSLoc(BL, Remap);
2617 SourceLocation EL = I->RemoveRange.getEnd();
2618 TranslateSLoc(EL, Remap);
2619 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2620 I->RemoveRange.isTokenRange());
2621 }
2622
2623 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2624 SD.getMessage(), Loc, Ranges, FixIts));
2625 }
2626 Result.swap(Out);
2627}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002628
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002629static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2630 std::pair<unsigned, Decl *> R) {
2631 return L.first < R.first;
2632}
2633
2634void ASTUnit::addFileLevelDecl(Decl *D) {
2635 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002636
2637 // We only care about local declarations.
2638 if (D->isFromASTFile())
2639 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002640
2641 SourceManager &SM = *SourceMgr;
2642 SourceLocation Loc = D->getLocation();
2643 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2644 return;
2645
2646 // We only keep track of the file-level declarations of each file.
2647 if (!D->getLexicalDeclContext()->isFileContext())
2648 return;
2649
2650 SourceLocation FileLoc = SM.getFileLoc(Loc);
2651 assert(SM.isLocalSourceLocation(FileLoc));
2652 FileID FID;
2653 unsigned Offset;
2654 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2655 if (FID.isInvalid())
2656 return;
2657
2658 LocDeclsTy *&Decls = FileDecls[FID];
2659 if (!Decls)
2660 Decls = new LocDeclsTy();
2661
2662 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2663
2664 if (Decls->empty() || Decls->back().first <= Offset) {
2665 Decls->push_back(LocDecl);
2666 return;
2667 }
2668
2669 LocDeclsTy::iterator
2670 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2671
2672 Decls->insert(I, LocDecl);
2673}
2674
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002675void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2676 SmallVectorImpl<Decl *> &Decls) {
2677 if (File.isInvalid())
2678 return;
2679
2680 if (SourceMgr->isLoadedFileID(File)) {
2681 assert(Ctx->getExternalSource() && "No external source!");
2682 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2683 Decls);
2684 }
2685
2686 FileDeclsTy::iterator I = FileDecls.find(File);
2687 if (I == FileDecls.end())
2688 return;
2689
2690 LocDeclsTy &LocDecls = *I->second;
2691 if (LocDecls.empty())
2692 return;
2693
2694 LocDeclsTy::iterator
2695 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2696 std::make_pair(Offset, (Decl*)0), compLocDecl);
2697 if (BeginIt != LocDecls.begin())
2698 --BeginIt;
2699
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002700 // If we are pointing at a top-level decl inside an objc container, we need
2701 // to backtrack until we find it otherwise we will fail to report that the
2702 // region overlaps with an objc container.
2703 while (BeginIt != LocDecls.begin() &&
2704 BeginIt->second->isTopLevelDeclInObjCContainer())
2705 --BeginIt;
2706
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002707 LocDeclsTy::iterator
2708 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2709 std::make_pair(Offset+Length, (Decl*)0),
2710 compLocDecl);
2711 if (EndIt != LocDecls.end())
2712 ++EndIt;
2713
2714 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2715 Decls.push_back(DIt->second);
2716}
2717
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002718SourceLocation ASTUnit::getLocation(const FileEntry *File,
2719 unsigned Line, unsigned Col) const {
2720 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002721 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002722 return SM.getMacroArgExpandedLocation(Loc);
2723}
2724
2725SourceLocation ASTUnit::getLocation(const FileEntry *File,
2726 unsigned Offset) const {
2727 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002728 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002729 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2730}
2731
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002732/// \brief If \arg Loc is a loaded location from the preamble, returns
2733/// the corresponding local location of the main file, otherwise it returns
2734/// \arg Loc.
2735SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2736 FileID PreambleID;
2737 if (SourceMgr)
2738 PreambleID = SourceMgr->getPreambleFileID();
2739
2740 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2741 return Loc;
2742
2743 unsigned Offs;
2744 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2745 SourceLocation FileLoc
2746 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2747 return FileLoc.getLocWithOffset(Offs);
2748 }
2749
2750 return Loc;
2751}
2752
2753/// \brief If \arg Loc is a local location of the main file but inside the
2754/// preamble chunk, returns the corresponding loaded location from the
2755/// preamble, otherwise it returns \arg Loc.
2756SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2757 FileID PreambleID;
2758 if (SourceMgr)
2759 PreambleID = SourceMgr->getPreambleFileID();
2760
2761 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2762 return Loc;
2763
2764 unsigned Offs;
2765 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2766 Offs < Preamble.size()) {
2767 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2768 return FileLoc.getLocWithOffset(Offs);
2769 }
2770
2771 return Loc;
2772}
2773
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002774bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2775 FileID FID;
2776 if (SourceMgr)
2777 FID = SourceMgr->getPreambleFileID();
2778
2779 if (Loc.isInvalid() || FID.isInvalid())
2780 return false;
2781
2782 return SourceMgr->isInFileID(Loc, FID);
2783}
2784
2785bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2786 FileID FID;
2787 if (SourceMgr)
2788 FID = SourceMgr->getMainFileID();
2789
2790 if (Loc.isInvalid() || FID.isInvalid())
2791 return false;
2792
2793 return SourceMgr->isInFileID(Loc, FID);
2794}
2795
2796SourceLocation ASTUnit::getEndOfPreambleFileID() {
2797 FileID FID;
2798 if (SourceMgr)
2799 FID = SourceMgr->getPreambleFileID();
2800
2801 if (FID.isInvalid())
2802 return SourceLocation();
2803
2804 return SourceMgr->getLocForEndOfFile(FID);
2805}
2806
2807SourceLocation ASTUnit::getStartOfMainFileID() {
2808 FileID FID;
2809 if (SourceMgr)
2810 FID = SourceMgr->getMainFileID();
2811
2812 if (FID.isInvalid())
2813 return SourceLocation();
2814
2815 return SourceMgr->getLocForStartOfFile(FID);
2816}
2817
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002818std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2819ASTUnit::getLocalPreprocessingEntities() const {
2820 if (isMainFileAST()) {
2821 serialization::ModuleFile &
2822 Mod = Reader->getModuleManager().getPrimaryModule();
2823 return Reader->getModulePreprocessedEntities(Mod);
2824 }
2825
2826 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2827 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2828
2829 return std::make_pair(PreprocessingRecord::iterator(),
2830 PreprocessingRecord::iterator());
2831}
2832
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002833bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002834 if (isMainFileAST()) {
2835 serialization::ModuleFile &
2836 Mod = Reader->getModuleManager().getPrimaryModule();
2837 ASTReader::ModuleDeclIterator MDI, MDE;
2838 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2839 for (; MDI != MDE; ++MDI) {
2840 if (!Fn(context, *MDI))
2841 return false;
2842 }
2843
2844 return true;
2845 }
2846
2847 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2848 TLEnd = top_level_end();
2849 TL != TLEnd; ++TL) {
2850 if (!Fn(context, *TL))
2851 return false;
2852 }
2853
2854 return true;
2855}
2856
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002857namespace {
2858struct PCHLocatorInfo {
2859 serialization::ModuleFile *Mod;
2860 PCHLocatorInfo() : Mod(0) {}
2861};
2862}
2863
2864static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2865 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2866 switch (M.Kind) {
2867 case serialization::MK_Module:
2868 return true; // skip dependencies.
2869 case serialization::MK_PCH:
2870 Info.Mod = &M;
2871 return true; // found it.
2872 case serialization::MK_Preamble:
2873 return false; // look in dependencies.
2874 case serialization::MK_MainFile:
2875 return false; // look in dependencies.
2876 }
2877
2878 return true;
2879}
2880
2881const FileEntry *ASTUnit::getPCHFile() {
2882 if (!Reader)
2883 return 0;
2884
2885 PCHLocatorInfo Info;
2886 Reader->getModuleManager().visit(PCHLocator, &Info);
2887 if (Info.Mod)
2888 return Info.Mod->File;
2889
2890 return 0;
2891}
2892
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002893bool ASTUnit::isModuleFile() {
2894 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2895}
2896
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002897void ASTUnit::PreambleData::countLines() const {
2898 NumLines = 0;
2899 if (empty())
2900 return;
2901
2902 for (std::vector<char>::const_iterator
2903 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2904 if (*I == '\n')
2905 ++NumLines;
2906 }
2907 if (Buffer.back() != '\n')
2908 ++NumLines;
2909}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002910
2911#ifndef NDEBUG
2912ASTUnit::ConcurrencyState::ConcurrencyState() {
2913 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2914}
2915
2916ASTUnit::ConcurrencyState::~ConcurrencyState() {
2917 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2918}
2919
2920void ASTUnit::ConcurrencyState::start() {
2921 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2922 assert(acquired && "Concurrent access to ASTUnit!");
2923}
2924
2925void ASTUnit::ConcurrencyState::finish() {
2926 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2927}
2928
2929#else // NDEBUG
2930
2931ASTUnit::ConcurrencyState::ConcurrencyState() {}
2932ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2933void ASTUnit::ConcurrencyState::start() {}
2934void ASTUnit::ConcurrencyState::finish() {}
2935
2936#endif