blob: bfb1efe352295618092b5dafa9f83bd9f4f40192 [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>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor213f18b2010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek1872b312011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
Rafael Espindolab804cb32013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek1872b312011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolab804cb32013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek1872b312011-10-27 17:55:18 +000090 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000107
Stephen Hines176edba2014-12-01 14:53:08 -0800108typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek1872b312011-10-27 17:55:18 +0000110static 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());
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700123 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700126 I.second->Cleanup();
Ted Kremenek1872b312011-10-27 17:55:18 +0000127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
Stephen Hines176edba2014-12-01 14:53:08 -0800135 auto &D = M[AU];
Ted Kremenek1872b312011-10-27 17:55:18 +0000136 if (!D)
Stephen Hines176edba2014-12-01 14:53:08 -0800137 D = llvm::make_unique<OnDiskData>();
Ted Kremenek1872b312011-10-27 17:55:18 +0000138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700153 M.erase(I);
Ted Kremenek1872b312011-10-27 17:55:18 +0000154 }
155}
156
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000157static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000158 getOnDiskData(AU).PreambleFile = preambleFile;
159}
160
161static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
163}
164
165void OnDiskData::CleanTemporaryFiles() {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700166 for (StringRef File : TemporaryFiles)
167 llvm::sys::fs::remove(File);
Rafael Espindolab804cb32013-06-26 03:52:38 +0000168 TemporaryFiles.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +0000169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
Rafael Espindola85d28482013-06-26 04:02:37 +0000173 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek1872b312011-10-27 17:55:18 +0000174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000183struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
186 ASTWriter Writer;
187
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
189};
190
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000191void ASTUnit::clearFileLevelDecls() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700192 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000193}
194
Ted Kremenek1872b312011-10-27 17:55:18 +0000195void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
197}
198
Rafael Espindolab804cb32013-06-26 03:52:38 +0000199void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000201}
202
Douglas Gregoreababfb2010-08-04 05:53:38 +0000203/// \brief After failing to build a precompiled preamble (due to
204/// errors in the source that occurs in the preamble), the number of
205/// reparses during which we'll skip even trying to precompile the
206/// preamble.
207const unsigned DefaultPreambleRebuildInterval = 5;
208
Douglas Gregore3c60a72010-11-17 00:13:31 +0000209/// \brief Tracks the number of ASTUnit objects that are currently active.
210///
211/// Used for debugging purposes only.
Stephen Hines651f13c2014-04-23 16:59:28 -0700212static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700215 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +0000216 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000217 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000218 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000219 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000220 NumStoredDiagnosticsFromDriver(0),
Stephen Hines176edba2014-12-01 14:53:08 -0800221 PreambleRebuildCounter(0),
222 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000223 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000224 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000225 CompletionCacheTopLevelHashValue(0),
226 PreambleTopLevelHashValue(0),
227 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000228 UnsafeToFree(false) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700229 if (getenv("LIBCLANG_OBJTRACKING"))
230 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor385103b2010-07-30 20:58:08 +0000231}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000232
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000234 // If we loaded from an AST file, balance out the BeginSourceFile call.
235 if (MainFileIsAST && getDiagnostics().getClient()) {
236 getDiagnostics().getClient()->EndSourceFile();
237 }
238
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000239 clearFileLevelDecls();
240
Ted Kremenek1872b312011-10-27 17:55:18 +0000241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
243
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
247 // parser.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700248 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700250 for (const auto &RB : PPOpts.RemappedFileBuffers)
251 delete RB.second;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000252 }
Douglas Gregor671947b2010-08-19 01:33:06 +0000253
Douglas Gregor213f18b2010-10-28 15:44:59 +0000254 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000255
Stephen Hines651f13c2014-04-23 16:59:28 -0700256 if (getenv("LIBCLANG_OBJTRACKING"))
257 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000258}
259
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000260void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
261
Douglas Gregor8071e422010-08-15 06:18:01 +0000262/// \brief Determine the set of code-completion contexts in which this
263/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000264static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
268
Douglas Gregor8071e422010-08-15 06:18:01 +0000269 if (isa<UsingShadowDecl>(ND))
270 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
271 if (!ND)
272 return 0;
273
Richard Smith026b3582012-08-14 03:13:00 +0000274 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
277 // Types can appear in these contexts.
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000279 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
280 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
281 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
282 | (1LL << CodeCompletionContext::CCC_Statement)
283 | (1LL << CodeCompletionContext::CCC_Type)
284 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000285
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000289
290 // In Objective-C, message sends can send interfaces. In Objective-C++,
291 // all types are available due to functional casts.
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000294
295 // In Objective-C, you can only be a subclass of another Objective-C class
296 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000302
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000303 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000304 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000306 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000307 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 else
Richard Smith026b3582012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000311
Douglas Gregor8071e422010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000314 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000315 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
317 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000318 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
319 | (1LL << CodeCompletionContext::CCC_Expression)
320 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
321 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000322 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000324 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000328
329 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 }
332
333 return Contexts;
334}
335
Douglas Gregor87c08a52010-08-13 22:48:40 +0000336void ASTUnit::CacheCodeCompletionResults() {
337 if (!TheSema)
338 return;
339
Douglas Gregor213f18b2010-10-28 15:44:59 +0000340 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000341 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000342
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
345
346 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000347 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000348 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000350 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000352 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000353
354 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700356
357 for (Result &R : Results) {
358 switch (R.Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000359 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000360 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000361 CachedCodeCompletionResult CachedResult;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700362 CachedResult.Completion = R.CreateCodeCompletionString(
363 *TheSema, *CachedCompletionAllocator, CCTUInfo,
364 IncludeBriefCommentsInCodeCompletion);
365 CachedResult.ShowInContexts = getDeclShowContexts(
366 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
367 CachedResult.Priority = R.Priority;
368 CachedResult.Kind = R.CursorKind;
369 CachedResult.Availability = R.Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000370
Douglas Gregorf5586f62010-08-16 18:08:11 +0000371 // Keep track of the type of this completion in an ASTContext-agnostic
372 // way.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700373 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000374 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000375 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000376 CachedResult.Type = 0;
377 } else {
378 CanQualType CanUsageType
379 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
380 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
381
382 // Determine whether we have already seen this type. If so, we save
383 // ourselves the work of formatting the type string by using the
384 // temporary, CanQualType-based hash table to find the associated value.
385 unsigned &TypeValue = CompletionTypes[CanUsageType];
386 if (TypeValue == 0) {
387 TypeValue = CompletionTypes.size();
388 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
389 = TypeValue;
390 }
391
392 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000393 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000394
Douglas Gregor8071e422010-08-15 06:18:01 +0000395 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000396
397 /// Handle nested-name-specifiers in C++.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700398 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
399 !R.StartsNestedNameSpecifier) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000400 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000401 uint64_t NNSContexts
402 = (1LL << CodeCompletionContext::CCC_TopLevel)
403 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
404 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
405 | (1LL << CodeCompletionContext::CCC_Statement)
406 | (1LL << CodeCompletionContext::CCC_Expression)
407 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
408 | (1LL << CodeCompletionContext::CCC_EnumTag)
409 | (1LL << CodeCompletionContext::CCC_UnionTag)
410 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
411 | (1LL << CodeCompletionContext::CCC_Type)
412 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
413 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000414
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700415 if (isa<NamespaceDecl>(R.Declaration) ||
416 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000417 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000418
419 if (unsigned RemainingContexts
420 = NNSContexts & ~CachedResult.ShowInContexts) {
421 // If there any contexts where this completion can be a
422 // nested-name-specifier but isn't already an option, create a
423 // nested-name-specifier completion.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700424 R.StartsNestedNameSpecifier = true;
425 CachedResult.Completion = R.CreateCodeCompletionString(
426 *TheSema, *CachedCompletionAllocator, CCTUInfo,
427 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000428 CachedResult.ShowInContexts = RemainingContexts;
429 CachedResult.Priority = CCP_NestedNameSpecifier;
430 CachedResult.TypeClass = STC_Void;
431 CachedResult.Type = 0;
432 CachedCompletionResults.push_back(CachedResult);
433 }
434 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000435 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000436 }
437
Douglas Gregor87c08a52010-08-13 22:48:40 +0000438 case Result::RK_Keyword:
439 case Result::RK_Pattern:
440 // Ignore keywords and patterns; we don't care, since they are so
441 // easily regenerated.
442 break;
443
444 case Result::RK_Macro: {
445 CachedCodeCompletionResult CachedResult;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700446 CachedResult.Completion = R.CreateCodeCompletionString(
447 *TheSema, *CachedCompletionAllocator, CCTUInfo,
448 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000449 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000450 = (1LL << CodeCompletionContext::CCC_TopLevel)
451 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
452 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
453 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
454 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
455 | (1LL << CodeCompletionContext::CCC_Statement)
456 | (1LL << CodeCompletionContext::CCC_Expression)
457 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
458 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
459 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
460 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
461 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700462
463 CachedResult.Priority = R.Priority;
464 CachedResult.Kind = R.CursorKind;
465 CachedResult.Availability = R.Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000466 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000467 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000468 CachedCompletionResults.push_back(CachedResult);
469 break;
470 }
471 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000472 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000473
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476}
477
478void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000479 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000480 CachedCompletionTypes.clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700481 CachedCompletionAllocator = nullptr;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482}
483
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000484namespace {
485
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000486/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000487/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000488class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000489 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000490 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000491 LangOptions &LangOpt;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700492 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000493 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000496 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497public:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700498 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
499 std::shared_ptr<TargetOptions> &TargetOpts,
500 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
501 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
502 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Stephen Hines176edba2014-12-01 14:53:08 -0800504 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
505 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000506 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000507 return false;
508
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000509 LangOpt = LangOpts;
510 InitializedLanguage = true;
511
512 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 return false;
514 }
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Stephen Hines651f13c2014-04-23 16:59:28 -0700516 bool ReadTargetOptions(const TargetOptions &TargetOpts,
517 bool Complain) override {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000518 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000519 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000520 return false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700521
522 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
523 Target =
524 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000525
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000526 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000527 return false;
528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Stephen Hines651f13c2014-04-23 16:59:28 -0700530 void ReadCounter(const serialization::ModuleFile &M,
531 unsigned Value) override {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000532 Counter = Value;
533 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000534
535private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000536 void updated() {
537 if (!Target || !InitializedLanguage)
538 return;
539
540 // Inform the target of the language options.
541 //
542 // FIXME: We shouldn't need to do this, the target should be immutable once
543 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700544 Target->adjust(LangOpt);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000545
546 // Initialize the preprocessor.
547 PP.Initialize(*Target);
548
549 // Initialize the ASTContext
550 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000551
552 // We didn't have access to the comment options when the ASTContext was
553 // constructed, so register them now.
554 Context.getCommentCommandTraits().registerCommentOptions(
555 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000556 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000557};
558
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000559 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000560class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000561 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000562 SourceManager *SourceMgr;
563
Douglas Gregora88084b2010-02-18 18:08:43 +0000564public:
David Blaikie26e7a902011-09-26 00:01:39 +0000565 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000566 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700567 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000568
Stephen Hines651f13c2014-04-23 16:59:28 -0700569 void BeginSourceFile(const LangOptions &LangOpts,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700570 const Preprocessor *PP = nullptr) override {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000571 if (PP)
572 SourceMgr = &PP->getSourceManager();
573 }
574
Stephen Hines651f13c2014-04-23 16:59:28 -0700575 void HandleDiagnostic(DiagnosticsEngine::Level Level,
576 const Diagnostic &Info) override;
Douglas Gregora88084b2010-02-18 18:08:43 +0000577};
578
579/// \brief RAII object that optionally captures diagnostics, if
580/// there is no diagnostic client to capture them already.
581class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000582 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000583 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000584 DiagnosticConsumer *PreviousClient;
Stephen Hines176edba2014-12-01 14:53:08 -0800585 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000586
587public:
David Blaikied6471f72011-09-25 23:23:43 +0000588 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700590 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregora88084b2010-02-18 18:08:43 +0000591 {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700592 if (RequestCapture || Diags.getClient() == nullptr) {
Stephen Hines176edba2014-12-01 14:53:08 -0800593 OwningPreviousClient = Diags.takeClient();
594 PreviousClient = Diags.getClient();
595 Diags.setClient(&Client, false);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000596 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000597 }
598
599 ~CaptureDroppedDiagnostics() {
Stephen Hines176edba2014-12-01 14:53:08 -0800600 if (Diags.getClient() == &Client)
601 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregora88084b2010-02-18 18:08:43 +0000602 }
603};
604
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000605} // anonymous namespace
606
David Blaikie26e7a902011-09-26 00:01:39 +0000607void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000608 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000609 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000610 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000611
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000612 // Only record the diagnostic if it's part of the source manager we know
613 // about. This effectively drops diagnostics from modules we're building.
614 // FIXME: In the long run, ee don't want to drop source managers from modules.
615 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
616 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000617}
618
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000619ASTMutationListener *ASTUnit::getASTMutationListener() {
620 if (WriterData)
621 return &WriterData->Writer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700622 return nullptr;
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000623}
624
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000625ASTDeserializationListener *ASTUnit::getDeserializationListener() {
626 if (WriterData)
627 return &WriterData->Writer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700628 return nullptr;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000629}
630
Stephen Hines176edba2014-12-01 14:53:08 -0800631std::unique_ptr<llvm::MemoryBuffer>
632ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000633 assert(FileMgr);
Stephen Hines176edba2014-12-01 14:53:08 -0800634 auto Buffer = FileMgr->getBufferForFile(Filename);
635 if (Buffer)
636 return std::move(*Buffer);
637 if (ErrorStr)
638 *ErrorStr = Buffer.getError().message();
639 return nullptr;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000640}
641
Douglas Gregore47be3e2010-11-11 00:39:14 +0000642/// \brief Configure the diagnostics object for use with ASTUnit.
Stephen Hines176edba2014-12-01 14:53:08 -0800643void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000644 ASTUnit &AST, bool CaptureDiagnostics) {
Stephen Hines176edba2014-12-01 14:53:08 -0800645 assert(Diags.get() && "no DiagnosticsEngine was provided");
646 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000647 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000648}
649
Stephen Hines176edba2014-12-01 14:53:08 -0800650std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
651 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
652 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
653 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
654 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700655 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000656
657 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000658 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
659 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000660 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
661 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700662 DiagCleanup(Diags.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000663
Stephen Hines176edba2014-12-01 14:53:08 -0800664 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000665
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000666 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000667 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000668 AST->Diagnostics = Diags;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700669 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
670 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000671 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000672 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000673 AST->getFileManager(),
674 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000675 AST->HSOpts = new HeaderSearchOptions();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700676
Douglas Gregorc042edd2012-10-24 16:19:39 +0000677 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimekee0cd372013-10-24 07:51:24 +0000678 AST->getSourceManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000679 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000680 AST->ASTFileLangOpts,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700681 /*Target=*/nullptr));
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000682
Stephen Hines651f13c2014-04-23 16:59:28 -0700683 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000684
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700685 for (const auto &RemappedFile : RemappedFiles)
686 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Stephen Hines651f13c2014-04-23 16:59:28 -0700687
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000688 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Stephen Hines176edba2014-12-01 14:53:08 -0800690 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000691 unsigned Counter;
692
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700693 AST->PP =
694 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
695 AST->getSourceManager(), HeaderInfo, *AST,
696 /*IILookup=*/nullptr,
697 /*OwnsHeaderSearch=*/false);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000698 Preprocessor &PP = *AST->PP;
699
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700700 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
701 PP.getIdentifierTable(), PP.getSelectorTable(),
702 PP.getBuiltinInfo());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000703 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000704
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000705 bool disableValid = false;
706 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
707 disableValid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700708 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000709 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000710 /*DisableValidation=*/disableValid,
Stephen Hines651f13c2014-04-23 16:59:28 -0700711 AllowPCHWithCompilerErrors);
Ted Kremenek8c647de2011-05-04 23:27:12 +0000712
Stephen Hines176edba2014-12-01 14:53:08 -0800713 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
714 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
715 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000716
Stephen Hines651f13c2014-04-23 16:59:28 -0700717 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000718 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000719 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000720 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000722 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000723 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000724 case ASTReader::OutOfDate:
725 case ASTReader::VersionMismatch:
726 case ASTReader::ConfigurationMismatch:
727 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000728 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700729 return nullptr;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Stephen Hines651f13c2014-04-23 16:59:28 -0700732 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000733
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000734 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000736 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000737 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000738 // AST file as needed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700739 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000740
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000741 // Create an AST consumer, even though it isn't used.
742 AST->Consumer.reset(new ASTConsumer);
743
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000744 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000745 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
746 AST->TheSema->Initialize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700747 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000748
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000749 // Tell the diagnostic client that we have started a source file.
750 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
751
Stephen Hines176edba2014-12-01 14:53:08 -0800752 return AST;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000753}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000754
755namespace {
756
Douglas Gregor9b7db622011-02-16 18:16:54 +0000757/// \brief Preprocessor callback class that updates a hash value with the names
758/// of all macros that have been defined by the translation unit.
759class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
760 unsigned &Hash;
761
762public:
763 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Stephen Hines651f13c2014-04-23 16:59:28 -0700764
765 void MacroDefined(const Token &MacroNameTok,
766 const MacroDirective *MD) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000767 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
768 }
769};
770
771/// \brief Add the given declaration to the hash of all top-level entities.
772void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
773 if (!D)
774 return;
775
776 DeclContext *DC = D->getDeclContext();
777 if (!DC)
778 return;
779
780 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
781 return;
782
783 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000784 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
785 // For an unscoped enum include the enumerators in the hash since they
786 // enter the top-level namespace.
787 if (!EnumD->isScoped()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700788 for (const auto *EI : EnumD->enumerators()) {
789 if (EI->getIdentifier())
790 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000791 }
792 }
793 }
794
Douglas Gregor9b7db622011-02-16 18:16:54 +0000795 if (ND->getIdentifier())
796 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
797 else if (DeclarationName Name = ND->getDeclName()) {
798 std::string NameStr = Name.getAsString();
799 Hash = llvm::HashString(NameStr, Hash);
800 }
801 return;
Argyrios Kyrtzidis1f3ff6a2013-06-24 21:19:12 +0000802 }
803
804 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
805 if (Module *Mod = ImportD->getImportedModule()) {
806 std::string ModName = Mod->getFullModuleName();
807 Hash = llvm::HashString(ModName, Hash);
808 }
809 return;
810 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000811}
812
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000813class TopLevelDeclTrackerConsumer : public ASTConsumer {
814 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000815 unsigned &Hash;
816
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000817public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000818 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
819 : Unit(_Unit), Hash(Hash) {
820 Hash = 0;
821 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000822
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000823 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000824 if (!D)
825 return;
826
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000827 // FIXME: Currently ObjC method declarations are incorrectly being
828 // reported as top-level declarations, even though their DeclContext
829 // is the containing ObjC @interface/@implementation. This is a
830 // fundamental problem in the parser right now.
831 if (isa<ObjCMethodDecl>(D))
832 return;
833
834 AddTopLevelDeclarationToHash(D, Hash);
835 Unit.addTopLevelDecl(D);
836
837 handleFileLevelDecl(D);
838 }
839
840 void handleFileLevelDecl(Decl *D) {
841 Unit.addFileLevelDecl(D);
842 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700843 for (auto *I : NSD->decls())
844 handleFileLevelDecl(I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000845 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000846 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000847
Stephen Hines651f13c2014-04-23 16:59:28 -0700848 bool HandleTopLevelDecl(DeclGroupRef D) override {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700849 for (Decl *TopLevelDecl : D)
850 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000851 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000852 }
853
Sebastian Redl27372b42010-08-11 18:52:41 +0000854 // We're not interested in "interesting" decls.
Stephen Hines651f13c2014-04-23 16:59:28 -0700855 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000856
Stephen Hines651f13c2014-04-23 16:59:28 -0700857 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700858 for (Decl *TopLevelDecl : D)
859 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000860 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000861
Stephen Hines651f13c2014-04-23 16:59:28 -0700862 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000863 return Unit.getASTMutationListener();
864 }
865
Stephen Hines651f13c2014-04-23 16:59:28 -0700866 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000867 return Unit.getDeserializationListener();
868 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000869};
870
871class TopLevelDeclTrackerAction : public ASTFrontendAction {
872public:
873 ASTUnit &Unit;
874
Stephen Hines176edba2014-12-01 14:53:08 -0800875 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
876 StringRef InFile) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000877 CI.getPreprocessor().addPPCallbacks(
Stephen Hines176edba2014-12-01 14:53:08 -0800878 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
879 Unit.getCurrentTopLevelHashValue()));
880 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
881 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000882 }
883
884public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000885 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
886
Stephen Hines651f13c2014-04-23 16:59:28 -0700887 bool hasCodeCompletionSupport() const override { return false; }
888 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor467dc882011-08-25 22:30:56 +0000889 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000890 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000891};
892
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000893class PrecompilePreambleAction : public ASTFrontendAction {
894 ASTUnit &Unit;
895 bool HasEmittedPreamblePCH;
896
897public:
898 explicit PrecompilePreambleAction(ASTUnit &Unit)
899 : Unit(Unit), HasEmittedPreamblePCH(false) {}
900
Stephen Hines176edba2014-12-01 14:53:08 -0800901 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
902 StringRef InFile) override;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000903 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
904 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Stephen Hines651f13c2014-04-23 16:59:28 -0700905 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000906
Stephen Hines651f13c2014-04-23 16:59:28 -0700907 bool hasCodeCompletionSupport() const override { return false; }
908 bool hasASTFileSupport() const override { return false; }
909 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000910};
911
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000912class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000913 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000914 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000915 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000916 PrecompilePreambleAction *Action;
917
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000918public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000919 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
920 const Preprocessor &PP, StringRef isysroot,
921 raw_ostream *Out)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700922 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000923 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000924 Hash = 0;
925 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000926
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700927 bool HandleTopLevelDecl(DeclGroupRef DG) override {
928 for (Decl *D : DG) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000929 // FIXME: Currently ObjC method declarations are incorrectly being
930 // reported as top-level declarations, even though their DeclContext
931 // is the containing ObjC @interface/@implementation. This is a
932 // fundamental problem in the parser right now.
933 if (isa<ObjCMethodDecl>(D))
934 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000935 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000936 TopLevelDecls.push_back(D);
937 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000938 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000939 }
940
Stephen Hines651f13c2014-04-23 16:59:28 -0700941 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000942 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +0000943 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000944 // Translate the top-level declarations we captured during
945 // parsing into declaration IDs in the precompiled
946 // preamble. This will allow us to deserialize those top-level
947 // declarations when requested.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700948 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidis51e75ae2013-08-07 21:17:33 +0000949 // Invalid top-level decls may not have been serialized.
950 if (D->isInvalidDecl())
951 continue;
952 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
953 }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000954
955 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000956 }
957 }
958};
959
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000960}
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000961
Stephen Hines176edba2014-12-01 14:53:08 -0800962std::unique_ptr<ASTConsumer>
963PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
964 StringRef InFile) {
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000965 std::string Sysroot;
966 std::string OutputFile;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700967 raw_ostream *OS = nullptr;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000968 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
969 OutputFile, OS))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700970 return nullptr;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000971
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000972 if (!CI.getFrontendOpts().RelocatablePCH)
973 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +0000974
Stephen Hines176edba2014-12-01 14:53:08 -0800975 CI.getPreprocessor().addPPCallbacks(
976 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
977 Unit.getCurrentTopLevelHashValue()));
978 return llvm::make_unique<PrecompilePreambleConsumer>(
979 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000980}
981
Benjamin Kramerfe57db22013-05-05 12:39:28 +0000982static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
983 return StoredDiag.getLocation().isValid();
984}
985
986static void
987checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000988 // Get rid of stored diagnostics except the ones from the driver which do not
989 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +0000990 StoredDiags.erase(
991 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
992 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000993}
994
995static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
996 StoredDiagnostics,
997 SourceManager &SM) {
998 // The stored diagnostic has the old source manager in it; update
999 // the locations to refer into the new source manager. Since we've
1000 // been careful to make sure that the source manager's state
1001 // before and after are identical, so that we can reuse the source
1002 // location itself.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001003 for (StoredDiagnostic &SD : StoredDiagnostics) {
1004 if (SD.getLocation().isValid()) {
1005 FullSourceLoc Loc(SD.getLocation(), SM);
1006 SD.setLocation(Loc);
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001007 }
1008 }
1009}
1010
Douglas Gregorabc563f2010-07-19 21:46:24 +00001011/// Parse the source file into a translation unit using the given compiler
1012/// invocation, replacing the current translation unit.
1013///
1014/// \returns True if a failure occurred that causes the ASTUnit not to
1015/// contain any translation-unit information, false otherwise.
Stephen Hines176edba2014-12-01 14:53:08 -08001016bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1017 SavedMainFileBuffer.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001018
Stephen Hines176edba2014-12-01 14:53:08 -08001019 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001020 return true;
Stephen Hines176edba2014-12-01 14:53:08 -08001021
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001022 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001023 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001024
1025 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001026 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1027 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001028
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001029 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001030 CCInvocation(new CompilerInvocation(*Invocation));
1031
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001032 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001033 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001034
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001035 // Set up diagnostics, capturing any diagnostics that would
1036 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001037 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001038
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001039 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001040 Clang->setTarget(TargetInfo::CreateTargetInfo(
1041 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Stephen Hines176edba2014-12-01 14:53:08 -08001042 if (!Clang->hasTarget())
Douglas Gregorabc563f2010-07-19 21:46:24 +00001043 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001044
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001045 // Inform the target of the language options.
1046 //
1047 // FIXME: We shouldn't need to do this, the target should be immutable once
1048 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001049 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001050
Ted Kremenek03201fb2011-03-21 18:40:07 +00001051 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001052 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001053 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001054 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001055 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001056 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001057
Douglas Gregorabc563f2010-07-19 21:46:24 +00001058 // Configure the various subsystems.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001059 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek03201fb2011-03-21 18:40:07 +00001060 FileSystemOpts = Clang->getFileSystemOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001061 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1062 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
Stephen Hines176edba2014-12-01 14:53:08 -08001063 if (!VFS)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001064 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001065 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001066 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1067 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001068 TheSema.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001069 Ctx = nullptr;
1070 PP = nullptr;
1071 Reader = nullptr;
1072
Douglas Gregorabc563f2010-07-19 21:46:24 +00001073 // Clear out old caches and data.
1074 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001075 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001076 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001077
Douglas Gregorf128fed2010-08-20 00:02:33 +00001078 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001079 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001080 TopLevelDeclsInPreamble.clear();
1081 }
1082
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001083 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001084 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001085
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001086 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001087 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001089 // If the main file has been overridden due to the use of a preamble,
1090 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001091 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001092 if (OverrideMainBuffer) {
Stephen Hines176edba2014-12-01 14:53:08 -08001093 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1094 OverrideMainBuffer.get());
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001095 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1096 PreprocessorOpts.PrecompiledPreambleBytes.second
1097 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001098 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001099 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001100
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001101 // The stored diagnostic has the old source manager in it; update
1102 // the locations to refer into the new source manager. Since we've
1103 // been careful to make sure that the source manager's state
1104 // before and after are identical, so that we can reuse the source
1105 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001106 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001107
1108 // Keep track of the override buffer;
Stephen Hines176edba2014-12-01 14:53:08 -08001109 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001110 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001111
1112 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1113 new TopLevelDeclTrackerAction(*this));
1114
Ted Kremenek25a11e12011-03-22 01:15:24 +00001115 // Recover resources if we crash before exiting this method.
1116 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1117 ActCleanup(Act.get());
1118
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001119 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001120 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001121
Stephen Hines176edba2014-12-01 14:53:08 -08001122 if (SavedMainFileBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001123 std::string ModName = getPreambleFile(this);
Stephen Hines651f13c2014-04-23 16:59:28 -07001124 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1125 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001126 }
1127
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001128 if (!Act->Execute())
1129 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001130
1131 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001132
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001133 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001134
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001135 FailedParseDiagnostics.clear();
1136
Douglas Gregorabc563f2010-07-19 21:46:24 +00001137 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001138
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001139error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001140 // Remove the overridden buffer we used for the preamble.
Stephen Hines176edba2014-12-01 14:53:08 -08001141 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001142
1143 // Keep the ownership of the data in the ASTUnit because the client may
1144 // want to see the diagnostics.
1145 transferASTDataFromCompilerInstance(*Clang);
1146 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001147 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001148 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001149 return true;
1150}
1151
Douglas Gregor44c181a2010-07-23 00:33:23 +00001152/// \brief Simple function to retrieve a path for a preamble precompiled header.
1153static std::string GetPreamblePCHPath() {
Douglas Gregor424668c2010-09-11 18:05:19 +00001154 // FIXME: This is a hack so that we can override the preamble file during
1155 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindola85d28482013-06-26 04:02:37 +00001156 // are not necessarily cleaned up.
Douglas Gregor424668c2010-09-11 18:05:19 +00001157 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1158 if (TmpFile)
1159 return TmpFile;
Rafael Espindola85d28482013-06-26 04:02:37 +00001160
1161 SmallString<128> Path;
Rafael Espindola1ec4a862013-07-05 20:00:06 +00001162 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindola85d28482013-06-26 04:02:37 +00001163
1164 return Path.str();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001165}
1166
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001167/// \brief Compute the preamble for the main file, providing the source buffer
1168/// that corresponds to the main file along with a pair (bytes, start-of-line)
1169/// that describes the preamble.
Stephen Hines176edba2014-12-01 14:53:08 -08001170ASTUnit::ComputedPreamble
1171ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001172 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001173 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001174
Douglas Gregor44c181a2010-07-23 00:33:23 +00001175 // Try to determine if the main file has been remapped, either from the
1176 // command line (to another file) or directly through the compiler invocation
1177 // (to a memory buffer).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001178 llvm::MemoryBuffer *Buffer = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08001179 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindola105b2072013-06-18 19:40:07 +00001180 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola44888352013-07-29 21:26:52 +00001181 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001182 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001183 // Check whether there is a file-file remapping of the main file
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001184 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1185 std::string MPath(RF.first);
Rafael Espindola44888352013-07-29 21:26:52 +00001186 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001187 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001188 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001189 // We found a remapping. Try to load the resulting, remapped source.
Stephen Hines176edba2014-12-01 14:53:08 -08001190 BufferOwner = getBufferForFile(RF.second);
1191 if (!BufferOwner)
1192 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001193 }
1194 }
1195 }
1196
1197 // Check whether there is a file-buffer remapping. It supercedes the
1198 // file-file remapping.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001199 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1200 std::string MPath(RB.first);
Rafael Espindola44888352013-07-29 21:26:52 +00001201 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001202 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001203 if (MainFileID == MID) {
1204 // We found a remapping.
Stephen Hines176edba2014-12-01 14:53:08 -08001205 BufferOwner.reset();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001206 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001207 }
1208 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001209 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001210 }
1211
1212 // If the main source file was not remapped, load it now.
Stephen Hines176edba2014-12-01 14:53:08 -08001213 if (!Buffer && !BufferOwner) {
1214 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1215 if (!BufferOwner)
1216 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217 }
Stephen Hines176edba2014-12-01 14:53:08 -08001218
1219 if (!Buffer)
1220 Buffer = BufferOwner.get();
1221 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1222 *Invocation.getLangOpts(), MaxLines);
1223 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1224 Pre.second);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001225}
1226
Stephen Hines651f13c2014-04-23 16:59:28 -07001227ASTUnit::PreambleFileHash
1228ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1229 PreambleFileHash Result;
1230 Result.Size = Size;
1231 Result.ModTime = ModTime;
1232 memset(Result.MD5, 0, sizeof(Result.MD5));
Douglas Gregor754f3492010-07-24 00:38:13 +00001233 return Result;
1234}
1235
Stephen Hines651f13c2014-04-23 16:59:28 -07001236ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1237 const llvm::MemoryBuffer *Buffer) {
1238 PreambleFileHash Result;
1239 Result.Size = Buffer->getBufferSize();
1240 Result.ModTime = 0;
1241
1242 llvm::MD5 MD5Ctx;
1243 MD5Ctx.update(Buffer->getBuffer().data());
1244 MD5Ctx.final(Result.MD5);
1245
1246 return Result;
1247}
1248
1249namespace clang {
1250bool operator==(const ASTUnit::PreambleFileHash &LHS,
1251 const ASTUnit::PreambleFileHash &RHS) {
1252 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1253 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1254}
1255} // namespace clang
1256
1257static std::pair<unsigned, unsigned>
1258makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1259 const LangOptions &LangOpts) {
1260 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1261 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1262 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1263 return std::make_pair(Offset, EndOffset);
1264}
1265
Stephen Hines176edba2014-12-01 14:53:08 -08001266static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1267 const LangOptions &LangOpts,
1268 const FixItHint &InFix) {
1269 ASTUnit::StandaloneFixIt OutFix;
Stephen Hines651f13c2014-04-23 16:59:28 -07001270 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1271 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1272 LangOpts);
1273 OutFix.CodeToInsert = InFix.CodeToInsert;
1274 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Stephen Hines176edba2014-12-01 14:53:08 -08001275 return OutFix;
Stephen Hines651f13c2014-04-23 16:59:28 -07001276}
1277
Stephen Hines176edba2014-12-01 14:53:08 -08001278static ASTUnit::StandaloneDiagnostic
1279makeStandaloneDiagnostic(const LangOptions &LangOpts,
1280 const StoredDiagnostic &InDiag) {
1281 ASTUnit::StandaloneDiagnostic OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001282 OutDiag.ID = InDiag.getID();
1283 OutDiag.Level = InDiag.getLevel();
1284 OutDiag.Message = InDiag.getMessage();
1285 OutDiag.LocOffset = 0;
1286 if (InDiag.getLocation().isInvalid())
Stephen Hines176edba2014-12-01 14:53:08 -08001287 return OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001288 const SourceManager &SM = InDiag.getLocation().getManager();
1289 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1290 OutDiag.Filename = SM.getFilename(FileLoc);
1291 if (OutDiag.Filename.empty())
Stephen Hines176edba2014-12-01 14:53:08 -08001292 return OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001293 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001294 for (const CharSourceRange &Range : InDiag.getRanges())
1295 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1296 for (const FixItHint &FixIt : InDiag.getFixIts())
1297 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Stephen Hines176edba2014-12-01 14:53:08 -08001298
1299 return OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001300}
1301
Douglas Gregor175c4a92010-07-23 23:58:40 +00001302/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1303/// the source file.
1304///
1305/// This routine will compute the preamble of the main source file. If a
1306/// non-trivial preamble is found, it will precompile that preamble into a
1307/// precompiled header so that the precompiled preamble can be used to reduce
1308/// reparsing time. If a precompiled preamble has already been constructed,
1309/// this routine will determine if it is still valid and, if so, avoid
1310/// rebuilding the precompiled preamble.
1311///
Douglas Gregordf95a132010-08-09 20:45:32 +00001312/// \param AllowRebuild When true (the default), this routine is
1313/// allowed to rebuild the precompiled preamble if it is found to be
1314/// out-of-date.
1315///
1316/// \param MaxLines When non-zero, the maximum number of lines that
1317/// can occur within the preamble.
1318///
Douglas Gregor754f3492010-07-24 00:38:13 +00001319/// \returns If the precompiled preamble can be used, returns a newly-allocated
1320/// buffer that should be used in place of the main file when doing so.
1321/// Otherwise, returns a NULL pointer.
Stephen Hines176edba2014-12-01 14:53:08 -08001322std::unique_ptr<llvm::MemoryBuffer>
1323ASTUnit::getMainBufferWithPrecompiledPreamble(
1324 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1325 unsigned MaxLines) {
1326
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001327 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001328 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1329 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001330 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001331 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001332
Stephen Hines176edba2014-12-01 14:53:08 -08001333 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001334
Stephen Hines176edba2014-12-01 14:53:08 -08001335 if (!NewPreamble.Size) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001336 // We couldn't find a preamble in the main source. Clear out the current
1337 // preamble, if we have one. It's obviously no good any more.
1338 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001339 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001340
1341 // The next time we actually see a preamble, precompile it.
1342 PreambleRebuildCounter = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001343 return nullptr;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001344 }
1345
1346 if (!Preamble.empty()) {
1347 // We've previously computed a preamble. Check whether we have the same
1348 // preamble now that we did before, and that there's enough space in
1349 // the main-file buffer within the precompiled preamble to fit the
1350 // new main file.
Stephen Hines176edba2014-12-01 14:53:08 -08001351 if (Preamble.size() == NewPreamble.Size &&
1352 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1353 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1354 NewPreamble.Size) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001355 // The preamble has not changed. We may be able to re-use the precompiled
1356 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001357
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001358 // Check that none of the files used by the preamble have changed.
1359 bool AnyFileChanged = false;
1360
1361 // First, make a record of those files that have been overridden via
1362 // remapping or unsaved_files.
Stephen Hines651f13c2014-04-23 16:59:28 -07001363 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001364 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1365 if (AnyFileChanged)
1366 break;
1367
Stephen Hines651f13c2014-04-23 16:59:28 -07001368 vfs::Status Status;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001369 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001370 // If we can't stat the file we're remapping to, assume that something
1371 // horrible happened.
1372 AnyFileChanged = true;
1373 break;
1374 }
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001375
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001376 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001377 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001378 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001379
1380 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1381 if (AnyFileChanged)
1382 break;
1383 OverriddenFiles[RB.first] =
1384 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001385 }
1386
1387 // Check whether anything has changed.
Stephen Hines651f13c2014-04-23 16:59:28 -07001388 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001389 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1390 !AnyFileChanged && F != FEnd;
1391 ++F) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001392 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001393 = OverriddenFiles.find(F->first());
1394 if (Overridden != OverriddenFiles.end()) {
1395 // This file was remapped; check whether the newly-mapped file
1396 // matches up with the previous mapping.
1397 if (Overridden->second != F->second)
1398 AnyFileChanged = true;
1399 continue;
1400 }
1401
1402 // The file was not remapped; check whether it has changed on disk.
Stephen Hines651f13c2014-04-23 16:59:28 -07001403 vfs::Status Status;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001404 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001405 // If we can't stat the file, assume that something horrible happened.
1406 AnyFileChanged = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001407 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001408 Status.getLastModificationTime().toEpochTime() !=
Stephen Hines651f13c2014-04-23 16:59:28 -07001409 uint64_t(F->second.ModTime))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001410 AnyFileChanged = true;
1411 }
1412
1413 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001414 // Okay! We can re-use the precompiled preamble.
1415
1416 // Set the state of the diagnostic object to mimic its state
1417 // after parsing the preamble.
1418 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001419 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001420 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001421 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001422
Stephen Hines651f13c2014-04-23 16:59:28 -07001423 return llvm::MemoryBuffer::getMemBufferCopy(
Stephen Hines176edba2014-12-01 14:53:08 -08001424 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001425 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001426 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001427
1428 // If we aren't allowed to rebuild the precompiled preamble, just
1429 // return now.
1430 if (!AllowRebuild)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001431 return nullptr;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001432
Douglas Gregor175c4a92010-07-23 23:58:40 +00001433 // We can't reuse the previously-computed preamble. Build a new one.
1434 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001435 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001436 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001437 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001438 } else if (!AllowRebuild) {
1439 // We aren't allowed to rebuild the precompiled preamble; just
1440 // return now.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001441 return nullptr;
Douglas Gregordf95a132010-08-09 20:45:32 +00001442 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001443
1444 // If the preamble rebuild counter > 1, it's because we previously
1445 // failed to build a preamble and we're not yet ready to try
1446 // again. Decrement the counter and return a failure.
1447 if (PreambleRebuildCounter > 1) {
1448 --PreambleRebuildCounter;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001449 return nullptr;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001450 }
1451
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001452 // Create a temporary file for the precompiled preamble. In rare
1453 // circumstances, this can fail.
1454 std::string PreamblePCHPath = GetPreamblePCHPath();
1455 if (PreamblePCHPath.empty()) {
1456 // Try again next time.
1457 PreambleRebuildCounter = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001458 return nullptr;
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001459 }
1460
Douglas Gregor175c4a92010-07-23 23:58:40 +00001461 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001462 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001463 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor175c4a92010-07-23 23:58:40 +00001464
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001465 // Save the preamble text for later; we'll need to compare against it for
1466 // subsequent reparses.
Stephen Hines651f13c2014-04-23 16:59:28 -07001467 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001468 Preamble.assign(FileMgr->getFile(MainFilename),
Stephen Hines176edba2014-12-01 14:53:08 -08001469 NewPreamble.Buffer->getBufferStart(),
1470 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1471 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001472
Stephen Hines176edba2014-12-01 14:53:08 -08001473 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1474 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001475
Douglas Gregor44c181a2010-07-23 00:33:23 +00001476 // Remap the main source file to the preamble buffer.
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001477 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Stephen Hines176edba2014-12-01 14:53:08 -08001478 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001479
Douglas Gregor44c181a2010-07-23 00:33:23 +00001480 // Tell the compiler invocation to generate a temporary precompiled header.
1481 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001482 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001483 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001484 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1485 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001486
1487 // Create the compiler instance to use for building the precompiled preamble.
Stephen Hines651f13c2014-04-23 16:59:28 -07001488 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001489
1490 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001491 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1492 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001493
Douglas Gregor01b6e312011-07-01 18:22:13 +00001494 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001495 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001496
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001497 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001498 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001499
1500 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001501 Clang->setTarget(TargetInfo::CreateTargetInfo(
1502 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001503 if (!Clang->hasTarget()) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001504 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001505 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001506 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001507 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001508 return nullptr;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001509 }
1510
1511 // Inform the target of the language options.
1512 //
1513 // FIXME: We shouldn't need to do this, the target should be immutable once
1514 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001515 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516
Ted Kremenek03201fb2011-03-21 18:40:07 +00001517 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001518 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001519 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001520 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001521 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 "IR inputs not support here!");
1523
1524 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001525 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001526 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001527 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001528 TopLevelDecls.clear();
1529 TopLevelDeclsInPreamble.clear();
Stephen Hines651f13c2014-04-23 16:59:28 -07001530 PreambleDiagnostics.clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001531
1532 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1533 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1534 if (!VFS)
1535 return nullptr;
1536
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537 // Create a file manager object to provide access to and cache the filesystem.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001538 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001539
1540 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001541 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001542 Clang->getFileManager()));
Stephen Hines651f13c2014-04-23 16:59:28 -07001543
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001544 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1545 Clang->addDependencyCollector(PreambleDepCollector);
1546
Stephen Hines651f13c2014-04-23 16:59:28 -07001547 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001548 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001549 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001550 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001551 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001552 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001553 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001554 return nullptr;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001555 }
1556
1557 Act->Execute();
Stephen Hines651f13c2014-04-23 16:59:28 -07001558
1559 // Transfer any diagnostics generated when parsing the preamble into the set
1560 // of preamble diagnostics.
Stephen Hines176edba2014-12-01 14:53:08 -08001561 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1562 E = stored_diag_end();
1563 I != E; ++I)
1564 PreambleDiagnostics.push_back(
1565 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Stephen Hines651f13c2014-04-23 16:59:28 -07001566
Douglas Gregor44c181a2010-07-23 00:33:23 +00001567 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001568
Stephen Hines651f13c2014-04-23 16:59:28 -07001569 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1570
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001571 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001572 // The preamble PCH failed (e.g. there was a module loading fatal error),
1573 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001574 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindola21b18242013-06-26 04:26:38 +00001575 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001576 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001577 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001578 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001579 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001580 return nullptr;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001581 }
1582
1583 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001584 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001585 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001586
1587 // Keep track of all of the files that the source manager knows about,
1588 // so we can verify whether they have changed or not.
1589 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001590 SourceManager &SourceMgr = Clang->getSourceManager();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001591 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1592 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1593 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001594 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001595 if (time_t ModTime = File->getModificationTime()) {
1596 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001597 File->getSize(), ModTime);
Stephen Hines651f13c2014-04-23 16:59:28 -07001598 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001599 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Stephen Hines651f13c2014-04-23 16:59:28 -07001600 FilesInPreamble[File->getName()] =
1601 PreambleFileHash::createForMemoryBuffer(Buffer);
1602 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001603 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001604
Douglas Gregoreababfb2010-08-04 05:53:38 +00001605 PreambleRebuildCounter = 1;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001606 PreprocessorOpts.RemappedFileBuffers.pop_back();
1607
Douglas Gregor9b7db622011-02-16 18:16:54 +00001608 // If the hash of top-level entities differs from the hash of the top-level
1609 // entities the last time we rebuilt the preamble, clear out the completion
1610 // cache.
1611 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1612 CompletionCacheTopLevelHashValue = 0;
1613 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1614 }
Stephen Hines176edba2014-12-01 14:53:08 -08001615
1616 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001617 MainFilename);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001618}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001619
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001620void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1621 std::vector<Decl *> Resolved;
1622 Resolved.reserve(TopLevelDeclsInPreamble.size());
1623 ExternalASTSource &Source = *getASTContext().getExternalSource();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001624 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001625 // Resolve the declaration ID to an actual declaration, possibly
1626 // deserializing the declaration in the process.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001627 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001628 Resolved.push_back(D);
1629 }
1630 TopLevelDeclsInPreamble.clear();
1631 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1632}
1633
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001634void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001635 // Steal the created target, context, and preprocessor if they have been
1636 // created.
1637 assert(CI.hasInvocation() && "missing invocation");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001638 LangOpts = CI.getInvocation().LangOpts;
Stephen Hines176edba2014-12-01 14:53:08 -08001639 TheSema = CI.takeSema();
1640 Consumer = CI.takeASTConsumer();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001641 if (CI.hasASTContext())
1642 Ctx = &CI.getASTContext();
1643 if (CI.hasPreprocessor())
1644 PP = &CI.getPreprocessor();
1645 CI.setSourceManager(nullptr);
1646 CI.setFileManager(nullptr);
1647 if (CI.hasTarget())
1648 Target = &CI.getTarget();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001649 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001650 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001651}
1652
Chris Lattner5f9e2722011-07-23 10:55:15 +00001653StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001654 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1655 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1656 if (Input.isFile())
1657 return Input.getFile();
1658 else
1659 return Input.getBuffer()->getBufferIdentifier();
1660 }
1661
1662 if (SourceMgr) {
1663 if (const FileEntry *
1664 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1665 return FE->getName();
1666 }
1667
1668 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001669}
1670
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001671StringRef ASTUnit::getASTFileName() const {
1672 if (!isMainFileAST())
1673 return StringRef();
1674
1675 serialization::ModuleFile &
1676 Mod = Reader->getModuleManager().getPrimaryModule();
1677 return Mod.FileName;
1678}
1679
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001680ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001681 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001682 bool CaptureDiagnostics,
1683 bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001684 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001685 AST.reset(new ASTUnit(false));
Stephen Hines176edba2014-12-01 14:53:08 -08001686 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001687 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001688 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001689 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001690 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1691 createVFSFromCompilerInvocation(*CI, *Diags);
1692 if (!VFS)
1693 return nullptr;
1694 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001695 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1696 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1697 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001698
Stephen Hines651f13c2014-04-23 16:59:28 -07001699 return AST.release();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001700}
1701
Stephen Hines651f13c2014-04-23 16:59:28 -07001702ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1703 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1704 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1705 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1706 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1707 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1708 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001709 assert(CI && "A CompilerInvocation is required");
1710
Stephen Hines651f13c2014-04-23 16:59:28 -07001711 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001712 ASTUnit *AST = Unit;
1713 if (!AST) {
1714 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001715 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001716 AST = OwnAST.get();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001717 if (!AST)
1718 return nullptr;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001719 }
1720
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001721 if (!ResourceFilesPath.empty()) {
1722 // Override the resources path.
1723 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1724 }
1725 AST->OnlyLocalDecls = OnlyLocalDecls;
1726 AST->CaptureDiagnostics = CaptureDiagnostics;
1727 if (PrecompilePreamble)
1728 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001729 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001730 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001731 AST->IncludeBriefCommentsInCodeCompletion
1732 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001733
1734 // Recover resources if we crash before exiting this method.
1735 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001736 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001737 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1738 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001739 DiagCleanup(Diags.get());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001740
1741 // We'll manage file buffers ourselves.
1742 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1743 CI->getFrontendOpts().DisableFree = false;
1744 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1745
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001746 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001747 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001748
1749 // Recover resources if we crash before exiting this method.
1750 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1751 CICleanup(Clang.get());
1752
1753 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001754 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001755
1756 // Set up diagnostics, capturing any diagnostics that would
1757 // otherwise be dropped.
1758 Clang->setDiagnostics(&AST->getDiagnostics());
1759
1760 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001761 Clang->setTarget(TargetInfo::CreateTargetInfo(
1762 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001763 if (!Clang->hasTarget())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001764 return nullptr;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765
1766 // Inform the target of the language options.
1767 //
1768 // FIXME: We shouldn't need to do this, the target should be immutable once
1769 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001770 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001771
1772 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1773 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001774 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001775 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001776 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001777 "IR inputs not supported here!");
1778
1779 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001780 AST->TheSema.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001781 AST->Ctx = nullptr;
1782 AST->PP = nullptr;
1783 AST->Reader = nullptr;
1784
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001785 // Create a file manager object to provide access to and cache the filesystem.
1786 Clang->setFileManager(&AST->getFileManager());
1787
1788 // Create the source manager.
1789 Clang->setSourceManager(&AST->getSourceManager());
1790
1791 ASTFrontendAction *Act = Action;
1792
Stephen Hines651f13c2014-04-23 16:59:28 -07001793 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001794 if (!Act) {
1795 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1796 Act = TrackerAct.get();
1797 }
1798
1799 // Recover resources if we crash before exiting this method.
1800 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1801 ActCleanup(TrackerAct.get());
1802
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001803 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1804 AST->transferASTDataFromCompilerInstance(*Clang);
1805 if (OwnAST && ErrAST)
1806 ErrAST->swap(OwnAST);
1807
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001808 return nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001809 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001810
1811 if (Persistent && !TrackerAct) {
1812 Clang->getPreprocessor().addPPCallbacks(
Stephen Hines176edba2014-12-01 14:53:08 -08001813 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1814 AST->getCurrentTopLevelHashValue()));
1815 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001816 if (Clang->hasASTConsumer())
1817 Consumers.push_back(Clang->takeASTConsumer());
Stephen Hines176edba2014-12-01 14:53:08 -08001818 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1819 *AST, AST->getCurrentTopLevelHashValue()));
1820 Clang->setASTConsumer(
1821 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001822 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001823 if (!Act->Execute()) {
1824 AST->transferASTDataFromCompilerInstance(*Clang);
1825 if (OwnAST && ErrAST)
1826 ErrAST->swap(OwnAST);
1827
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001828 return nullptr;
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001829 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001830
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001831 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001832 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001833
1834 Act->EndSourceFile();
1835
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001836 if (OwnAST)
Stephen Hines651f13c2014-04-23 16:59:28 -07001837 return OwnAST.release();
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001838 else
1839 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001840}
1841
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001842bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1843 if (!Invocation)
1844 return true;
1845
1846 // We'll manage file buffers ourselves.
1847 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1848 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001849 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001850
Stephen Hines176edba2014-12-01 14:53:08 -08001851 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001852 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001853 PreambleRebuildCounter = 2;
Stephen Hines176edba2014-12-01 14:53:08 -08001854 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001855 }
1856
Douglas Gregor213f18b2010-10-28 15:44:59 +00001857 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001858 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001859
Ted Kremenek25a11e12011-03-22 01:15:24 +00001860 // Recover resources if we crash before exiting this method.
1861 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Stephen Hines176edba2014-12-01 14:53:08 -08001862 MemBufferCleanup(OverrideMainBuffer.get());
1863
1864 return Parse(std::move(OverrideMainBuffer));
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001865}
1866
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001867std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1868 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1869 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1870 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1871 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001872 // Create the AST unit.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001873 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Stephen Hines176edba2014-12-01 14:53:08 -08001874 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001875 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001876 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001877 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001878 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001879 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001880 AST->IncludeBriefCommentsInCodeCompletion
1881 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001882 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001883 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001884 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1885 createVFSFromCompilerInvocation(*CI, *Diags);
1886 if (!VFS)
1887 return nullptr;
1888 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001889 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001890
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001891 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001892 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1893 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001894 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1895 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001896 DiagCleanup(Diags.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001897
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001898 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1899 return nullptr;
1900 return AST;
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001901}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001902
Stephen Hines651f13c2014-04-23 16:59:28 -07001903ASTUnit *ASTUnit::LoadFromCommandLine(
1904 const char **ArgBegin, const char **ArgEnd,
1905 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1906 bool OnlyLocalDecls, bool CaptureDiagnostics,
1907 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1908 bool PrecompilePreamble, TranslationUnitKind TUKind,
1909 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1910 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1911 bool UserFilesAreVolatile, bool ForSerialization,
1912 std::unique_ptr<ASTUnit> *ErrAST) {
Stephen Hines176edba2014-12-01 14:53:08 -08001913 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar7b556682009-12-02 03:23:45 +00001914
Chris Lattner5f9e2722011-07-23 10:55:15 +00001915 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001916
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001917 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001918
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001919 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001920
Douglas Gregore47be3e2010-11-11 00:39:14 +00001921 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001922 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001923
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001924 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001925 llvm::makeArrayRef(ArgBegin, ArgEnd),
1926 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001927 if (!CI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001928 return nullptr;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001929 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001930
Douglas Gregor4db64a42010-01-23 00:14:00 +00001931 // Override any files that need remapping
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001932 for (const auto &RemappedFile : RemappedFiles) {
1933 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1934 RemappedFile.second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001935 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001936 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1937 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1938 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001939
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001940 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001941 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001942
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001943 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1944
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001945 // Create the AST unit.
Stephen Hines651f13c2014-04-23 16:59:28 -07001946 std::unique_ptr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001947 AST.reset(new ASTUnit(false));
Stephen Hines176edba2014-12-01 14:53:08 -08001948 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001949 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001950 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001951 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1952 createVFSFromCompilerInvocation(*CI, *Diags);
1953 if (!VFS)
1954 return nullptr;
1955 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001956 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001957 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001958 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001959 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001960 AST->IncludeBriefCommentsInCodeCompletion
1961 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001962 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001963 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001964 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001965 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001966 if (ForSerialization)
1967 AST->WriterData.reset(new ASTWriterData());
Stephen Hines176edba2014-12-01 14:53:08 -08001968 // Zero out now to ease cleanup during crash recovery.
1969 CI = nullptr;
1970 Diags = nullptr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001971
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001972 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001973 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1974 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001975
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001976 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1977 // Some error occurred, if caller wants to examine diagnostics, pass it the
1978 // ASTUnit.
1979 if (ErrAST) {
1980 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1981 ErrAST->swap(AST);
1982 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001983 return nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001984 }
1985
Stephen Hines651f13c2014-04-23 16:59:28 -07001986 return AST.release();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001987}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001988
Stephen Hines651f13c2014-04-23 16:59:28 -07001989bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001990 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001991 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001992
1993 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001994
Douglas Gregor213f18b2010-10-28 15:44:59 +00001995 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001996 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001997
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001998 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001999 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002000 for (const auto &RB : PPOpts.RemappedFileBuffers)
2001 delete RB.second;
2002
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002003 Invocation->getPreprocessorOpts().clearRemappedFiles();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002004 for (const auto &RemappedFile : RemappedFiles) {
2005 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2006 RemappedFile.second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002007 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002008
Douglas Gregoreababfb2010-08-04 05:53:38 +00002009 // If we have a preamble file lying around, or if we might try to
2010 // build a precompiled preamble, do so now.
Stephen Hines176edba2014-12-01 14:53:08 -08002011 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek1872b312011-10-27 17:55:18 +00002012 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002013 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002014
Douglas Gregorabc563f2010-07-19 21:46:24 +00002015 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002016 getDiagnostics().Reset();
2017 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002018 if (OverrideMainBuffer)
2019 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002020
Douglas Gregor175c4a92010-07-23 23:58:40 +00002021 // Parse the sources
Stephen Hines176edba2014-12-01 14:53:08 -08002022 bool Result = Parse(std::move(OverrideMainBuffer));
2023
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002024 // If we're caching global code-completion results, and the top-level
2025 // declarations have changed, clear out the code-completion cache.
2026 if (!Result && ShouldCacheCodeCompletionResults &&
2027 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2028 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002029
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002030 // We now need to clear out the completion info related to this translation
2031 // unit; it'll be recreated if necessary.
2032 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002033
Douglas Gregor175c4a92010-07-23 23:58:40 +00002034 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002035}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002036
Douglas Gregor87c08a52010-08-13 22:48:40 +00002037//----------------------------------------------------------------------------//
2038// Code completion
2039//----------------------------------------------------------------------------//
2040
2041namespace {
2042 /// \brief Code completion consumer that combines the cached code-completion
2043 /// results from an ASTUnit with the code-completion results provided to it,
2044 /// then passes the result on to
2045 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002046 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002047 ASTUnit &AST;
2048 CodeCompleteConsumer &Next;
2049
2050 public:
2051 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002052 const CodeCompleteOptions &CodeCompleteOpts)
2053 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2054 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002055 {
2056 // Compute the set of contexts in which we will look when we don't have
2057 // any information about the specific context.
2058 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002059 = (1LL << CodeCompletionContext::CCC_TopLevel)
2060 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2061 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2062 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2063 | (1LL << CodeCompletionContext::CCC_Statement)
2064 | (1LL << CodeCompletionContext::CCC_Expression)
2065 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2066 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2067 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2068 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2069 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2070 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2071 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002072
David Blaikie4e4d0842012-03-11 07:00:24 +00002073 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002074 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2075 | (1LL << CodeCompletionContext::CCC_UnionTag)
2076 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002077 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002078
2079 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2080 CodeCompletionResult *Results,
2081 unsigned NumResults) override;
2082
2083 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2084 OverloadCandidate *Candidates,
2085 unsigned NumCandidates) override {
Douglas Gregor87c08a52010-08-13 22:48:40 +00002086 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2087 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002088
2089 CodeCompletionAllocator &getAllocator() override {
Douglas Gregor218937c2011-02-01 19:23:04 +00002090 return Next.getAllocator();
2091 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002092
Stephen Hines651f13c2014-04-23 16:59:28 -07002093 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002094 return Next.getCodeCompletionTUInfo();
2095 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002096 };
2097}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002098
Douglas Gregor5f808c22010-08-16 21:18:39 +00002099/// \brief Helper function that computes which global names are hidden by the
2100/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002101static void CalculateHiddenNames(const CodeCompletionContext &Context,
2102 CodeCompletionResult *Results,
2103 unsigned NumResults,
2104 ASTContext &Ctx,
2105 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002106 bool OnlyTagNames = false;
2107 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002108 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002109 case CodeCompletionContext::CCC_TopLevel:
2110 case CodeCompletionContext::CCC_ObjCInterface:
2111 case CodeCompletionContext::CCC_ObjCImplementation:
2112 case CodeCompletionContext::CCC_ObjCIvarList:
2113 case CodeCompletionContext::CCC_ClassStructUnion:
2114 case CodeCompletionContext::CCC_Statement:
2115 case CodeCompletionContext::CCC_Expression:
2116 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002117 case CodeCompletionContext::CCC_DotMemberAccess:
2118 case CodeCompletionContext::CCC_ArrowMemberAccess:
2119 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002120 case CodeCompletionContext::CCC_Namespace:
2121 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002122 case CodeCompletionContext::CCC_Name:
2123 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002124 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002125 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002126 break;
2127
2128 case CodeCompletionContext::CCC_EnumTag:
2129 case CodeCompletionContext::CCC_UnionTag:
2130 case CodeCompletionContext::CCC_ClassOrStructTag:
2131 OnlyTagNames = true;
2132 break;
2133
2134 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002135 case CodeCompletionContext::CCC_MacroName:
2136 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002137 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002138 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002139 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002140 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002141 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002142 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002143 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002144 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2145 case CodeCompletionContext::CCC_ObjCClassMessage:
2146 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002147 // We're looking for nothing, or we're looking for names that cannot
2148 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002149 return;
2150 }
2151
John McCall0a2c5e22010-08-25 06:19:51 +00002152 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002153 for (unsigned I = 0; I != NumResults; ++I) {
2154 if (Results[I].Kind != Result::RK_Declaration)
2155 continue;
2156
2157 unsigned IDNS
2158 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2159
2160 bool Hiding = false;
2161 if (OnlyTagNames)
2162 Hiding = (IDNS & Decl::IDNS_Tag);
2163 else {
2164 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002165 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2166 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002167 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002168 HiddenIDNS |= Decl::IDNS_Tag;
2169 Hiding = (IDNS & HiddenIDNS);
2170 }
2171
2172 if (!Hiding)
2173 continue;
2174
2175 DeclarationName Name = Results[I].Declaration->getDeclName();
2176 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2177 HiddenNames.insert(Identifier->getName());
2178 else
2179 HiddenNames.insert(Name.getAsString());
2180 }
2181}
2182
2183
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002184void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2185 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002186 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002187 unsigned NumResults) {
2188 // Merge the results we were given with the results we cached.
2189 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002190 uint64_t InContexts =
2191 Context.getKind() == CodeCompletionContext::CCC_Recovery
2192 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002193 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002194 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002195 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002196 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002197 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002198 C = AST.cached_completion_begin(),
2199 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002200 C != CEnd; ++C) {
2201 // If the context we are in matches any of the contexts we are
2202 // interested in, we'll add this result.
2203 if ((C->ShowInContexts & InContexts) == 0)
2204 continue;
2205
2206 // If we haven't added any results previously, do so now.
2207 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002208 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2209 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002210 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2211 AddedResult = true;
2212 }
2213
Douglas Gregor5f808c22010-08-16 21:18:39 +00002214 // Determine whether this global completion result is hidden by a local
2215 // completion result. If so, skip it.
2216 if (C->Kind != CXCursor_MacroDefinition &&
2217 HiddenNames.count(C->Completion->getTypedText()))
2218 continue;
2219
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002220 // Adjust priority based on similar type classes.
2221 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002222 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002223 if (!Context.getPreferredType().isNull()) {
2224 if (C->Kind == CXCursor_MacroDefinition) {
2225 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002226 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002227 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002228 } else if (C->Type) {
2229 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002230 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002231 Context.getPreferredType().getUnqualifiedType());
2232 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2233 if (ExpectedSTC == C->TypeClass) {
2234 // We know this type is similar; check for an exact match.
2235 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002236 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002237 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002238 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002239 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2240 Priority /= CCF_ExactTypeMatch;
2241 else
2242 Priority /= CCF_SimilarTypeMatch;
2243 }
2244 }
2245 }
2246
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002247 // Adjust the completion string, if required.
2248 if (C->Kind == CXCursor_MacroDefinition &&
2249 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2250 // Create a new code-completion string that just contains the
2251 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002252 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2253 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002254 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002255 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002256 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002257 }
2258
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002259 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002260 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002261 }
2262
2263 // If we did not add any cached completion results, just forward the
2264 // results we were given to the next consumer.
2265 if (!AddedResult) {
2266 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2267 return;
2268 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002269
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002270 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2271 AllResults.size());
2272}
2273
2274
2275
Chris Lattner5f9e2722011-07-23 10:55:15 +00002276void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Stephen Hines651f13c2014-04-23 16:59:28 -07002277 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002278 bool IncludeMacros,
2279 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002280 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002281 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002282 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002283 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002284 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2285 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002286 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002287 return;
2288
Douglas Gregor213f18b2010-10-28 15:44:59 +00002289 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002290 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002291 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002292
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002293 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002294 CCInvocation(new CompilerInvocation(*Invocation));
2295
2296 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002297 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002298 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002299
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002300 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2301 CachedCompletionResults.empty();
2302 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2303 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2304 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2305
2306 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2307
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002308 FrontendOpts.CodeCompletionAt.FileName = File;
2309 FrontendOpts.CodeCompletionAt.Line = Line;
2310 FrontendOpts.CodeCompletionAt.Column = Column;
2311
2312 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002313 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002314
Stephen Hines176edba2014-12-01 14:53:08 -08002315 // Spell-checking and warnings are wasteful during code-completion.
2316 LangOpts.SpellChecking = false;
2317 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2318
Stephen Hines651f13c2014-04-23 16:59:28 -07002319 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002320
2321 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002322 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2323 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002324
Ted Kremenek4f327862011-03-21 18:40:17 +00002325 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002326 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002327
2328 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002329 Clang->setDiagnostics(&Diag);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002330 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002331 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002332 StoredDiagnostics);
Manuel Klimekf0c06a32013-07-18 14:23:12 +00002333 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002334
2335 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002336 Clang->setTarget(TargetInfo::CreateTargetInfo(
2337 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002338 if (!Clang->hasTarget()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002339 Clang->setInvocation(nullptr);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002340 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341 }
2342
2343 // Inform the target of the language options.
2344 //
2345 // FIXME: We shouldn't need to do this, the target should be immutable once
2346 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002347 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348
Ted Kremenek03201fb2011-03-21 18:40:07 +00002349 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002350 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002351 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002352 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002353 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354 "IR inputs not support here!");
2355
2356
2357 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002358 Clang->setFileManager(&FileMgr);
2359 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002360
2361 // Remap files.
2362 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002363 PreprocessorOpts.RetainRemappedFileBuffers = true;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002364 for (const auto &RemappedFile : RemappedFiles) {
2365 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2366 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregor2283d792010-08-20 00:59:43 +00002367 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002368
Douglas Gregor87c08a52010-08-13 22:48:40 +00002369 // Use the code completion consumer we were given, but adding any cached
2370 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002371 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002372 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002373 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002374
Douglas Gregordf95a132010-08-09 20:45:32 +00002375 // If we have a precompiled preamble, try to use it. We only allow
2376 // the use of the precompiled preamble if we're if the completion
2377 // point is within the main file, after the end of the precompiled
2378 // preamble.
Stephen Hines176edba2014-12-01 14:53:08 -08002379 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek1872b312011-10-27 17:55:18 +00002380 if (!getPreambleFile(this).empty()) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002381 std::string CompleteFilePath(File);
Rafael Espindola44888352013-07-29 21:26:52 +00002382 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindola105b2072013-06-18 19:40:07 +00002383
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002384 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002385 std::string MainPath(OriginalSourceFile);
Rafael Espindola44888352013-07-29 21:26:52 +00002386 llvm::sys::fs::UniqueID MainID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002387 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002388 if (CompleteFileID == MainID && Line > 1)
Stephen Hines176edba2014-12-01 14:53:08 -08002389 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2390 *CCInvocation, false, Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002391 }
2392 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002393 }
2394
2395 // If the main file has been overridden due to the use of a preamble,
2396 // make that override happen and introduce the preamble.
2397 if (OverrideMainBuffer) {
Stephen Hines176edba2014-12-01 14:53:08 -08002398 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2399 OverrideMainBuffer.get());
Douglas Gregordf95a132010-08-09 20:45:32 +00002400 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2401 PreprocessorOpts.PrecompiledPreambleBytes.second
2402 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002403 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002404 PreprocessorOpts.DisablePCHValidation = true;
Stephen Hines176edba2014-12-01 14:53:08 -08002405
2406 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregorf128fed2010-08-20 00:02:33 +00002407 } else {
2408 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2409 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002410 }
2411
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002412 // Disable the preprocessing record if modules are not enabled.
2413 if (!Clang->getLangOpts().Modules)
2414 PreprocessorOpts.DetailedRecord = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002415
2416 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002417 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002418 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002419 Act->Execute();
2420 Act->EndSourceFile();
2421 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002422}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002423
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002424bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002425 if (HadModuleLoaderFatalFailure)
2426 return true;
2427
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002428 // Write to a temporary file and later rename it to the actual file, to avoid
2429 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002430 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002431 TempPath = File;
2432 TempPath += "-%%%%%%%%";
2433 int fd;
Rafael Espindola70e7aec2013-07-05 21:13:58 +00002434 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002435 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002436
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002437 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2438 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002439 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002440
2441 serialize(Out);
2442 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002443 if (Out.has_error()) {
2444 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002445 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002446 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002447
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002448 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002449 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002450 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002451 }
2452
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002453 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002454}
2455
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002456static bool serializeUnit(ASTWriter &Writer,
2457 SmallVectorImpl<char> &Buffer,
2458 Sema &S,
2459 bool hasErrors,
2460 raw_ostream &OS) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002461 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002462
2463 // Write the generated bitstream to "Out".
2464 if (!Buffer.empty())
2465 OS.write(Buffer.data(), Buffer.size());
2466
2467 return false;
2468}
2469
Chris Lattner5f9e2722011-07-23 10:55:15 +00002470bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002471 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002472
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002473 if (WriterData)
2474 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2475 getSema(), hasErrors, OS);
2476
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002477 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002478 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002479 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002480 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002481}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002482
2483typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2484
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002485void ASTUnit::TranslateStoredDiagnostics(
Stephen Hines651f13c2014-04-23 16:59:28 -07002486 FileManager &FileMgr,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002487 SourceManager &SrcMgr,
Stephen Hines651f13c2014-04-23 16:59:28 -07002488 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002489 SmallVectorImpl<StoredDiagnostic> &Out) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002490 // Map the standalone diagnostic into the new source manager. We also need to
2491 // remap all the locations to the new view. This includes the diag location,
2492 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002493 // FIXME: There should be a cleaner way to do this.
2494
Chris Lattner5f9e2722011-07-23 10:55:15 +00002495 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002496 Result.reserve(Diags.size());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002497 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002498 // Rebuild the StoredDiagnostic.
Stephen Hines651f13c2014-04-23 16:59:28 -07002499 if (SD.Filename.empty())
2500 continue;
2501 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2502 if (!FE)
2503 continue;
2504 FileID FID = SrcMgr.translateFile(FE);
2505 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2506 if (FileLoc.isInvalid())
2507 continue;
2508 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002509 FullSourceLoc Loc(L, SrcMgr);
2510
Chris Lattner5f9e2722011-07-23 10:55:15 +00002511 SmallVector<CharSourceRange, 4> Ranges;
Stephen Hines651f13c2014-04-23 16:59:28 -07002512 Ranges.reserve(SD.Ranges.size());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002513 for (const auto &Range : SD.Ranges) {
2514 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2515 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Stephen Hines651f13c2014-04-23 16:59:28 -07002516 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002517 }
2518
Chris Lattner5f9e2722011-07-23 10:55:15 +00002519 SmallVector<FixItHint, 2> FixIts;
Stephen Hines651f13c2014-04-23 16:59:28 -07002520 FixIts.reserve(SD.FixIts.size());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002521 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002522 FixIts.push_back(FixItHint());
2523 FixItHint &FH = FixIts.back();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002524 FH.CodeToInsert = FixIt.CodeToInsert;
2525 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2526 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Stephen Hines651f13c2014-04-23 16:59:28 -07002527 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002528 }
2529
Stephen Hines651f13c2014-04-23 16:59:28 -07002530 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2531 SD.Message, Loc, Ranges, FixIts));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002532 }
2533 Result.swap(Out);
2534}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002535
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002536void ASTUnit::addFileLevelDecl(Decl *D) {
2537 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002538
2539 // We only care about local declarations.
2540 if (D->isFromASTFile())
2541 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002542
2543 SourceManager &SM = *SourceMgr;
2544 SourceLocation Loc = D->getLocation();
2545 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2546 return;
2547
2548 // We only keep track of the file-level declarations of each file.
2549 if (!D->getLexicalDeclContext()->isFileContext())
2550 return;
2551
2552 SourceLocation FileLoc = SM.getFileLoc(Loc);
2553 assert(SM.isLocalSourceLocation(FileLoc));
2554 FileID FID;
2555 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07002556 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002557 if (FID.isInvalid())
2558 return;
2559
2560 LocDeclsTy *&Decls = FileDecls[FID];
2561 if (!Decls)
2562 Decls = new LocDeclsTy();
2563
2564 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2565
2566 if (Decls->empty() || Decls->back().first <= Offset) {
2567 Decls->push_back(LocDecl);
2568 return;
2569 }
2570
Benjamin Kramer809d2542013-08-24 13:22:59 +00002571 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2572 LocDecl, llvm::less_first());
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002573
2574 Decls->insert(I, LocDecl);
2575}
2576
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002577void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2578 SmallVectorImpl<Decl *> &Decls) {
2579 if (File.isInvalid())
2580 return;
2581
2582 if (SourceMgr->isLoadedFileID(File)) {
2583 assert(Ctx->getExternalSource() && "No external source!");
2584 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2585 Decls);
2586 }
2587
2588 FileDeclsTy::iterator I = FileDecls.find(File);
2589 if (I == FileDecls.end())
2590 return;
2591
2592 LocDeclsTy &LocDecls = *I->second;
2593 if (LocDecls.empty())
2594 return;
2595
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002596 LocDeclsTy::iterator BeginIt =
2597 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002598 std::make_pair(Offset, (Decl *)nullptr),
2599 llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002600 if (BeginIt != LocDecls.begin())
2601 --BeginIt;
2602
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002603 // If we are pointing at a top-level decl inside an objc container, we need
2604 // to backtrack until we find it otherwise we will fail to report that the
2605 // region overlaps with an objc container.
2606 while (BeginIt != LocDecls.begin() &&
2607 BeginIt->second->isTopLevelDeclInObjCContainer())
2608 --BeginIt;
2609
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002610 LocDeclsTy::iterator EndIt = std::upper_bound(
2611 LocDecls.begin(), LocDecls.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002612 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002613 if (EndIt != LocDecls.end())
2614 ++EndIt;
2615
2616 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2617 Decls.push_back(DIt->second);
2618}
2619
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002620SourceLocation ASTUnit::getLocation(const FileEntry *File,
2621 unsigned Line, unsigned Col) const {
2622 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002623 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002624 return SM.getMacroArgExpandedLocation(Loc);
2625}
2626
2627SourceLocation ASTUnit::getLocation(const FileEntry *File,
2628 unsigned Offset) const {
2629 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002630 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002631 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2632}
2633
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002634/// \brief If \arg Loc is a loaded location from the preamble, returns
2635/// the corresponding local location of the main file, otherwise it returns
2636/// \arg Loc.
2637SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2638 FileID PreambleID;
2639 if (SourceMgr)
2640 PreambleID = SourceMgr->getPreambleFileID();
2641
2642 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2643 return Loc;
2644
2645 unsigned Offs;
2646 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2647 SourceLocation FileLoc
2648 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2649 return FileLoc.getLocWithOffset(Offs);
2650 }
2651
2652 return Loc;
2653}
2654
2655/// \brief If \arg Loc is a local location of the main file but inside the
2656/// preamble chunk, returns the corresponding loaded location from the
2657/// preamble, otherwise it returns \arg Loc.
2658SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2659 FileID PreambleID;
2660 if (SourceMgr)
2661 PreambleID = SourceMgr->getPreambleFileID();
2662
2663 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2664 return Loc;
2665
2666 unsigned Offs;
2667 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2668 Offs < Preamble.size()) {
2669 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2670 return FileLoc.getLocWithOffset(Offs);
2671 }
2672
2673 return Loc;
2674}
2675
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002676bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2677 FileID FID;
2678 if (SourceMgr)
2679 FID = SourceMgr->getPreambleFileID();
2680
2681 if (Loc.isInvalid() || FID.isInvalid())
2682 return false;
2683
2684 return SourceMgr->isInFileID(Loc, FID);
2685}
2686
2687bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2688 FileID FID;
2689 if (SourceMgr)
2690 FID = SourceMgr->getMainFileID();
2691
2692 if (Loc.isInvalid() || FID.isInvalid())
2693 return false;
2694
2695 return SourceMgr->isInFileID(Loc, FID);
2696}
2697
2698SourceLocation ASTUnit::getEndOfPreambleFileID() {
2699 FileID FID;
2700 if (SourceMgr)
2701 FID = SourceMgr->getPreambleFileID();
2702
2703 if (FID.isInvalid())
2704 return SourceLocation();
2705
2706 return SourceMgr->getLocForEndOfFile(FID);
2707}
2708
2709SourceLocation ASTUnit::getStartOfMainFileID() {
2710 FileID FID;
2711 if (SourceMgr)
2712 FID = SourceMgr->getMainFileID();
2713
2714 if (FID.isInvalid())
2715 return SourceLocation();
2716
2717 return SourceMgr->getLocForStartOfFile(FID);
2718}
2719
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002720llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002721ASTUnit::getLocalPreprocessingEntities() const {
2722 if (isMainFileAST()) {
2723 serialization::ModuleFile &
2724 Mod = Reader->getModuleManager().getPrimaryModule();
2725 return Reader->getModulePreprocessedEntities(Mod);
2726 }
2727
2728 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002729 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002730
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002731 return llvm::make_range(PreprocessingRecord::iterator(),
2732 PreprocessingRecord::iterator());
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002733}
2734
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002735bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002736 if (isMainFileAST()) {
2737 serialization::ModuleFile &
2738 Mod = Reader->getModuleManager().getPrimaryModule();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002739 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2740 if (!Fn(context, D))
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002741 return false;
2742 }
2743
2744 return true;
2745 }
2746
2747 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2748 TLEnd = top_level_end();
2749 TL != TLEnd; ++TL) {
2750 if (!Fn(context, *TL))
2751 return false;
2752 }
2753
2754 return true;
2755}
2756
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002757namespace {
2758struct PCHLocatorInfo {
2759 serialization::ModuleFile *Mod;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002760 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002761};
2762}
2763
2764static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2765 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2766 switch (M.Kind) {
Stephen Hines176edba2014-12-01 14:53:08 -08002767 case serialization::MK_ImplicitModule:
2768 case serialization::MK_ExplicitModule:
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002769 return true; // skip dependencies.
2770 case serialization::MK_PCH:
2771 Info.Mod = &M;
2772 return true; // found it.
2773 case serialization::MK_Preamble:
2774 return false; // look in dependencies.
2775 case serialization::MK_MainFile:
2776 return false; // look in dependencies.
2777 }
2778
2779 return true;
2780}
2781
2782const FileEntry *ASTUnit::getPCHFile() {
2783 if (!Reader)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002784 return nullptr;
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002785
2786 PCHLocatorInfo Info;
2787 Reader->getModuleManager().visit(PCHLocator, &Info);
2788 if (Info.Mod)
2789 return Info.Mod->File;
2790
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002791 return nullptr;
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002792}
2793
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002794bool ASTUnit::isModuleFile() {
2795 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2796}
2797
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002798void ASTUnit::PreambleData::countLines() const {
2799 NumLines = 0;
2800 if (empty())
2801 return;
2802
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002803 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2804
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002805 if (Buffer.back() != '\n')
2806 ++NumLines;
2807}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002808
2809#ifndef NDEBUG
2810ASTUnit::ConcurrencyState::ConcurrencyState() {
2811 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2812}
2813
2814ASTUnit::ConcurrencyState::~ConcurrencyState() {
2815 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2816}
2817
2818void ASTUnit::ConcurrencyState::start() {
2819 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2820 assert(acquired && "Concurrent access to ASTUnit!");
2821}
2822
2823void ASTUnit::ConcurrencyState::finish() {
2824 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2825}
2826
2827#else // NDEBUG
2828
Stephen Hines651f13c2014-04-23 16:59:28 -07002829ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002830ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2831void ASTUnit::ConcurrencyState::start() {}
2832void ASTUnit::ConcurrencyState::finish() {}
2833
2834#endif