blob: c4f7596e0037b908df6eba83350ebd3f9a2240f5 [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"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0b5ca512013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.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"
Stephen Hines651f13c2014-04-23 16:59:28 -070047#include <atomic>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000049#include <cstdlib>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000050#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor213f18b2010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000061 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000065 }
66
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 }
71
Douglas Gregor213f18b2010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ted Kremenek1872b312011-10-27 17:55:18 +000082
83 struct OnDiskData {
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
86
Rafael Espindolab804cb32013-06-26 03:52:38 +000087 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek1872b312011-10-27 17:55:18 +000088 /// destroyed.
Rafael Espindolab804cb32013-06-26 03:52:38 +000089 SmallVector<std::string, 4> TemporaryFiles;
90
Ted Kremenek1872b312011-10-27 17:55:18 +000091 /// \brief Erase temporary files.
92 void CleanTemporaryFiles();
93
94 /// \brief Erase the preamble file.
95 void CleanPreambleFile();
96
97 /// \brief Erase temporary files and the preamble file.
98 void Cleanup();
99 };
100}
101
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000102static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
103 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
104 return M;
105}
106
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000108
109typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
110static OnDiskDataMap &getOnDiskDataMap() {
111 static OnDiskDataMap M;
112 static bool hasRegisteredAtExit = false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit = true;
115 atexit(cleanupOnDiskMapAtExit);
116 }
117 return M;
118}
119
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000123 OnDiskDataMap &M = getOnDiskDataMap();
124 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
127 I->second->Cleanup();
128 }
129}
130
131static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000132 // We require the mutex since we are modifying the structure of the
133 // DenseMap.
134 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000135 OnDiskDataMap &M = getOnDiskDataMap();
136 OnDiskData *&D = M[AU];
137 if (!D)
138 D = new OnDiskData();
139 return *D;
140}
141
142static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
144}
145
146static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000147 // We require the mutex since we are modifying the structure of the
148 // DenseMap.
149 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
152 if (I != M.end()) {
153 I->second->Cleanup();
154 delete I->second;
155 M.erase(AU);
156 }
157}
158
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000159static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000160 getOnDiskData(AU).PreambleFile = preambleFile;
161}
162
163static const std::string &getPreambleFile(const ASTUnit *AU) {
164 return getOnDiskData(AU).PreambleFile;
165}
166
167void OnDiskData::CleanTemporaryFiles() {
168 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolab804cb32013-06-26 03:52:38 +0000169 llvm::sys::fs::remove(TemporaryFiles[I]);
170 TemporaryFiles.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +0000171}
172
173void OnDiskData::CleanPreambleFile() {
174 if (!PreambleFile.empty()) {
Rafael Espindola85d28482013-06-26 04:02:37 +0000175 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek1872b312011-10-27 17:55:18 +0000176 PreambleFile.clear();
177 }
178}
179
180void OnDiskData::Cleanup() {
181 CleanTemporaryFiles();
182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000185struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
188 ASTWriter Writer;
189
190 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
191};
192
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000193void ASTUnit::clearFileLevelDecls() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700194 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000195}
196
Ted Kremenek1872b312011-10-27 17:55:18 +0000197void ASTUnit::CleanTemporaryFiles() {
198 getOnDiskData(this).CleanTemporaryFiles();
199}
200
Rafael Espindolab804cb32013-06-26 03:52:38 +0000201void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000202 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000203}
204
Douglas Gregoreababfb2010-08-04 05:53:38 +0000205/// \brief After failing to build a precompiled preamble (due to
206/// errors in the source that occurs in the preamble), the number of
207/// reparses during which we'll skip even trying to precompile the
208/// preamble.
209const unsigned DefaultPreambleRebuildInterval = 5;
210
Douglas Gregore3c60a72010-11-17 00:13:31 +0000211/// \brief Tracks the number of ASTUnit objects that are currently active.
212///
213/// Used for debugging purposes only.
Stephen Hines651f13c2014-04-23 16:59:28 -0700214static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000215
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000216ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +0000217 : Reader(0), HadModuleLoaderFatalFailure(false),
218 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000224 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700231 if (getenv("LIBCLANG_OBJTRACKING"))
232 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor385103b2010-07-30 20:58:08 +0000233}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000234
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000235ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000236 // If we loaded from an AST file, balance out the BeginSourceFile call.
237 if (MainFileIsAST && getDiagnostics().getClient()) {
238 getDiagnostics().getClient()->EndSourceFile();
239 }
240
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000241 clearFileLevelDecls();
242
Ted Kremenek1872b312011-10-27 17:55:18 +0000243 // Clean up the temporary files and the preamble file.
244 removeOnDiskEntry(this);
245
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000246 // Free the buffers associated with remapped files. We are required to
247 // perform this operation here because we explicitly request that the
248 // compiler instance *not* free these buffers for each invocation of the
249 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000250 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000251 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
252 for (PreprocessorOptions::remapped_file_buffer_iterator
253 FB = PPOpts.remapped_file_buffer_begin(),
254 FBEnd = PPOpts.remapped_file_buffer_end();
255 FB != FBEnd;
256 ++FB)
257 delete FB->second;
258 }
Douglas Gregor28233422010-07-27 14:52:07 +0000259
260 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000261 delete PreambleBuffer;
262
Douglas Gregor213f18b2010-10-28 15:44:59 +0000263 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000264
Stephen Hines651f13c2014-04-23 16:59:28 -0700265 if (getenv("LIBCLANG_OBJTRACKING"))
266 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000267}
268
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000269void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
270
Douglas Gregor8071e422010-08-15 06:18:01 +0000271/// \brief Determine the set of code-completion contexts in which this
272/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000273static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000274 const LangOptions &LangOpts,
275 bool &IsNestedNameSpecifier) {
276 IsNestedNameSpecifier = false;
277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278 if (isa<UsingShadowDecl>(ND))
279 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
280 if (!ND)
281 return 0;
282
Richard Smith026b3582012-08-14 03:13:00 +0000283 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000284 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
285 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
286 // Types can appear in these contexts.
287 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
289 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
290 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
291 | (1LL << CodeCompletionContext::CCC_Statement)
292 | (1LL << CodeCompletionContext::CCC_Type)
293 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000294
295 // In C++, types can appear in expressions contexts (for functional casts).
296 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // In Objective-C, message sends can send interfaces. In Objective-C++,
300 // all types are available due to functional casts.
301 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000303
304 // In Objective-C, you can only be a subclass of another Objective-C class
305 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000307
308 // Deal with tag names.
309 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000311
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000312 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000313 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000315 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000318 else
Richard Smith026b3582012-08-14 03:13:00 +0000319 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000320
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000322 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000323 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000324 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
326 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
328 | (1LL << CodeCompletionContext::CCC_Expression)
329 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
330 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000333 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000337
338 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000339 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 }
341
342 return Contexts;
343}
344
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345void ASTUnit::CacheCodeCompletionResults() {
346 if (!TheSema)
347 return;
348
Douglas Gregor213f18b2010-10-28 15:44:59 +0000349 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000350 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000351
352 // Clear out the previous results.
353 ClearCachedCompletionResults();
354
355 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000356 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000357 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000358 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000359 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000360 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000361 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000362
363 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000364 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
365
Douglas Gregor87c08a52010-08-13 22:48:40 +0000366 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
367 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000369 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000370 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000371 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000372 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000373 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000374 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000376 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000377 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000378 CachedResult.Priority = Results[I].Priority;
379 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000380 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000381
Douglas Gregorf5586f62010-08-16 18:08:11 +0000382 // Keep track of the type of this completion in an ASTContext-agnostic
383 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000384 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000385 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000386 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000387 CachedResult.Type = 0;
388 } else {
389 CanQualType CanUsageType
390 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
391 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
392
393 // Determine whether we have already seen this type. If so, we save
394 // ourselves the work of formatting the type string by using the
395 // temporary, CanQualType-based hash table to find the associated value.
396 unsigned &TypeValue = CompletionTypes[CanUsageType];
397 if (TypeValue == 0) {
398 TypeValue = CompletionTypes.size();
399 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
400 = TypeValue;
401 }
402
403 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000404 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000405
Douglas Gregor8071e422010-08-15 06:18:01 +0000406 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000407
408 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000410 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
411 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000412 uint64_t NNSContexts
413 = (1LL << CodeCompletionContext::CCC_TopLevel)
414 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
415 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
416 | (1LL << CodeCompletionContext::CCC_Statement)
417 | (1LL << CodeCompletionContext::CCC_Expression)
418 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
419 | (1LL << CodeCompletionContext::CCC_EnumTag)
420 | (1LL << CodeCompletionContext::CCC_UnionTag)
421 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
422 | (1LL << CodeCompletionContext::CCC_Type)
423 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
424 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000425
426 if (isa<NamespaceDecl>(Results[I].Declaration) ||
427 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000428 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000429
430 if (unsigned RemainingContexts
431 = NNSContexts & ~CachedResult.ShowInContexts) {
432 // If there any contexts where this completion can be a
433 // nested-name-specifier but isn't already an option, create a
434 // nested-name-specifier completion.
435 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000436 CachedResult.Completion
437 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000438 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000439 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000440 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000441 CachedResult.ShowInContexts = RemainingContexts;
442 CachedResult.Priority = CCP_NestedNameSpecifier;
443 CachedResult.TypeClass = STC_Void;
444 CachedResult.Type = 0;
445 CachedCompletionResults.push_back(CachedResult);
446 }
447 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000448 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000449 }
450
Douglas Gregor87c08a52010-08-13 22:48:40 +0000451 case Result::RK_Keyword:
452 case Result::RK_Pattern:
453 // Ignore keywords and patterns; we don't care, since they are so
454 // easily regenerated.
455 break;
456
457 case Result::RK_Macro: {
458 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000459 CachedResult.Completion
460 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000461 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000462 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000463 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000464 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000465 = (1LL << CodeCompletionContext::CCC_TopLevel)
466 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
467 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
468 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
469 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
470 | (1LL << CodeCompletionContext::CCC_Statement)
471 | (1LL << CodeCompletionContext::CCC_Expression)
472 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
473 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
474 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
475 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
476 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000477
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478 CachedResult.Priority = Results[I].Priority;
479 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000480 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000481 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000482 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedCompletionResults.push_back(CachedResult);
484 break;
485 }
486 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000487 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000488
489 // Save the current top-level hash value.
490 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000491}
492
493void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000494 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000495 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000496 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000497}
498
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499namespace {
500
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000501/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000503class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000504 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000505 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506 LangOptions &LangOpt;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000507 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000512public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000514 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 unsigned &Counter)
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000517 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000518 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000519 Counter(Counter),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000520 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Stephen Hines651f13c2014-04-23 16:59:28 -0700522 bool ReadLanguageOptions(const LangOptions &LangOpts,
523 bool Complain) override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000524 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000525 return false;
526
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000527 LangOpt = LangOpts;
528 InitializedLanguage = true;
529
530 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000531 return false;
532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Stephen Hines651f13c2014-04-23 16:59:28 -0700534 bool ReadTargetOptions(const TargetOptions &TargetOpts,
535 bool Complain) override {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000536 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000537 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000538 return false;
539
Douglas Gregor57016dd2012-10-16 23:40:58 +0000540 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000541 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
542 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000543
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000544 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000545 return false;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Stephen Hines651f13c2014-04-23 16:59:28 -0700548 void ReadCounter(const serialization::ModuleFile &M,
549 unsigned Value) override {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000550 Counter = Value;
551 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000552
553private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000554 void updated() {
555 if (!Target || !InitializedLanguage)
556 return;
557
558 // Inform the target of the language options.
559 //
560 // FIXME: We shouldn't need to do this, the target should be immutable once
561 // created. This complexity should be lifted elsewhere.
562 Target->setForcedLangOptions(LangOpt);
563
564 // Initialize the preprocessor.
565 PP.Initialize(*Target);
566
567 // Initialize the ASTContext
568 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000569
570 // We didn't have access to the comment options when the ASTContext was
571 // constructed, so register them now.
572 Context.getCommentCommandTraits().registerCommentOptions(
573 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000574 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000575};
576
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000577 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000578class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000580 SourceManager *SourceMgr;
581
Douglas Gregora88084b2010-02-18 18:08:43 +0000582public:
David Blaikie26e7a902011-09-26 00:01:39 +0000583 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000585 : StoredDiags(StoredDiags), SourceMgr(0) { }
586
Stephen Hines651f13c2014-04-23 16:59:28 -0700587 void BeginSourceFile(const LangOptions &LangOpts,
588 const Preprocessor *PP = 0) override {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000589 if (PP)
590 SourceMgr = &PP->getSourceManager();
591 }
592
Stephen Hines651f13c2014-04-23 16:59:28 -0700593 void HandleDiagnostic(DiagnosticsEngine::Level Level,
594 const Diagnostic &Info) override;
Douglas Gregora88084b2010-02-18 18:08:43 +0000595};
596
597/// \brief RAII object that optionally captures diagnostics, if
598/// there is no diagnostic client to capture them already.
599class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000600 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000601 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000602 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000603
604public:
David Blaikied6471f72011-09-25 23:23:43 +0000605 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000606 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000607 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000608 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000609 if (RequestCapture || Diags.getClient() == 0) {
610 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000611 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000612 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000613 }
614
615 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000616 if (Diags.getClient() == &Client) {
617 Diags.takeClient();
618 Diags.setClient(PreviousClient);
619 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000620 }
621};
622
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000623} // anonymous namespace
624
David Blaikie26e7a902011-09-26 00:01:39 +0000625void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000626 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000627 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000628 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000629
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000630 // Only record the diagnostic if it's part of the source manager we know
631 // about. This effectively drops diagnostics from modules we're building.
632 // FIXME: In the long run, ee don't want to drop source managers from modules.
633 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
634 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000635}
636
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000637ASTMutationListener *ASTUnit::getASTMutationListener() {
638 if (WriterData)
639 return &WriterData->Writer;
640 return 0;
641}
642
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000643ASTDeserializationListener *ASTUnit::getDeserializationListener() {
644 if (WriterData)
645 return &WriterData->Writer;
646 return 0;
647}
648
Chris Lattner5f9e2722011-07-23 10:55:15 +0000649llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000650 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000651 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000652 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000653}
654
Douglas Gregore47be3e2010-11-11 00:39:14 +0000655/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000656void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000657 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000658 ASTUnit &AST, bool CaptureDiagnostics) {
659 if (!Diags.getPtr()) {
660 // No diagnostics engine was provided, so create our own diagnostics object
661 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000662 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000663 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000664 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000665 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000666 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000667 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000668 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000669 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000670 }
671}
672
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000673ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000674 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000675 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000676 bool OnlyLocalDecls,
Stephen Hines651f13c2014-04-23 16:59:28 -0700677 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000678 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000679 bool AllowPCHWithCompilerErrors,
680 bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700681 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000682
683 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000684 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
685 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000686 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
687 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000688 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000689
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000690 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000691
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000692 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000693 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000694 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000695 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000696 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000697 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000698 AST->getFileManager(),
699 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000700 AST->HSOpts = new HeaderSearchOptions();
701
702 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimekee0cd372013-10-24 07:51:24 +0000703 AST->getSourceManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000704 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000705 AST->ASTFileLangOpts,
706 /*Target=*/0));
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000707
Stephen Hines651f13c2014-04-23 16:59:28 -0700708 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000709
Stephen Hines651f13c2014-04-23 16:59:28 -0700710 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
711 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
712
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000713 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000715 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000716 unsigned Counter;
717
Stephen Hines651f13c2014-04-23 16:59:28 -0700718 AST->PP = new Preprocessor(PPOpts,
Douglas Gregor36a16492012-10-24 17:46:57 +0000719 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000720 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
721 *AST,
722 /*IILookup=*/0,
723 /*OwnsHeaderSearch=*/false,
724 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000725 Preprocessor &PP = *AST->PP;
726
727 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
728 AST->getSourceManager(),
729 /*Target=*/0,
730 PP.getIdentifierTable(),
731 PP.getSelectorTable(),
732 PP.getBuiltinInfo(),
733 /* size_reserve = */0,
734 /*DelayInitialization=*/true);
735 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000736
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000737 bool disableValid = false;
738 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
739 disableValid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700740 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000741 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000742 /*DisableValidation=*/disableValid,
Stephen Hines651f13c2014-04-23 16:59:28 -0700743 AllowPCHWithCompilerErrors);
Ted Kremenek8c647de2011-05-04 23:27:12 +0000744
Stephen Hines651f13c2014-04-23 16:59:28 -0700745 AST->Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000746 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000747 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000748 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000749
Stephen Hines651f13c2014-04-23 16:59:28 -0700750 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000751 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000752 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000753 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000755 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000756 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000757 case ASTReader::OutOfDate:
758 case ASTReader::VersionMismatch:
759 case ASTReader::ConfigurationMismatch:
760 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000761 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Stephen Hines651f13c2014-04-23 16:59:28 -0700765 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000766
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000767 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000769 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000770 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000771 // AST file as needed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700772 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000773
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000774 // Create an AST consumer, even though it isn't used.
775 AST->Consumer.reset(new ASTConsumer);
776
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000777 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000778 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
779 AST->TheSema->Initialize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700780 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000781
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000782 // Tell the diagnostic client that we have started a source file.
783 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
784
Stephen Hines651f13c2014-04-23 16:59:28 -0700785 return AST.release();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000786}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000787
788namespace {
789
Douglas Gregor9b7db622011-02-16 18:16:54 +0000790/// \brief Preprocessor callback class that updates a hash value with the names
791/// of all macros that have been defined by the translation unit.
792class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
793 unsigned &Hash;
794
795public:
796 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Stephen Hines651f13c2014-04-23 16:59:28 -0700797
798 void MacroDefined(const Token &MacroNameTok,
799 const MacroDirective *MD) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000800 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
801 }
802};
803
804/// \brief Add the given declaration to the hash of all top-level entities.
805void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
806 if (!D)
807 return;
808
809 DeclContext *DC = D->getDeclContext();
810 if (!DC)
811 return;
812
813 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
814 return;
815
816 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000817 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
818 // For an unscoped enum include the enumerators in the hash since they
819 // enter the top-level namespace.
820 if (!EnumD->isScoped()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700821 for (const auto *EI : EnumD->enumerators()) {
822 if (EI->getIdentifier())
823 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000824 }
825 }
826 }
827
Douglas Gregor9b7db622011-02-16 18:16:54 +0000828 if (ND->getIdentifier())
829 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
830 else if (DeclarationName Name = ND->getDeclName()) {
831 std::string NameStr = Name.getAsString();
832 Hash = llvm::HashString(NameStr, Hash);
833 }
834 return;
Argyrios Kyrtzidis1f3ff6a2013-06-24 21:19:12 +0000835 }
836
837 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
838 if (Module *Mod = ImportD->getImportedModule()) {
839 std::string ModName = Mod->getFullModuleName();
840 Hash = llvm::HashString(ModName, Hash);
841 }
842 return;
843 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000844}
845
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000846class TopLevelDeclTrackerConsumer : public ASTConsumer {
847 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000848 unsigned &Hash;
849
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000850public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000851 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
852 : Unit(_Unit), Hash(Hash) {
853 Hash = 0;
854 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000855
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000856 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000857 if (!D)
858 return;
859
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000860 // FIXME: Currently ObjC method declarations are incorrectly being
861 // reported as top-level declarations, even though their DeclContext
862 // is the containing ObjC @interface/@implementation. This is a
863 // fundamental problem in the parser right now.
864 if (isa<ObjCMethodDecl>(D))
865 return;
866
867 AddTopLevelDeclarationToHash(D, Hash);
868 Unit.addTopLevelDecl(D);
869
870 handleFileLevelDecl(D);
871 }
872
873 void handleFileLevelDecl(Decl *D) {
874 Unit.addFileLevelDecl(D);
875 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700876 for (auto *I : NSD->decls())
877 handleFileLevelDecl(I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000878 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000879 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000880
Stephen Hines651f13c2014-04-23 16:59:28 -0700881 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000882 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
883 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000884 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000885 }
886
Sebastian Redl27372b42010-08-11 18:52:41 +0000887 // We're not interested in "interesting" decls.
Stephen Hines651f13c2014-04-23 16:59:28 -0700888 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000889
Stephen Hines651f13c2014-04-23 16:59:28 -0700890 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000891 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
892 handleTopLevelDecl(*it);
893 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000894
Stephen Hines651f13c2014-04-23 16:59:28 -0700895 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000896 return Unit.getASTMutationListener();
897 }
898
Stephen Hines651f13c2014-04-23 16:59:28 -0700899 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000900 return Unit.getDeserializationListener();
901 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000902};
903
904class TopLevelDeclTrackerAction : public ASTFrontendAction {
905public:
906 ASTUnit &Unit;
907
Stephen Hines651f13c2014-04-23 16:59:28 -0700908 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
909 StringRef InFile) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000910 CI.getPreprocessor().addPPCallbacks(
911 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
912 return new TopLevelDeclTrackerConsumer(Unit,
913 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000914 }
915
916public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000917 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
918
Stephen Hines651f13c2014-04-23 16:59:28 -0700919 bool hasCodeCompletionSupport() const override { return false; }
920 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor467dc882011-08-25 22:30:56 +0000921 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000922 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000923};
924
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000925class PrecompilePreambleAction : public ASTFrontendAction {
926 ASTUnit &Unit;
927 bool HasEmittedPreamblePCH;
928
929public:
930 explicit PrecompilePreambleAction(ASTUnit &Unit)
931 : Unit(Unit), HasEmittedPreamblePCH(false) {}
932
Stephen Hines651f13c2014-04-23 16:59:28 -0700933 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
934 StringRef InFile) override;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000935 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
936 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Stephen Hines651f13c2014-04-23 16:59:28 -0700937 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000938
Stephen Hines651f13c2014-04-23 16:59:28 -0700939 bool hasCodeCompletionSupport() const override { return false; }
940 bool hasASTFileSupport() const override { return false; }
941 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000942};
943
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000944class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000945 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000946 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000947 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000948 PrecompilePreambleAction *Action;
949
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000950public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000951 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
952 const Preprocessor &PP, StringRef isysroot,
953 raw_ostream *Out)
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +0000954 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000955 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000956 Hash = 0;
957 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000958
Stephen Hines651f13c2014-04-23 16:59:28 -0700959 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000960 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
961 Decl *D = *it;
962 // FIXME: Currently ObjC method declarations are incorrectly being
963 // reported as top-level declarations, even though their DeclContext
964 // is the containing ObjC @interface/@implementation. This is a
965 // fundamental problem in the parser right now.
966 if (isa<ObjCMethodDecl>(D))
967 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000968 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000969 TopLevelDecls.push_back(D);
970 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000971 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000972 }
973
Stephen Hines651f13c2014-04-23 16:59:28 -0700974 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000975 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +0000976 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000977 // Translate the top-level declarations we captured during
978 // parsing into declaration IDs in the precompiled
979 // preamble. This will allow us to deserialize those top-level
980 // declarations when requested.
Argyrios Kyrtzidis51e75ae2013-08-07 21:17:33 +0000981 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
982 Decl *D = TopLevelDecls[I];
983 // Invalid top-level decls may not have been serialized.
984 if (D->isInvalidDecl())
985 continue;
986 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
987 }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000988
989 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000990 }
991 }
992};
993
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000994}
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000995
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000996ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
997 StringRef InFile) {
998 std::string Sysroot;
999 std::string OutputFile;
1000 raw_ostream *OS = 0;
1001 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1002 OutputFile, OS))
1003 return 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001004
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001005 if (!CI.getFrontendOpts().RelocatablePCH)
1006 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +00001007
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001008 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1009 Unit.getCurrentTopLevelHashValue()));
1010 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1011 Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001012}
1013
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001014static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1015 return StoredDiag.getLocation().isValid();
1016}
1017
1018static void
1019checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001020 // Get rid of stored diagnostics except the ones from the driver which do not
1021 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001022 StoredDiags.erase(
1023 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1024 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001025}
1026
1027static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1028 StoredDiagnostics,
1029 SourceManager &SM) {
1030 // The stored diagnostic has the old source manager in it; update
1031 // the locations to refer into the new source manager. Since we've
1032 // been careful to make sure that the source manager's state
1033 // before and after are identical, so that we can reuse the source
1034 // location itself.
1035 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1036 if (StoredDiagnostics[I].getLocation().isValid()) {
1037 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1038 StoredDiagnostics[I].setLocation(Loc);
1039 }
1040 }
1041}
1042
Douglas Gregorabc563f2010-07-19 21:46:24 +00001043/// Parse the source file into a translation unit using the given compiler
1044/// invocation, replacing the current translation unit.
1045///
1046/// \returns True if a failure occurred that causes the ASTUnit not to
1047/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001048bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001049 delete SavedMainFileBuffer;
1050 SavedMainFileBuffer = 0;
1051
Ted Kremenek4f327862011-03-21 18:40:17 +00001052 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001053 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001054 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001055 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001056
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001057 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001058 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001059
1060 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001061 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1062 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001063
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001064 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001065 CCInvocation(new CompilerInvocation(*Invocation));
1066
1067 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001068 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001069
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001070 // Set up diagnostics, capturing any diagnostics that would
1071 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001072 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001073
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001074 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001075 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001076 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001077 if (!Clang->hasTarget()) {
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 }
1081
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001082 // Inform the target of the language options.
1083 //
1084 // FIXME: We shouldn't need to do this, the target should be immutable once
1085 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001086 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001087
Ted Kremenek03201fb2011-03-21 18:40:07 +00001088 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001089 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001090 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001091 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001092 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001093 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001094
Douglas Gregorabc563f2010-07-19 21:46:24 +00001095 // Configure the various subsystems.
1096 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001097 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001098 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001099 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001100 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1101 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001102 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001103 Ctx = 0;
1104 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001105 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001106
1107 // Clear out old caches and data.
1108 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001109 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001110 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001111
Douglas Gregorf128fed2010-08-20 00:02:33 +00001112 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001113 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001114 TopLevelDeclsInPreamble.clear();
1115 }
1116
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001117 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001118 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001119
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001120 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001121 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001122
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001123 // If the main file has been overridden due to the use of a preamble,
1124 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001125 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001126 if (OverrideMainBuffer) {
1127 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1128 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1129 PreprocessorOpts.PrecompiledPreambleBytes.second
1130 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001131 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001132 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001133
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001134 // The stored diagnostic has the old source manager in it; update
1135 // the locations to refer into the new source manager. Since we've
1136 // been careful to make sure that the source manager's state
1137 // before and after are identical, so that we can reuse the source
1138 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001139 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001140
1141 // Keep track of the override buffer;
1142 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001143 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001144
1145 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1146 new TopLevelDeclTrackerAction(*this));
1147
Ted Kremenek25a11e12011-03-22 01:15:24 +00001148 // Recover resources if we crash before exiting this method.
1149 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1150 ActCleanup(Act.get());
1151
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001152 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001153 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001154
1155 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001156 std::string ModName = getPreambleFile(this);
Stephen Hines651f13c2014-04-23 16:59:28 -07001157 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1158 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001159 }
1160
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001161 if (!Act->Execute())
1162 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001163
1164 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001165
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001166 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001167
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001168 FailedParseDiagnostics.clear();
1169
Douglas Gregorabc563f2010-07-19 21:46:24 +00001170 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001171
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001172error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001173 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001174 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001175 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001176 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001177 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001178
1179 // Keep the ownership of the data in the ASTUnit because the client may
1180 // want to see the diagnostics.
1181 transferASTDataFromCompilerInstance(*Clang);
1182 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001183 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001184 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001185 return true;
1186}
1187
Douglas Gregor44c181a2010-07-23 00:33:23 +00001188/// \brief Simple function to retrieve a path for a preamble precompiled header.
1189static std::string GetPreamblePCHPath() {
Douglas Gregor424668c2010-09-11 18:05:19 +00001190 // FIXME: This is a hack so that we can override the preamble file during
1191 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindola85d28482013-06-26 04:02:37 +00001192 // are not necessarily cleaned up.
Douglas Gregor424668c2010-09-11 18:05:19 +00001193 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1194 if (TmpFile)
1195 return TmpFile;
Rafael Espindola85d28482013-06-26 04:02:37 +00001196
1197 SmallString<128> Path;
Rafael Espindola1ec4a862013-07-05 20:00:06 +00001198 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindola85d28482013-06-26 04:02:37 +00001199
1200 return Path.str();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001201}
1202
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001203/// \brief Compute the preamble for the main file, providing the source buffer
1204/// that corresponds to the main file along with a pair (bytes, start-of-line)
1205/// that describes the preamble.
1206std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001207ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1208 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001209 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001210 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001211 CreatedBuffer = false;
1212
Douglas Gregor44c181a2010-07-23 00:33:23 +00001213 // Try to determine if the main file has been remapped, either from the
1214 // command line (to another file) or directly through the compiler invocation
1215 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001216 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindola105b2072013-06-18 19:40:07 +00001217 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola44888352013-07-29 21:26:52 +00001218 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001219 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220 // Check whether there is a file-file remapping of the main file
1221 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001222 M = PreprocessorOpts.remapped_file_begin(),
1223 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224 M != E;
1225 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001226 std::string MPath(M->first);
Rafael Espindola44888352013-07-29 21:26:52 +00001227 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001228 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001229 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001230 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001231 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001232 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001233 CreatedBuffer = false;
1234 }
1235
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001236 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001237 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001238 return std::make_pair((llvm::MemoryBuffer*)0,
1239 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001240 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241 }
1242 }
1243 }
1244
1245 // Check whether there is a file-buffer remapping. It supercedes the
1246 // file-file remapping.
1247 for (PreprocessorOptions::remapped_file_buffer_iterator
1248 M = PreprocessorOpts.remapped_file_buffer_begin(),
1249 E = PreprocessorOpts.remapped_file_buffer_end();
1250 M != E;
1251 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001252 std::string MPath(M->first);
Rafael Espindola44888352013-07-29 21:26:52 +00001253 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001254 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001255 if (MainFileID == MID) {
1256 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001257 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001259 CreatedBuffer = false;
1260 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261
Douglas Gregor175c4a92010-07-23 23:58:40 +00001262 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263 }
1264 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001265 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 }
1267
1268 // If the main source file was not remapped, load it now.
1269 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001270 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001271 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001272 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001273
1274 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001275 }
1276
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001277 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001278 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001279 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001280}
1281
Stephen Hines651f13c2014-04-23 16:59:28 -07001282ASTUnit::PreambleFileHash
1283ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1284 PreambleFileHash Result;
1285 Result.Size = Size;
1286 Result.ModTime = ModTime;
1287 memset(Result.MD5, 0, sizeof(Result.MD5));
Douglas Gregor754f3492010-07-24 00:38:13 +00001288 return Result;
1289}
1290
Stephen Hines651f13c2014-04-23 16:59:28 -07001291ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1292 const llvm::MemoryBuffer *Buffer) {
1293 PreambleFileHash Result;
1294 Result.Size = Buffer->getBufferSize();
1295 Result.ModTime = 0;
1296
1297 llvm::MD5 MD5Ctx;
1298 MD5Ctx.update(Buffer->getBuffer().data());
1299 MD5Ctx.final(Result.MD5);
1300
1301 return Result;
1302}
1303
1304namespace clang {
1305bool operator==(const ASTUnit::PreambleFileHash &LHS,
1306 const ASTUnit::PreambleFileHash &RHS) {
1307 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1308 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1309}
1310} // namespace clang
1311
1312static std::pair<unsigned, unsigned>
1313makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1314 const LangOptions &LangOpts) {
1315 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1316 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1317 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1318 return std::make_pair(Offset, EndOffset);
1319}
1320
1321static void makeStandaloneFixIt(const SourceManager &SM,
1322 const LangOptions &LangOpts,
1323 const FixItHint &InFix,
1324 ASTUnit::StandaloneFixIt &OutFix) {
1325 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1326 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1327 LangOpts);
1328 OutFix.CodeToInsert = InFix.CodeToInsert;
1329 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1330}
1331
1332static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1333 const StoredDiagnostic &InDiag,
1334 ASTUnit::StandaloneDiagnostic &OutDiag) {
1335 OutDiag.ID = InDiag.getID();
1336 OutDiag.Level = InDiag.getLevel();
1337 OutDiag.Message = InDiag.getMessage();
1338 OutDiag.LocOffset = 0;
1339 if (InDiag.getLocation().isInvalid())
1340 return;
1341 const SourceManager &SM = InDiag.getLocation().getManager();
1342 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1343 OutDiag.Filename = SM.getFilename(FileLoc);
1344 if (OutDiag.Filename.empty())
1345 return;
1346 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1347 for (StoredDiagnostic::range_iterator
1348 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1349 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1350 }
1351 for (StoredDiagnostic::fixit_iterator
1352 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1353 ASTUnit::StandaloneFixIt Fix;
1354 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1355 OutDiag.FixIts.push_back(Fix);
1356 }
1357}
1358
Douglas Gregor175c4a92010-07-23 23:58:40 +00001359/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1360/// the source file.
1361///
1362/// This routine will compute the preamble of the main source file. If a
1363/// non-trivial preamble is found, it will precompile that preamble into a
1364/// precompiled header so that the precompiled preamble can be used to reduce
1365/// reparsing time. If a precompiled preamble has already been constructed,
1366/// this routine will determine if it is still valid and, if so, avoid
1367/// rebuilding the precompiled preamble.
1368///
Douglas Gregordf95a132010-08-09 20:45:32 +00001369/// \param AllowRebuild When true (the default), this routine is
1370/// allowed to rebuild the precompiled preamble if it is found to be
1371/// out-of-date.
1372///
1373/// \param MaxLines When non-zero, the maximum number of lines that
1374/// can occur within the preamble.
1375///
Douglas Gregor754f3492010-07-24 00:38:13 +00001376/// \returns If the precompiled preamble can be used, returns a newly-allocated
1377/// buffer that should be used in place of the main file when doing so.
1378/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001379llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001380 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001381 bool AllowRebuild,
1382 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001383
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001384 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001385 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1386 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001387 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001388 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001389
1390 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001391 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001392 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001393
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001394 // If ComputePreamble() Take ownership of the preamble buffer.
Stephen Hines651f13c2014-04-23 16:59:28 -07001395 std::unique_ptr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001396 if (CreatedPreambleBuffer)
1397 OwnedPreambleBuffer.reset(NewPreamble.first);
1398
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001399 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001400 // We couldn't find a preamble in the main source. Clear out the current
1401 // preamble, if we have one. It's obviously no good any more.
1402 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001403 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001404
1405 // The next time we actually see a preamble, precompile it.
1406 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001407 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001408 }
1409
1410 if (!Preamble.empty()) {
1411 // We've previously computed a preamble. Check whether we have the same
1412 // preamble now that we did before, and that there's enough space in
1413 // the main-file buffer within the precompiled preamble to fit the
1414 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001415 if (Preamble.size() == NewPreamble.second.first &&
1416 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001417 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001418 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001419 // The preamble has not changed. We may be able to re-use the precompiled
1420 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001421
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001422 // Check that none of the files used by the preamble have changed.
1423 bool AnyFileChanged = false;
1424
1425 // First, make a record of those files that have been overridden via
1426 // remapping or unsaved_files.
Stephen Hines651f13c2014-04-23 16:59:28 -07001427 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001428 for (PreprocessorOptions::remapped_file_iterator
1429 R = PreprocessorOpts.remapped_file_begin(),
1430 REnd = PreprocessorOpts.remapped_file_end();
1431 !AnyFileChanged && R != REnd;
1432 ++R) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001433 vfs::Status Status;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001434 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001435 // If we can't stat the file we're remapping to, assume that something
1436 // horrible happened.
1437 AnyFileChanged = true;
1438 break;
1439 }
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001440
Stephen Hines651f13c2014-04-23 16:59:28 -07001441 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001442 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001443 }
1444 for (PreprocessorOptions::remapped_file_buffer_iterator
1445 R = PreprocessorOpts.remapped_file_buffer_begin(),
1446 REnd = PreprocessorOpts.remapped_file_buffer_end();
1447 !AnyFileChanged && R != REnd;
1448 ++R) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001449 OverriddenFiles[R->first] =
1450 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001451 }
1452
1453 // Check whether anything has changed.
Stephen Hines651f13c2014-04-23 16:59:28 -07001454 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001455 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1456 !AnyFileChanged && F != FEnd;
1457 ++F) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001458 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001459 = OverriddenFiles.find(F->first());
1460 if (Overridden != OverriddenFiles.end()) {
1461 // This file was remapped; check whether the newly-mapped file
1462 // matches up with the previous mapping.
1463 if (Overridden->second != F->second)
1464 AnyFileChanged = true;
1465 continue;
1466 }
1467
1468 // The file was not remapped; check whether it has changed on disk.
Stephen Hines651f13c2014-04-23 16:59:28 -07001469 vfs::Status Status;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001470 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001471 // If we can't stat the file, assume that something horrible happened.
1472 AnyFileChanged = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001473 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001474 Status.getLastModificationTime().toEpochTime() !=
Stephen Hines651f13c2014-04-23 16:59:28 -07001475 uint64_t(F->second.ModTime))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001476 AnyFileChanged = true;
1477 }
1478
1479 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001480 // Okay! We can re-use the precompiled preamble.
1481
1482 // Set the state of the diagnostic object to mimic its state
1483 // after parsing the preamble.
1484 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001485 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001486 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001487 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001488
Stephen Hines651f13c2014-04-23 16:59:28 -07001489 return llvm::MemoryBuffer::getMemBufferCopy(
1490 NewPreamble.first->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001491 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001492 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001493
1494 // If we aren't allowed to rebuild the precompiled preamble, just
1495 // return now.
1496 if (!AllowRebuild)
1497 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001498
Douglas Gregor175c4a92010-07-23 23:58:40 +00001499 // We can't reuse the previously-computed preamble. Build a new one.
1500 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001501 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001502 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001503 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001504 } else if (!AllowRebuild) {
1505 // We aren't allowed to rebuild the precompiled preamble; just
1506 // return now.
1507 return 0;
1508 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001509
1510 // If the preamble rebuild counter > 1, it's because we previously
1511 // failed to build a preamble and we're not yet ready to try
1512 // again. Decrement the counter and return a failure.
1513 if (PreambleRebuildCounter > 1) {
1514 --PreambleRebuildCounter;
1515 return 0;
1516 }
1517
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001518 // Create a temporary file for the precompiled preamble. In rare
1519 // circumstances, this can fail.
1520 std::string PreamblePCHPath = GetPreamblePCHPath();
1521 if (PreamblePCHPath.empty()) {
1522 // Try again next time.
1523 PreambleRebuildCounter = 1;
1524 return 0;
1525 }
1526
Douglas Gregor175c4a92010-07-23 23:58:40 +00001527 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001528 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001529 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor175c4a92010-07-23 23:58:40 +00001530
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001531 // Save the preamble text for later; we'll need to compare against it for
1532 // subsequent reparses.
Stephen Hines651f13c2014-04-23 16:59:28 -07001533 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001534 Preamble.assign(FileMgr->getFile(MainFilename),
1535 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001536 NewPreamble.first->getBufferStart()
1537 + NewPreamble.second.first);
1538 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1539
Douglas Gregor671947b2010-08-19 01:33:06 +00001540 delete PreambleBuffer;
1541 PreambleBuffer
Stephen Hines651f13c2014-04-23 16:59:28 -07001542 = llvm::MemoryBuffer::getMemBufferCopy(
1543 NewPreamble.first->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001544
Douglas Gregor44c181a2010-07-23 00:33:23 +00001545 // Remap the main source file to the preamble buffer.
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001546 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1547 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1548
Douglas Gregor44c181a2010-07-23 00:33:23 +00001549 // Tell the compiler invocation to generate a temporary precompiled header.
1550 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001551 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001552 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001553 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1554 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001555
1556 // Create the compiler instance to use for building the precompiled preamble.
Stephen Hines651f13c2014-04-23 16:59:28 -07001557 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001558
1559 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001560 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1561 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001562
Douglas Gregor01b6e312011-07-01 18:22:13 +00001563 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001564 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001565
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001566 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001567 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001568
1569 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001570 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001571 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001572 if (!Clang->hasTarget()) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001573 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001574 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001575 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001576 PreprocessorOpts.eraseRemappedFile(
1577 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001578 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579 }
1580
1581 // Inform the target of the language options.
1582 //
1583 // FIXME: We shouldn't need to do this, the target should be immutable once
1584 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001585 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001586
Ted Kremenek03201fb2011-03-21 18:40:07 +00001587 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001588 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001589 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001591 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001592 "IR inputs not support here!");
1593
1594 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001595 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001596 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001597 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001598 TopLevelDecls.clear();
1599 TopLevelDeclsInPreamble.clear();
Stephen Hines651f13c2014-04-23 16:59:28 -07001600 PreambleDiagnostics.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001601
1602 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001603 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001604
1605 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001606 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001607 Clang->getFileManager()));
Stephen Hines651f13c2014-04-23 16:59:28 -07001608
1609 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001610 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001611 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001612 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001613 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001614 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001615 PreprocessorOpts.eraseRemappedFile(
1616 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001617 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001618 }
1619
1620 Act->Execute();
Stephen Hines651f13c2014-04-23 16:59:28 -07001621
1622 // Transfer any diagnostics generated when parsing the preamble into the set
1623 // of preamble diagnostics.
1624 for (stored_diag_iterator
1625 I = stored_diag_afterDriver_begin(),
1626 E = stored_diag_end(); I != E; ++I) {
1627 StandaloneDiagnostic Diag;
1628 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1629 PreambleDiagnostics.push_back(Diag);
1630 }
1631
Douglas Gregor44c181a2010-07-23 00:33:23 +00001632 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001633
Stephen Hines651f13c2014-04-23 16:59:28 -07001634 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1635
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001636 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001637 // The preamble PCH failed (e.g. there was a module loading fatal error),
1638 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001639 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindola21b18242013-06-26 04:26:38 +00001640 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001641 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001642 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001643 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001644 PreprocessorOpts.eraseRemappedFile(
1645 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001646 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001647 }
1648
1649 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001650 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001651 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001652
1653 // Keep track of all of the files that the source manager knows about,
1654 // so we can verify whether they have changed or not.
1655 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001656 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001657 const llvm::MemoryBuffer *MainFileBuffer
1658 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1659 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1660 FEnd = SourceMgr.fileinfo_end();
1661 F != FEnd;
1662 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001663 const FileEntry *File = F->second->OrigEntry;
Stephen Hines651f13c2014-04-23 16:59:28 -07001664 if (!File)
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001665 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001666 const llvm::MemoryBuffer *Buffer = F->second->getRawBuffer();
1667 if (Buffer == MainFileBuffer)
1668 continue;
1669
1670 if (time_t ModTime = File->getModificationTime()) {
1671 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1672 F->second->getSize(), ModTime);
1673 } else {
1674 assert(F->second->getSize() == Buffer->getBufferSize());
1675 FilesInPreamble[File->getName()] =
1676 PreambleFileHash::createForMemoryBuffer(Buffer);
1677 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001678 }
1679
Douglas Gregoreababfb2010-08-04 05:53:38 +00001680 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001681 PreprocessorOpts.eraseRemappedFile(
1682 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001683
1684 // If the hash of top-level entities differs from the hash of the top-level
1685 // entities the last time we rebuilt the preamble, clear out the completion
1686 // cache.
1687 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1688 CompletionCacheTopLevelHashValue = 0;
1689 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1690 }
1691
Stephen Hines651f13c2014-04-23 16:59:28 -07001692 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.first->getBuffer(),
1693 MainFilename);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001694}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001695
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001696void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1697 std::vector<Decl *> Resolved;
1698 Resolved.reserve(TopLevelDeclsInPreamble.size());
1699 ExternalASTSource &Source = *getASTContext().getExternalSource();
1700 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1701 // Resolve the declaration ID to an actual declaration, possibly
1702 // deserializing the declaration in the process.
1703 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1704 if (D)
1705 Resolved.push_back(D);
1706 }
1707 TopLevelDeclsInPreamble.clear();
1708 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1709}
1710
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001711void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1712 // Steal the created target, context, and preprocessor.
1713 TheSema.reset(CI.takeSema());
1714 Consumer.reset(CI.takeASTConsumer());
1715 Ctx = &CI.getASTContext();
1716 PP = &CI.getPreprocessor();
1717 CI.setSourceManager(0);
1718 CI.setFileManager(0);
1719 Target = &CI.getTarget();
1720 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001721 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001722}
1723
Chris Lattner5f9e2722011-07-23 10:55:15 +00001724StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001725 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1726 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1727 if (Input.isFile())
1728 return Input.getFile();
1729 else
1730 return Input.getBuffer()->getBufferIdentifier();
1731 }
1732
1733 if (SourceMgr) {
1734 if (const FileEntry *
1735 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1736 return FE->getName();
1737 }
1738
1739 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001740}
1741
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001742StringRef ASTUnit::getASTFileName() const {
1743 if (!isMainFileAST())
1744 return StringRef();
1745
1746 serialization::ModuleFile &
1747 Mod = Reader->getModuleManager().getPrimaryModule();
1748 return Mod.FileName;
1749}
1750
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001751ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001752 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001753 bool CaptureDiagnostics,
1754 bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001755 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001756 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001757 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001758 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001759 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001760 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001761 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001762 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1763 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1764 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001765
Stephen Hines651f13c2014-04-23 16:59:28 -07001766 return AST.release();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001767}
1768
Stephen Hines651f13c2014-04-23 16:59:28 -07001769ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1770 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1771 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1772 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1773 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1774 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1775 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001776 assert(CI && "A CompilerInvocation is required");
1777
Stephen Hines651f13c2014-04-23 16:59:28 -07001778 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001779 ASTUnit *AST = Unit;
1780 if (!AST) {
1781 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001782 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001783 AST = OwnAST.get();
1784 }
1785
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001786 if (!ResourceFilesPath.empty()) {
1787 // Override the resources path.
1788 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1789 }
1790 AST->OnlyLocalDecls = OnlyLocalDecls;
1791 AST->CaptureDiagnostics = CaptureDiagnostics;
1792 if (PrecompilePreamble)
1793 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001794 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001795 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001796 AST->IncludeBriefCommentsInCodeCompletion
1797 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001798
1799 // Recover resources if we crash before exiting this method.
1800 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001801 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001802 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1803 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001804 DiagCleanup(Diags.getPtr());
1805
1806 // We'll manage file buffers ourselves.
1807 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1808 CI->getFrontendOpts().DisableFree = false;
1809 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1810
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001811 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001812 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813
1814 // Recover resources if we crash before exiting this method.
1815 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1816 CICleanup(Clang.get());
1817
1818 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001819 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001820
1821 // Set up diagnostics, capturing any diagnostics that would
1822 // otherwise be dropped.
1823 Clang->setDiagnostics(&AST->getDiagnostics());
1824
1825 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001826 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001827 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001828 if (!Clang->hasTarget())
1829 return 0;
1830
1831 // Inform the target of the language options.
1832 //
1833 // FIXME: We shouldn't need to do this, the target should be immutable once
1834 // created. This complexity should be lifted elsewhere.
1835 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1836
1837 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1838 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001839 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001840 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001841 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001842 "IR inputs not supported here!");
1843
1844 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001845 AST->TheSema.reset();
1846 AST->Ctx = 0;
1847 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001848 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001849
1850 // Create a file manager object to provide access to and cache the filesystem.
1851 Clang->setFileManager(&AST->getFileManager());
1852
1853 // Create the source manager.
1854 Clang->setSourceManager(&AST->getSourceManager());
1855
1856 ASTFrontendAction *Act = Action;
1857
Stephen Hines651f13c2014-04-23 16:59:28 -07001858 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001859 if (!Act) {
1860 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1861 Act = TrackerAct.get();
1862 }
1863
1864 // Recover resources if we crash before exiting this method.
1865 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1866 ActCleanup(TrackerAct.get());
1867
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001868 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1869 AST->transferASTDataFromCompilerInstance(*Clang);
1870 if (OwnAST && ErrAST)
1871 ErrAST->swap(OwnAST);
1872
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001873 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001874 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001875
1876 if (Persistent && !TrackerAct) {
1877 Clang->getPreprocessor().addPPCallbacks(
1878 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1879 std::vector<ASTConsumer*> Consumers;
1880 if (Clang->hasASTConsumer())
1881 Consumers.push_back(Clang->takeASTConsumer());
1882 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1883 AST->getCurrentTopLevelHashValue()));
1884 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1885 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001886 if (!Act->Execute()) {
1887 AST->transferASTDataFromCompilerInstance(*Clang);
1888 if (OwnAST && ErrAST)
1889 ErrAST->swap(OwnAST);
1890
1891 return 0;
1892 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001893
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001894 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001895 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001896
1897 Act->EndSourceFile();
1898
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001899 if (OwnAST)
Stephen Hines651f13c2014-04-23 16:59:28 -07001900 return OwnAST.release();
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001901 else
1902 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001903}
1904
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001905bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1906 if (!Invocation)
1907 return true;
1908
1909 // We'll manage file buffers ourselves.
1910 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1911 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001912 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001913
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001914 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001915 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001916 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001917 OverrideMainBuffer
1918 = getMainBufferWithPrecompiledPreamble(*Invocation);
1919 }
1920
Douglas Gregor213f18b2010-10-28 15:44:59 +00001921 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001922 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001923
Ted Kremenek25a11e12011-03-22 01:15:24 +00001924 // Recover resources if we crash before exiting this method.
1925 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1926 MemBufferCleanup(OverrideMainBuffer);
1927
Douglas Gregor213f18b2010-10-28 15:44:59 +00001928 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001929}
1930
Douglas Gregorabc563f2010-07-19 21:46:24 +00001931ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001932 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001933 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001934 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001935 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001936 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001937 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001938 bool IncludeBriefCommentsInCodeCompletion,
1939 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001940 // Create the AST unit.
Stephen Hines651f13c2014-04-23 16:59:28 -07001941 std::unique_ptr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001942 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001943 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001944 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001945 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001946 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001947 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001948 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001949 AST->IncludeBriefCommentsInCodeCompletion
1950 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001951 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001952 AST->FileSystemOpts = CI->getFileSystemOpts();
1953 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001954 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001955
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001956 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001957 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1958 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001959 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1960 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001961 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001962
Stephen Hines651f13c2014-04-23 16:59:28 -07001963 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0
1964 : AST.release();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001965}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001966
Stephen Hines651f13c2014-04-23 16:59:28 -07001967ASTUnit *ASTUnit::LoadFromCommandLine(
1968 const char **ArgBegin, const char **ArgEnd,
1969 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1970 bool OnlyLocalDecls, bool CaptureDiagnostics,
1971 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1972 bool PrecompilePreamble, TranslationUnitKind TUKind,
1973 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1974 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1975 bool UserFilesAreVolatile, bool ForSerialization,
1976 std::unique_ptr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001977 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001978 // No diagnostics engine was provided, so create our own diagnostics object
1979 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001980 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001981 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001982
Chris Lattner5f9e2722011-07-23 10:55:15 +00001983 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001984
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001985 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001986
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001987 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001988
Douglas Gregore47be3e2010-11-11 00:39:14 +00001989 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001990 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001991
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001992 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001993 llvm::makeArrayRef(ArgBegin, ArgEnd),
1994 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001995 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001996 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001997 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001998
Douglas Gregor4db64a42010-01-23 00:14:00 +00001999 // Override any files that need remapping
Stephen Hines651f13c2014-04-23 16:59:28 -07002000 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2001 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2002 RemappedFiles[I].second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002003 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002004 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2005 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2006 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002007
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002008 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002009 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002010
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002011 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2012
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002013 // Create the AST unit.
Stephen Hines651f13c2014-04-23 16:59:28 -07002014 std::unique_ptr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002015 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002016 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002017 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002018 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002019 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002020 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002021 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002022 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002023 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002024 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002025 AST->IncludeBriefCommentsInCodeCompletion
2026 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002027 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002028 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002029 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002030 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002031 if (ForSerialization)
2032 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002033 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002034
2035 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002036 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2037 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002038
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002039 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2040 // Some error occurred, if caller wants to examine diagnostics, pass it the
2041 // ASTUnit.
2042 if (ErrAST) {
2043 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2044 ErrAST->swap(AST);
2045 }
2046 return 0;
2047 }
2048
Stephen Hines651f13c2014-04-23 16:59:28 -07002049 return AST.release();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002050}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002051
Stephen Hines651f13c2014-04-23 16:59:28 -07002052bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002053 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002054 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002055
2056 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002057
Douglas Gregor213f18b2010-10-28 15:44:59 +00002058 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002059 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002060
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002061 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002062 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2063 for (PreprocessorOptions::remapped_file_buffer_iterator
2064 R = PPOpts.remapped_file_buffer_begin(),
2065 REnd = PPOpts.remapped_file_buffer_end();
2066 R != REnd;
2067 ++R) {
2068 delete R->second;
2069 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002070 Invocation->getPreprocessorOpts().clearRemappedFiles();
Stephen Hines651f13c2014-04-23 16:59:28 -07002071 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2072 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2073 RemappedFiles[I].second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002074 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002075
Douglas Gregoreababfb2010-08-04 05:53:38 +00002076 // If we have a preamble file lying around, or if we might try to
2077 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002078 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002079 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002080 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002081
Douglas Gregorabc563f2010-07-19 21:46:24 +00002082 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002083 getDiagnostics().Reset();
2084 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002085 if (OverrideMainBuffer)
2086 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002087
Douglas Gregor175c4a92010-07-23 23:58:40 +00002088 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002089 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002090
2091 // If we're caching global code-completion results, and the top-level
2092 // declarations have changed, clear out the code-completion cache.
2093 if (!Result && ShouldCacheCodeCompletionResults &&
2094 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2095 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002096
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002097 // We now need to clear out the completion info related to this translation
2098 // unit; it'll be recreated if necessary.
2099 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002100
Douglas Gregor175c4a92010-07-23 23:58:40 +00002101 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002102}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002103
Douglas Gregor87c08a52010-08-13 22:48:40 +00002104//----------------------------------------------------------------------------//
2105// Code completion
2106//----------------------------------------------------------------------------//
2107
2108namespace {
2109 /// \brief Code completion consumer that combines the cached code-completion
2110 /// results from an ASTUnit with the code-completion results provided to it,
2111 /// then passes the result on to
2112 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002113 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002114 ASTUnit &AST;
2115 CodeCompleteConsumer &Next;
2116
2117 public:
2118 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002119 const CodeCompleteOptions &CodeCompleteOpts)
2120 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2121 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002122 {
2123 // Compute the set of contexts in which we will look when we don't have
2124 // any information about the specific context.
2125 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002126 = (1LL << CodeCompletionContext::CCC_TopLevel)
2127 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2128 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2129 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2130 | (1LL << CodeCompletionContext::CCC_Statement)
2131 | (1LL << CodeCompletionContext::CCC_Expression)
2132 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2133 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2134 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2135 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2136 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2137 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2138 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002139
David Blaikie4e4d0842012-03-11 07:00:24 +00002140 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002141 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2142 | (1LL << CodeCompletionContext::CCC_UnionTag)
2143 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002144 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002145
2146 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2147 CodeCompletionResult *Results,
2148 unsigned NumResults) override;
2149
2150 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2151 OverloadCandidate *Candidates,
2152 unsigned NumCandidates) override {
Douglas Gregor87c08a52010-08-13 22:48:40 +00002153 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2154 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002155
2156 CodeCompletionAllocator &getAllocator() override {
Douglas Gregor218937c2011-02-01 19:23:04 +00002157 return Next.getAllocator();
2158 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002159
Stephen Hines651f13c2014-04-23 16:59:28 -07002160 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002161 return Next.getCodeCompletionTUInfo();
2162 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002163 };
2164}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002165
Douglas Gregor5f808c22010-08-16 21:18:39 +00002166/// \brief Helper function that computes which global names are hidden by the
2167/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002168static void CalculateHiddenNames(const CodeCompletionContext &Context,
2169 CodeCompletionResult *Results,
2170 unsigned NumResults,
2171 ASTContext &Ctx,
2172 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002173 bool OnlyTagNames = false;
2174 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002175 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002176 case CodeCompletionContext::CCC_TopLevel:
2177 case CodeCompletionContext::CCC_ObjCInterface:
2178 case CodeCompletionContext::CCC_ObjCImplementation:
2179 case CodeCompletionContext::CCC_ObjCIvarList:
2180 case CodeCompletionContext::CCC_ClassStructUnion:
2181 case CodeCompletionContext::CCC_Statement:
2182 case CodeCompletionContext::CCC_Expression:
2183 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002184 case CodeCompletionContext::CCC_DotMemberAccess:
2185 case CodeCompletionContext::CCC_ArrowMemberAccess:
2186 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002187 case CodeCompletionContext::CCC_Namespace:
2188 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002189 case CodeCompletionContext::CCC_Name:
2190 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002191 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002192 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002193 break;
2194
2195 case CodeCompletionContext::CCC_EnumTag:
2196 case CodeCompletionContext::CCC_UnionTag:
2197 case CodeCompletionContext::CCC_ClassOrStructTag:
2198 OnlyTagNames = true;
2199 break;
2200
2201 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002202 case CodeCompletionContext::CCC_MacroName:
2203 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002204 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002205 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002206 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002207 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002208 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002209 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002210 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002211 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2212 case CodeCompletionContext::CCC_ObjCClassMessage:
2213 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002214 // We're looking for nothing, or we're looking for names that cannot
2215 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002216 return;
2217 }
2218
John McCall0a2c5e22010-08-25 06:19:51 +00002219 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002220 for (unsigned I = 0; I != NumResults; ++I) {
2221 if (Results[I].Kind != Result::RK_Declaration)
2222 continue;
2223
2224 unsigned IDNS
2225 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2226
2227 bool Hiding = false;
2228 if (OnlyTagNames)
2229 Hiding = (IDNS & Decl::IDNS_Tag);
2230 else {
2231 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002232 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2233 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002234 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002235 HiddenIDNS |= Decl::IDNS_Tag;
2236 Hiding = (IDNS & HiddenIDNS);
2237 }
2238
2239 if (!Hiding)
2240 continue;
2241
2242 DeclarationName Name = Results[I].Declaration->getDeclName();
2243 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2244 HiddenNames.insert(Identifier->getName());
2245 else
2246 HiddenNames.insert(Name.getAsString());
2247 }
2248}
2249
2250
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002251void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2252 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002253 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002254 unsigned NumResults) {
2255 // Merge the results we were given with the results we cached.
2256 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002257 uint64_t InContexts =
2258 Context.getKind() == CodeCompletionContext::CCC_Recovery
2259 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002260 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002261 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002262 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002263 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002264 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002265 C = AST.cached_completion_begin(),
2266 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002267 C != CEnd; ++C) {
2268 // If the context we are in matches any of the contexts we are
2269 // interested in, we'll add this result.
2270 if ((C->ShowInContexts & InContexts) == 0)
2271 continue;
2272
2273 // If we haven't added any results previously, do so now.
2274 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002275 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2276 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002277 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2278 AddedResult = true;
2279 }
2280
Douglas Gregor5f808c22010-08-16 21:18:39 +00002281 // Determine whether this global completion result is hidden by a local
2282 // completion result. If so, skip it.
2283 if (C->Kind != CXCursor_MacroDefinition &&
2284 HiddenNames.count(C->Completion->getTypedText()))
2285 continue;
2286
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002287 // Adjust priority based on similar type classes.
2288 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002289 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002290 if (!Context.getPreferredType().isNull()) {
2291 if (C->Kind == CXCursor_MacroDefinition) {
2292 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002293 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002294 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002295 } else if (C->Type) {
2296 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002297 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002298 Context.getPreferredType().getUnqualifiedType());
2299 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2300 if (ExpectedSTC == C->TypeClass) {
2301 // We know this type is similar; check for an exact match.
2302 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002303 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002304 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002305 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002306 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2307 Priority /= CCF_ExactTypeMatch;
2308 else
2309 Priority /= CCF_SimilarTypeMatch;
2310 }
2311 }
2312 }
2313
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002314 // Adjust the completion string, if required.
2315 if (C->Kind == CXCursor_MacroDefinition &&
2316 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2317 // Create a new code-completion string that just contains the
2318 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002319 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2320 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002321 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002322 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002323 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002324 }
2325
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002326 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002327 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002328 }
2329
2330 // If we did not add any cached completion results, just forward the
2331 // results we were given to the next consumer.
2332 if (!AddedResult) {
2333 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2334 return;
2335 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002336
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002337 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2338 AllResults.size());
2339}
2340
2341
2342
Chris Lattner5f9e2722011-07-23 10:55:15 +00002343void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Stephen Hines651f13c2014-04-23 16:59:28 -07002344 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002345 bool IncludeMacros,
2346 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002347 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002349 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002350 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002351 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2352 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002353 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354 return;
2355
Douglas Gregor213f18b2010-10-28 15:44:59 +00002356 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002357 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002358 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002359
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002360 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002361 CCInvocation(new CompilerInvocation(*Invocation));
2362
2363 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002364 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002365 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002366
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002367 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2368 CachedCompletionResults.empty();
2369 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2370 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2371 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2372
2373 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2374
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 FrontendOpts.CodeCompletionAt.FileName = File;
2376 FrontendOpts.CodeCompletionAt.Line = Line;
2377 FrontendOpts.CodeCompletionAt.Column = Column;
2378
2379 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002380 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002381
Stephen Hines651f13c2014-04-23 16:59:28 -07002382 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002383
2384 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002385 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2386 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002387
Ted Kremenek4f327862011-03-21 18:40:17 +00002388 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002389 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390
2391 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002392 Clang->setDiagnostics(&Diag);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002393 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002394 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002395 StoredDiagnostics);
Manuel Klimekf0c06a32013-07-18 14:23:12 +00002396 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002397
2398 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002399 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002400 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002401 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002402 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002403 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002404 }
2405
2406 // Inform the target of the language options.
2407 //
2408 // FIXME: We shouldn't need to do this, the target should be immutable once
2409 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002410 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002411
Ted Kremenek03201fb2011-03-21 18:40:07 +00002412 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002413 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002414 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002415 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002416 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002417 "IR inputs not support here!");
2418
2419
2420 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002421 Clang->setFileManager(&FileMgr);
2422 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002423
2424 // Remap files.
2425 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002426 PreprocessorOpts.RetainRemappedFileBuffers = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07002427 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2428 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2429 RemappedFiles[I].second);
2430 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00002431 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002432
Douglas Gregor87c08a52010-08-13 22:48:40 +00002433 // Use the code completion consumer we were given, but adding any cached
2434 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002435 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002436 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002437 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002438
Douglas Gregordf95a132010-08-09 20:45:32 +00002439 // If we have a precompiled preamble, try to use it. We only allow
2440 // the use of the precompiled preamble if we're if the completion
2441 // point is within the main file, after the end of the precompiled
2442 // preamble.
2443 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002444 if (!getPreambleFile(this).empty()) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002445 std::string CompleteFilePath(File);
Rafael Espindola44888352013-07-29 21:26:52 +00002446 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindola105b2072013-06-18 19:40:07 +00002447
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002448 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002449 std::string MainPath(OriginalSourceFile);
Rafael Espindola44888352013-07-29 21:26:52 +00002450 llvm::sys::fs::UniqueID MainID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002451 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002452 if (CompleteFileID == MainID && Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002453 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002454 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002455 Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002456 }
2457 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002458 }
2459
2460 // If the main file has been overridden due to the use of a preamble,
2461 // make that override happen and introduce the preamble.
2462 if (OverrideMainBuffer) {
2463 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2464 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2465 PreprocessorOpts.PrecompiledPreambleBytes.second
2466 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002467 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002468 PreprocessorOpts.DisablePCHValidation = true;
2469
Douglas Gregor2283d792010-08-20 00:59:43 +00002470 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002471 } else {
2472 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2473 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002474 }
2475
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002476 // Disable the preprocessing record if modules are not enabled.
2477 if (!Clang->getLangOpts().Modules)
2478 PreprocessorOpts.DetailedRecord = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002479
2480 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002481 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002482 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002483 Act->Execute();
2484 Act->EndSourceFile();
2485 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002486}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002487
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002488bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002489 if (HadModuleLoaderFatalFailure)
2490 return true;
2491
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002492 // Write to a temporary file and later rename it to the actual file, to avoid
2493 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002494 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002495 TempPath = File;
2496 TempPath += "-%%%%%%%%";
2497 int fd;
Rafael Espindola70e7aec2013-07-05 21:13:58 +00002498 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002499 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002500
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002501 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2502 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002503 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002504
2505 serialize(Out);
2506 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002507 if (Out.has_error()) {
2508 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002509 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002510 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002511
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002512 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002513 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002514 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002515 }
2516
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002517 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002518}
2519
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002520static bool serializeUnit(ASTWriter &Writer,
2521 SmallVectorImpl<char> &Buffer,
2522 Sema &S,
2523 bool hasErrors,
2524 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002525 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002526
2527 // Write the generated bitstream to "Out".
2528 if (!Buffer.empty())
2529 OS.write(Buffer.data(), Buffer.size());
2530
2531 return false;
2532}
2533
Chris Lattner5f9e2722011-07-23 10:55:15 +00002534bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002535 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002536
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002537 if (WriterData)
2538 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2539 getSema(), hasErrors, OS);
2540
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002541 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002542 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002543 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002544 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002545}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002546
2547typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2548
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002549void ASTUnit::TranslateStoredDiagnostics(
Stephen Hines651f13c2014-04-23 16:59:28 -07002550 FileManager &FileMgr,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002551 SourceManager &SrcMgr,
Stephen Hines651f13c2014-04-23 16:59:28 -07002552 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002553 SmallVectorImpl<StoredDiagnostic> &Out) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002554 // Map the standalone diagnostic into the new source manager. We also need to
2555 // remap all the locations to the new view. This includes the diag location,
2556 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002557 // FIXME: There should be a cleaner way to do this.
2558
Chris Lattner5f9e2722011-07-23 10:55:15 +00002559 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002560 Result.reserve(Diags.size());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002561 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2562 // Rebuild the StoredDiagnostic.
Stephen Hines651f13c2014-04-23 16:59:28 -07002563 const StandaloneDiagnostic &SD = Diags[I];
2564 if (SD.Filename.empty())
2565 continue;
2566 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2567 if (!FE)
2568 continue;
2569 FileID FID = SrcMgr.translateFile(FE);
2570 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2571 if (FileLoc.isInvalid())
2572 continue;
2573 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002574 FullSourceLoc Loc(L, SrcMgr);
2575
Chris Lattner5f9e2722011-07-23 10:55:15 +00002576 SmallVector<CharSourceRange, 4> Ranges;
Stephen Hines651f13c2014-04-23 16:59:28 -07002577 Ranges.reserve(SD.Ranges.size());
2578 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2579 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2580 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2581 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2582 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002583 }
2584
Chris Lattner5f9e2722011-07-23 10:55:15 +00002585 SmallVector<FixItHint, 2> FixIts;
Stephen Hines651f13c2014-04-23 16:59:28 -07002586 FixIts.reserve(SD.FixIts.size());
2587 for (std::vector<StandaloneFixIt>::const_iterator
2588 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002589 I != E; ++I) {
2590 FixIts.push_back(FixItHint());
2591 FixItHint &FH = FixIts.back();
2592 FH.CodeToInsert = I->CodeToInsert;
Stephen Hines651f13c2014-04-23 16:59:28 -07002593 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2594 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2595 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002596 }
2597
Stephen Hines651f13c2014-04-23 16:59:28 -07002598 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2599 SD.Message, Loc, Ranges, FixIts));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002600 }
2601 Result.swap(Out);
2602}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002603
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002604void ASTUnit::addFileLevelDecl(Decl *D) {
2605 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002606
2607 // We only care about local declarations.
2608 if (D->isFromASTFile())
2609 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002610
2611 SourceManager &SM = *SourceMgr;
2612 SourceLocation Loc = D->getLocation();
2613 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2614 return;
2615
2616 // We only keep track of the file-level declarations of each file.
2617 if (!D->getLexicalDeclContext()->isFileContext())
2618 return;
2619
2620 SourceLocation FileLoc = SM.getFileLoc(Loc);
2621 assert(SM.isLocalSourceLocation(FileLoc));
2622 FileID FID;
2623 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07002624 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002625 if (FID.isInvalid())
2626 return;
2627
2628 LocDeclsTy *&Decls = FileDecls[FID];
2629 if (!Decls)
2630 Decls = new LocDeclsTy();
2631
2632 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2633
2634 if (Decls->empty() || Decls->back().first <= Offset) {
2635 Decls->push_back(LocDecl);
2636 return;
2637 }
2638
Benjamin Kramer809d2542013-08-24 13:22:59 +00002639 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2640 LocDecl, llvm::less_first());
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002641
2642 Decls->insert(I, LocDecl);
2643}
2644
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002645void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2646 SmallVectorImpl<Decl *> &Decls) {
2647 if (File.isInvalid())
2648 return;
2649
2650 if (SourceMgr->isLoadedFileID(File)) {
2651 assert(Ctx->getExternalSource() && "No external source!");
2652 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2653 Decls);
2654 }
2655
2656 FileDeclsTy::iterator I = FileDecls.find(File);
2657 if (I == FileDecls.end())
2658 return;
2659
2660 LocDeclsTy &LocDecls = *I->second;
2661 if (LocDecls.empty())
2662 return;
2663
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002664 LocDeclsTy::iterator BeginIt =
2665 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer809d2542013-08-24 13:22:59 +00002666 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002667 if (BeginIt != LocDecls.begin())
2668 --BeginIt;
2669
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002670 // If we are pointing at a top-level decl inside an objc container, we need
2671 // to backtrack until we find it otherwise we will fail to report that the
2672 // region overlaps with an objc container.
2673 while (BeginIt != LocDecls.begin() &&
2674 BeginIt->second->isTopLevelDeclInObjCContainer())
2675 --BeginIt;
2676
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002677 LocDeclsTy::iterator EndIt = std::upper_bound(
2678 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer809d2542013-08-24 13:22:59 +00002679 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002680 if (EndIt != LocDecls.end())
2681 ++EndIt;
2682
2683 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2684 Decls.push_back(DIt->second);
2685}
2686
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002687SourceLocation ASTUnit::getLocation(const FileEntry *File,
2688 unsigned Line, unsigned Col) const {
2689 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002690 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002691 return SM.getMacroArgExpandedLocation(Loc);
2692}
2693
2694SourceLocation ASTUnit::getLocation(const FileEntry *File,
2695 unsigned Offset) const {
2696 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002697 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002698 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2699}
2700
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002701/// \brief If \arg Loc is a loaded location from the preamble, returns
2702/// the corresponding local location of the main file, otherwise it returns
2703/// \arg Loc.
2704SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2705 FileID PreambleID;
2706 if (SourceMgr)
2707 PreambleID = SourceMgr->getPreambleFileID();
2708
2709 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2710 return Loc;
2711
2712 unsigned Offs;
2713 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2714 SourceLocation FileLoc
2715 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2716 return FileLoc.getLocWithOffset(Offs);
2717 }
2718
2719 return Loc;
2720}
2721
2722/// \brief If \arg Loc is a local location of the main file but inside the
2723/// preamble chunk, returns the corresponding loaded location from the
2724/// preamble, otherwise it returns \arg Loc.
2725SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2726 FileID PreambleID;
2727 if (SourceMgr)
2728 PreambleID = SourceMgr->getPreambleFileID();
2729
2730 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2731 return Loc;
2732
2733 unsigned Offs;
2734 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2735 Offs < Preamble.size()) {
2736 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2737 return FileLoc.getLocWithOffset(Offs);
2738 }
2739
2740 return Loc;
2741}
2742
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002743bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2744 FileID FID;
2745 if (SourceMgr)
2746 FID = SourceMgr->getPreambleFileID();
2747
2748 if (Loc.isInvalid() || FID.isInvalid())
2749 return false;
2750
2751 return SourceMgr->isInFileID(Loc, FID);
2752}
2753
2754bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2755 FileID FID;
2756 if (SourceMgr)
2757 FID = SourceMgr->getMainFileID();
2758
2759 if (Loc.isInvalid() || FID.isInvalid())
2760 return false;
2761
2762 return SourceMgr->isInFileID(Loc, FID);
2763}
2764
2765SourceLocation ASTUnit::getEndOfPreambleFileID() {
2766 FileID FID;
2767 if (SourceMgr)
2768 FID = SourceMgr->getPreambleFileID();
2769
2770 if (FID.isInvalid())
2771 return SourceLocation();
2772
2773 return SourceMgr->getLocForEndOfFile(FID);
2774}
2775
2776SourceLocation ASTUnit::getStartOfMainFileID() {
2777 FileID FID;
2778 if (SourceMgr)
2779 FID = SourceMgr->getMainFileID();
2780
2781 if (FID.isInvalid())
2782 return SourceLocation();
2783
2784 return SourceMgr->getLocForStartOfFile(FID);
2785}
2786
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002787std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2788ASTUnit::getLocalPreprocessingEntities() const {
2789 if (isMainFileAST()) {
2790 serialization::ModuleFile &
2791 Mod = Reader->getModuleManager().getPrimaryModule();
2792 return Reader->getModulePreprocessedEntities(Mod);
2793 }
2794
2795 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2796 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2797
2798 return std::make_pair(PreprocessingRecord::iterator(),
2799 PreprocessingRecord::iterator());
2800}
2801
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002802bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002803 if (isMainFileAST()) {
2804 serialization::ModuleFile &
2805 Mod = Reader->getModuleManager().getPrimaryModule();
2806 ASTReader::ModuleDeclIterator MDI, MDE;
Stephen Hines651f13c2014-04-23 16:59:28 -07002807 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002808 for (; MDI != MDE; ++MDI) {
2809 if (!Fn(context, *MDI))
2810 return false;
2811 }
2812
2813 return true;
2814 }
2815
2816 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2817 TLEnd = top_level_end();
2818 TL != TLEnd; ++TL) {
2819 if (!Fn(context, *TL))
2820 return false;
2821 }
2822
2823 return true;
2824}
2825
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002826namespace {
2827struct PCHLocatorInfo {
2828 serialization::ModuleFile *Mod;
2829 PCHLocatorInfo() : Mod(0) {}
2830};
2831}
2832
2833static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2834 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2835 switch (M.Kind) {
2836 case serialization::MK_Module:
2837 return true; // skip dependencies.
2838 case serialization::MK_PCH:
2839 Info.Mod = &M;
2840 return true; // found it.
2841 case serialization::MK_Preamble:
2842 return false; // look in dependencies.
2843 case serialization::MK_MainFile:
2844 return false; // look in dependencies.
2845 }
2846
2847 return true;
2848}
2849
2850const FileEntry *ASTUnit::getPCHFile() {
2851 if (!Reader)
2852 return 0;
2853
2854 PCHLocatorInfo Info;
2855 Reader->getModuleManager().visit(PCHLocator, &Info);
2856 if (Info.Mod)
2857 return Info.Mod->File;
2858
2859 return 0;
2860}
2861
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002862bool ASTUnit::isModuleFile() {
2863 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2864}
2865
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002866void ASTUnit::PreambleData::countLines() const {
2867 NumLines = 0;
2868 if (empty())
2869 return;
2870
2871 for (std::vector<char>::const_iterator
2872 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2873 if (*I == '\n')
2874 ++NumLines;
2875 }
2876 if (Buffer.back() != '\n')
2877 ++NumLines;
2878}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002879
2880#ifndef NDEBUG
2881ASTUnit::ConcurrencyState::ConcurrencyState() {
2882 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2883}
2884
2885ASTUnit::ConcurrencyState::~ConcurrencyState() {
2886 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2887}
2888
2889void ASTUnit::ConcurrencyState::start() {
2890 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2891 assert(acquired && "Concurrent access to ASTUnit!");
2892}
2893
2894void ASTUnit::ConcurrencyState::finish() {
2895 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2896}
2897
2898#else // NDEBUG
2899
Stephen Hines651f13c2014-04-23 16:59:28 -07002900ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002901ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2902void ASTUnit::ConcurrencyState::start() {}
2903void ASTUnit::ConcurrencyState::finish() {}
2904
2905#endif