blob: bd9961edc2947a3acd0b8a00ff66ac0adbe7d85f [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-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"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000047#include <atomic>
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor16896c42010-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 Kramerf2e5a912010-11-09 20:00:56 +000060 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000064 }
65
Chris Lattner0e62c1c2011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000069 }
70
Douglas Gregor16896c42010-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 Kremenek06b4f912011-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 Espindolabc7d9492013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek06b4f912011-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 Kremenekbd307a52011-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 Gribenkob2aa9232012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000107
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000108typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-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 Gribenkob2aa9232012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000123 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-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.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000126 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-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 Kremenek06b4f912011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000135 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000136 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000137 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-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 Kremenekbd307a52011-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 Kremenek06b4f912011-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();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000153 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000154 }
155}
156
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000157static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-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() {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000166 for (StringRef File : TemporaryFiles)
167 llvm::sys::fs::remove(File);
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000168 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000173 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis0db720f2012-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 Kyrtzidise54568d2011-10-31 07:19:59 +0000191void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000192 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000193}
194
Ted Kremenek06b4f912011-10-27 17:55:18 +0000195void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
197}
198
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000199void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000201}
202
Douglas Gregorbb420ab2010-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 Gregor68dbaea2010-11-17 00:13:31 +0000209/// \brief Tracks the number of ASTUnit objects that are currently active.
210///
211/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000212static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000213
Douglas Gregord03e8232010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000215 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000216 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000217 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000218 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000219 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000220 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000221 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000222 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000223 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000224 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000225 CompletionCacheTopLevelHashValue(0),
226 PreambleTopLevelHashValue(0),
227 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000228 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000229 if (getenv("LIBCLANG_OBJTRACKING"))
230 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000231}
Douglas Gregord03e8232010-04-05 21:10:19 +0000232
Daniel Dunbar764c0822009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-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 Kyrtzidise54568d2011-10-31 07:19:59 +0000239 clearFileLevelDecls();
240
Ted Kremenek06b4f912011-10-27 17:55:18 +0000241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
243
Douglas Gregor3f4bea02010-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.
Alp Tokerf994cef2014-07-05 03:08:06 +0000248 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000250 for (const auto &RB : PPOpts.RemappedFileBuffers)
251 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000252 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000253
Douglas Gregor16896c42010-10-28 15:44:59 +0000254 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000255
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000256 if (getenv("LIBCLANG_OBJTRACKING"))
257 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000258}
259
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000260void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
261
Douglas Gregor39982192010-08-15 06:18:01 +0000262/// \brief Determine the set of code-completion contexts in which this
263/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000264static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
268
Douglas Gregor39982192010-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 Smith697cc9e2012-08-14 03:13:00 +0000274 uint64_t Contexts = 0;
Douglas Gregor39982192010-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 Smith697cc9e2012-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 Gregor39982192010-08-15 06:18:01 +0000285
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-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 Smith697cc9e2012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-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 Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
Douglas Gregor59cab552010-08-16 23:05:20 +0000303 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000304 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000306 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000307 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000309 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000311
Douglas Gregor39982192010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000314 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000315 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000316 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
317 // Values can appear in these contexts.
Richard Smith697cc9e2012-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 Gregor39982192010-08-15 06:18:01 +0000322 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000324 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000328
329 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000331 }
332
333 return Contexts;
334}
335
Douglas Gregorb14904c2010-08-13 22:48:40 +0000336void ASTUnit::CacheCodeCompletionResults() {
337 if (!TheSema)
338 return;
339
Douglas Gregor16896c42010-10-28 15:44:59 +0000340 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000341 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000342
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
345
346 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000347 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000350 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000352 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000353
354 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000356
357 for (Result &R : Results) {
358 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000359 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000360 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000361 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000362 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 Gregor24747402010-08-16 16:46:30 +0000370
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000371 // Keep track of the type of this completion in an ASTContext-agnostic
372 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000373 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000374 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000375 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-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 Gregor24747402010-08-16 16:46:30 +0000393 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000394
Douglas Gregor39982192010-08-15 06:18:01 +0000395 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000396
397 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000398 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
399 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000400 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-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 Gregor59cab552010-08-16 23:05:20 +0000414
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000415 if (isa<NamespaceDecl>(R.Declaration) ||
416 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000417 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-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.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000424 R.StartsNestedNameSpecifier = true;
425 CachedResult.Completion = R.CreateCodeCompletionString(
426 *TheSema, *CachedCompletionAllocator, CCTUInfo,
427 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-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 Gregorb14904c2010-08-13 22:48:40 +0000435 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000436 }
437
Douglas Gregorb14904c2010-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;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000446 CachedResult.Completion = R.CreateCodeCompletionString(
447 *TheSema, *CachedCompletionAllocator, CCTUInfo,
448 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000449 CachedResult.ShowInContexts
Richard Smith697cc9e2012-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);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000462
463 CachedResult.Priority = R.Priority;
464 CachedResult.Kind = R.CursorKind;
465 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000466 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000467 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000468 CachedCompletionResults.push_back(CachedResult);
469 break;
470 }
471 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000472 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000473
474 // Save the current top-level hash value.
475 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000476}
477
478void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000479 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000480 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000481 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482}
483
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000484namespace {
485
Sebastian Redl2c499f62010-08-18 23:56:43 +0000486/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000487/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000488class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000489 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000490 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000491 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000492 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000493 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregore8bbc122011-09-02 00:18:52 +0000496 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497public:
Alp Toker80758082014-07-06 05:26:44 +0000498 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 Stump11289f42009-09-09 15:08:12 +0000503
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000504 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
505 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000506 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000507 return false;
508
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000509 LangOpt = LangOpts;
510 InitializedLanguage = true;
511
512 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 return false;
514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000516 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
517 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000518 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000519 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000520 return false;
Alp Toker80758082014-07-06 05:26:44 +0000521
522 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
523 Target =
524 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000525
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000526 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000527 return false;
528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Craig Topperafa7cb32014-03-13 06:07:04 +0000530 void ReadCounter(const serialization::ModuleFile &M,
531 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000532 Counter = Value;
533 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000534
535private:
Argyrios Kyrtzidis0db720f2012-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.
Alp Toker74437972014-07-06 05:14:24 +0000544 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000545
546 // Initialize the preprocessor.
547 PP.Initialize(*Target);
548
549 // Initialize the ASTContext
550 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-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 Kyrtzidis9e1fb562012-09-14 20:24:53 +0000556 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000557};
558
Douglas Gregor6b930962013-05-03 22:58:43 +0000559 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000560class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000561 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000562 SourceManager *SourceMgr;
563
Douglas Gregor33cdd812010-02-18 18:08:43 +0000564public:
David Blaikief18d91a2011-09-26 00:01:39 +0000565 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000566 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000567 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000568
Craig Topperafa7cb32014-03-13 06:07:04 +0000569 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000570 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000571 if (PP)
572 SourceMgr = &PP->getSourceManager();
573 }
574
Craig Topperafa7cb32014-03-13 06:07:04 +0000575 void HandleDiagnostic(DiagnosticsEngine::Level Level,
576 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000577};
578
579/// \brief RAII object that optionally captures diagnostics, if
580/// there is no diagnostic client to capture them already.
581class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000582 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000583 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000584 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000585 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000586
587public:
David Blaikie9c902b52011-09-25 23:23:43 +0000588 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000590 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000591 {
Craig Topper49a27902014-05-22 04:46:25 +0000592 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000593 OwningPreviousClient = Diags.takeClient();
594 PreviousClient = Diags.getClient();
595 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000596 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000597 }
598
599 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000600 if (Diags.getClient() == &Client)
601 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000602 }
603};
604
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000605} // anonymous namespace
606
David Blaikief18d91a2011-09-26 00:01:39 +0000607void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000608 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000609 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000610 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000611
Douglas Gregor6b930962013-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 Gregor33cdd812010-02-18 18:08:43 +0000617}
618
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000619ASTMutationListener *ASTUnit::getASTMutationListener() {
620 if (WriterData)
621 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000622 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000623}
624
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000625ASTDeserializationListener *ASTUnit::getDeserializationListener() {
626 if (WriterData)
627 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000628 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000629}
630
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000631std::unique_ptr<llvm::MemoryBuffer>
632ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000633 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000634 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 Kyrtzidis71731d62010-11-03 22:45:23 +0000640}
641
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000642/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000643void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000644 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000645 assert(Diags.get() && "no DiagnosticsEngine was provided");
646 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000647 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000648}
649
David Blaikie6f7382d2014-08-10 19:08:04 +0000650std::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) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000655 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000656
657 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000658 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
659 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000660 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
661 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000662 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000663
Justin Bognerdbbcb112014-10-14 23:36:06 +0000664 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000665
Douglas Gregor16bef852009-10-16 20:01:17 +0000666 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000667 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000668 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000669 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
670 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000671 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000672 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000673 AST->getFileManager(),
674 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000675 AST->HSOpts = new HeaderSearchOptions();
Craig Topper49a27902014-05-22 04:46:25 +0000676
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000677 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000678 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000679 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000680 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000681 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000682
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000683 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000684
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000685 for (const auto &RemappedFile : RemappedFiles)
686 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000687
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000688 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000689
David Blaikie6f7382d2014-08-10 19:08:04 +0000690 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000691 unsigned Counter;
692
Alp Toker96637802014-05-02 03:43:38 +0000693 AST->PP =
694 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
695 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000696 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000697 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698 Preprocessor &PP = *AST->PP;
699
Alp Toker08043432014-05-03 03:46:04 +0000700 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
701 PP.getIdentifierTable(), PP.getSelectorTable(),
702 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000703 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000704
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000705 bool disableValid = false;
706 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
707 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000708 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000709 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000710 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000711 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000712
David Blaikie2721c322014-08-10 16:54:39 +0000713 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
714 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
715 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000716
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000717 // Attach the AST reader to the AST context as an external AST
718 // source, so that declarations will be deserialized from the
719 // AST file as needed.
720 // We need the external source to be set up before we read the AST, because
721 // eagerly-deserialized declarations may use it.
722 Context.setExternalSource(AST->Reader);
723
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000724 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000725 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000726 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000727 break;
Mike Stump11289f42009-09-09 15:08:12 +0000728
Sebastian Redl2c499f62010-08-18 23:56:43 +0000729 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000730 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000731 case ASTReader::OutOfDate:
732 case ASTReader::VersionMismatch:
733 case ASTReader::ConfigurationMismatch:
734 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000735 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000736 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000737 }
Mike Stump11289f42009-09-09 15:08:12 +0000738
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000739 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000740
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000741 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000742
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000743 // Create an AST consumer, even though it isn't used.
744 AST->Consumer.reset(new ASTConsumer);
745
Sebastian Redl2c499f62010-08-18 23:56:43 +0000746 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000747 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
748 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000749 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000750
Douglas Gregor6b930962013-05-03 22:58:43 +0000751 // Tell the diagnostic client that we have started a source file.
752 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
753
David Blaikie6f7382d2014-08-10 19:08:04 +0000754 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000755}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000756
757namespace {
758
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000759/// \brief Preprocessor callback class that updates a hash value with the names
760/// of all macros that have been defined by the translation unit.
761class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
762 unsigned &Hash;
763
764public:
765 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000766
767 void MacroDefined(const Token &MacroNameTok,
768 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000769 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
770 }
771};
772
773/// \brief Add the given declaration to the hash of all top-level entities.
774void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
775 if (!D)
776 return;
777
778 DeclContext *DC = D->getDeclContext();
779 if (!DC)
780 return;
781
782 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
783 return;
784
785 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000786 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
787 // For an unscoped enum include the enumerators in the hash since they
788 // enter the top-level namespace.
789 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000790 for (const auto *EI : EnumD->enumerators()) {
791 if (EI->getIdentifier())
792 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000793 }
794 }
795 }
796
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000797 if (ND->getIdentifier())
798 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
799 else if (DeclarationName Name = ND->getDeclName()) {
800 std::string NameStr = Name.getAsString();
801 Hash = llvm::HashString(NameStr, Hash);
802 }
803 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000804 }
805
806 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
807 if (Module *Mod = ImportD->getImportedModule()) {
808 std::string ModName = Mod->getFullModuleName();
809 Hash = llvm::HashString(ModName, Hash);
810 }
811 return;
812 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000813}
814
Daniel Dunbar644dca02009-12-04 08:17:33 +0000815class TopLevelDeclTrackerConsumer : public ASTConsumer {
816 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000817 unsigned &Hash;
818
Daniel Dunbar644dca02009-12-04 08:17:33 +0000819public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000820 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
821 : Unit(_Unit), Hash(Hash) {
822 Hash = 0;
823 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000824
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000825 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000826 if (!D)
827 return;
828
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000829 // FIXME: Currently ObjC method declarations are incorrectly being
830 // reported as top-level declarations, even though their DeclContext
831 // is the containing ObjC @interface/@implementation. This is a
832 // fundamental problem in the parser right now.
833 if (isa<ObjCMethodDecl>(D))
834 return;
835
836 AddTopLevelDeclarationToHash(D, Hash);
837 Unit.addTopLevelDecl(D);
838
839 handleFileLevelDecl(D);
840 }
841
842 void handleFileLevelDecl(Decl *D) {
843 Unit.addFileLevelDecl(D);
844 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000845 for (auto *I : NSD->decls())
846 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000847 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000848 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000849
Craig Topperafa7cb32014-03-13 06:07:04 +0000850 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000851 for (Decl *TopLevelDecl : D)
852 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000853 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000854 }
855
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000856 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000857 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000858
Craig Topperafa7cb32014-03-13 06:07:04 +0000859 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000860 for (Decl *TopLevelDecl : D)
861 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000862 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000863
Craig Topperafa7cb32014-03-13 06:07:04 +0000864 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000865 return Unit.getASTMutationListener();
866 }
867
Craig Topperafa7cb32014-03-13 06:07:04 +0000868 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000869 return Unit.getDeserializationListener();
870 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000871};
872
873class TopLevelDeclTrackerAction : public ASTFrontendAction {
874public:
875 ASTUnit &Unit;
876
David Blaikie6beb6aa2014-08-10 19:56:51 +0000877 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
878 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000879 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000880 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
881 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000882 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
883 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000884 }
885
886public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000887 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
888
Craig Topperafa7cb32014-03-13 06:07:04 +0000889 bool hasCodeCompletionSupport() const override { return false; }
890 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000891 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000892 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000893};
894
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000895class PrecompilePreambleAction : public ASTFrontendAction {
896 ASTUnit &Unit;
897 bool HasEmittedPreamblePCH;
898
899public:
900 explicit PrecompilePreambleAction(ASTUnit &Unit)
901 : Unit(Unit), HasEmittedPreamblePCH(false) {}
902
David Blaikie6beb6aa2014-08-10 19:56:51 +0000903 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
904 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000905 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
906 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000907 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000908
Craig Topperafa7cb32014-03-13 06:07:04 +0000909 bool hasCodeCompletionSupport() const override { return false; }
910 bool hasASTFileSupport() const override { return false; }
911 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000912};
913
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000914class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000915 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000916 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000917 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000918 PrecompilePreambleAction *Action;
919
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000920public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000921 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
922 const Preprocessor &PP, StringRef isysroot,
923 raw_ostream *Out)
Adrian Prantlcbc368c2015-02-25 02:44:04 +0000924 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
925 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000926 Hash = 0;
927 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000928
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000929 bool HandleTopLevelDecl(DeclGroupRef DG) override {
930 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000931 // FIXME: Currently ObjC method declarations are incorrectly being
932 // reported as top-level declarations, even though their DeclContext
933 // is the containing ObjC @interface/@implementation. This is a
934 // fundamental problem in the parser right now.
935 if (isa<ObjCMethodDecl>(D))
936 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000937 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000938 TopLevelDecls.push_back(D);
939 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000940 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000941 }
942
Craig Topperafa7cb32014-03-13 06:07:04 +0000943 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000944 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000945 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000946 // Translate the top-level declarations we captured during
947 // parsing into declaration IDs in the precompiled
948 // preamble. This will allow us to deserialize those top-level
949 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000950 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000951 // Invalid top-level decls may not have been serialized.
952 if (D->isInvalidDecl())
953 continue;
954 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
955 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000956
957 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000958 }
959 }
960};
961
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000962}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000963
David Blaikie6beb6aa2014-08-10 19:56:51 +0000964std::unique_ptr<ASTConsumer>
965PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
966 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000967 std::string Sysroot;
968 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000969 raw_ostream *OS = nullptr;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000970 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
971 OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000972 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000973
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000974 if (!CI.getFrontendOpts().RelocatablePCH)
975 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000976
Craig Topperb8a70532014-09-10 04:53:53 +0000977 CI.getPreprocessor().addPPCallbacks(
978 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
979 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000980 return llvm::make_unique<PrecompilePreambleConsumer>(
981 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000982}
983
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000984static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
985 return StoredDiag.getLocation().isValid();
986}
987
988static void
989checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000990 // Get rid of stored diagnostics except the ones from the driver which do not
991 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000992 StoredDiags.erase(
993 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
994 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000995}
996
997static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
998 StoredDiagnostics,
999 SourceManager &SM) {
1000 // The stored diagnostic has the old source manager in it; update
1001 // the locations to refer into the new source manager. Since we've
1002 // been careful to make sure that the source manager's state
1003 // before and after are identical, so that we can reuse the source
1004 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001005 for (StoredDiagnostic &SD : StoredDiagnostics) {
1006 if (SD.getLocation().isValid()) {
1007 FullSourceLoc Loc(SD.getLocation(), SM);
1008 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001009 }
1010 }
1011}
1012
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001013/// Parse the source file into a translation unit using the given compiler
1014/// invocation, replacing the current translation unit.
1015///
1016/// \returns True if a failure occurred that causes the ASTUnit not to
1017/// contain any translation-unit information, false otherwise.
Rafael Espindola32482082014-08-18 16:23:45 +00001018bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
Rafael Espindola4674a872014-08-13 17:08:22 +00001019 SavedMainFileBuffer.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001020
Rafael Espindola32482082014-08-18 16:23:45 +00001021 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001022 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001023
Daniel Dunbar764c0822009-12-01 09:51:01 +00001024 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001025 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001026
1027 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001028 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1029 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001030
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001031 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001032 CCInvocation(new CompilerInvocation(*Invocation));
1033
Alp Tokerf994cef2014-07-05 03:08:06 +00001034 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001035 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001036
Douglas Gregor8e984da2010-08-04 16:47:14 +00001037 // Set up diagnostics, capturing any diagnostics that would
1038 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001039 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001040
Daniel Dunbar764c0822009-12-01 09:51:01 +00001041 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001042 Clang->setTarget(TargetInfo::CreateTargetInfo(
1043 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001044 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001045 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001046
Daniel Dunbar764c0822009-12-01 09:51:01 +00001047 // Inform the target of the language options.
1048 //
1049 // FIXME: We shouldn't need to do this, the target should be immutable once
1050 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001051 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001052
Ted Kremenek84de4a12011-03-21 18:40:07 +00001053 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001054 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001055 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001056 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001057 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001058 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001059
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001060 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001061 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001062 FileSystemOpts = Clang->getFileSystemOpts();
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001063 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1064 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
Rafael Espindola32482082014-08-18 16:23:45 +00001065 if (!VFS)
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001066 return true;
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001067 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001068 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1069 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001070 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001071 Ctx = nullptr;
1072 PP = nullptr;
1073 Reader = nullptr;
1074
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001075 // Clear out old caches and data.
1076 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001077 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001078 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001079
Douglas Gregor7b02b582010-08-20 00:02:33 +00001080 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001081 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001082 TopLevelDeclsInPreamble.clear();
1083 }
1084
Daniel Dunbar764c0822009-12-01 09:51:01 +00001085 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001086 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001087
Daniel Dunbar764c0822009-12-01 09:51:01 +00001088 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001089 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001090
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001091 // If the main file has been overridden due to the use of a preamble,
1092 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001093 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001094 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001095 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1096 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001097 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1098 PreprocessorOpts.PrecompiledPreambleBytes.second
1099 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001100 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001101 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001102
Douglas Gregord9a30af2010-08-02 20:51:39 +00001103 // The stored diagnostic has the old source manager in it; update
1104 // the locations to refer into the new source manager. Since we've
1105 // been careful to make sure that the source manager's state
1106 // before and after are identical, so that we can reuse the source
1107 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001108 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001109
1110 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001111 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001112 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001113
1114 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1115 new TopLevelDeclTrackerAction(*this));
1116
Ted Kremenek022a4902011-03-22 01:15:24 +00001117 // Recover resources if we crash before exiting this method.
1118 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1119 ActCleanup(Act.get());
1120
Douglas Gregor32fbe312012-01-20 16:28:04 +00001121 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001122 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001123
Rafael Espindola32482082014-08-18 16:23:45 +00001124 if (SavedMainFileBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001125 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001126 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1127 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001128 }
1129
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001130 if (!Act->Execute())
1131 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001132
1133 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001134
Daniel Dunbar644dca02009-12-04 08:17:33 +00001135 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001136
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001137 FailedParseDiagnostics.clear();
1138
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001139 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001140
Daniel Dunbar764c0822009-12-01 09:51:01 +00001141error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001142 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001143 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001144
1145 // Keep the ownership of the data in the ASTUnit because the client may
1146 // want to see the diagnostics.
1147 transferASTDataFromCompilerInstance(*Clang);
1148 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001149 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001150 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001151 return true;
1152}
1153
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001154/// \brief Simple function to retrieve a path for a preamble precompiled header.
1155static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001156 // FIXME: This is a hack so that we can override the preamble file during
1157 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001158 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001159 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1160 if (TmpFile)
1161 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001162
1163 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001164 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001165
1166 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001167}
1168
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001169/// \brief Compute the preamble for the main file, providing the source buffer
1170/// that corresponds to the main file along with a pair (bytes, start-of-line)
1171/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001172ASTUnit::ComputedPreamble
1173ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001174 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001175 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001176
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001177 // Try to determine if the main file has been remapped, either from the
1178 // command line (to another file) or directly through the compiler invocation
1179 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001180 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001181 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001182 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001183 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001184 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001185 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001186 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1187 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001188 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001189 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001190 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191 // We found a remapping. Try to load the resulting, remapped source.
David Blaikied6902a12014-08-29 06:34:53 +00001192 BufferOwner = getBufferForFile(RF.second);
1193 if (!BufferOwner)
1194 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001195 }
1196 }
1197 }
1198
1199 // Check whether there is a file-buffer remapping. It supercedes the
1200 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001201 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1202 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001203 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001204 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001205 if (MainFileID == MID) {
1206 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001207 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001208 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001209 }
1210 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 }
1213
1214 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001215 if (!Buffer && !BufferOwner) {
1216 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1217 if (!BufferOwner)
1218 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219 }
David Blaikie3d95d852014-08-11 22:08:06 +00001220
David Blaikied6902a12014-08-29 06:34:53 +00001221 if (!Buffer)
1222 Buffer = BufferOwner.get();
1223 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1224 *Invocation.getLangOpts(), MaxLines);
1225 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1226 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001227}
1228
Dmitri Gribenko47652522013-12-20 00:16:25 +00001229ASTUnit::PreambleFileHash
1230ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1231 PreambleFileHash Result;
1232 Result.Size = Size;
1233 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001234 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001235 return Result;
1236}
1237
1238ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1239 const llvm::MemoryBuffer *Buffer) {
1240 PreambleFileHash Result;
1241 Result.Size = Buffer->getBufferSize();
1242 Result.ModTime = 0;
1243
1244 llvm::MD5 MD5Ctx;
1245 MD5Ctx.update(Buffer->getBuffer().data());
1246 MD5Ctx.final(Result.MD5);
1247
1248 return Result;
1249}
1250
1251namespace clang {
1252bool operator==(const ASTUnit::PreambleFileHash &LHS,
1253 const ASTUnit::PreambleFileHash &RHS) {
1254 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001255 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001256}
1257} // namespace clang
1258
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001259static std::pair<unsigned, unsigned>
1260makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1261 const LangOptions &LangOpts) {
1262 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1263 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1264 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1265 return std::make_pair(Offset, EndOffset);
1266}
1267
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001268static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1269 const LangOptions &LangOpts,
1270 const FixItHint &InFix) {
1271 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001272 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1273 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1274 LangOpts);
1275 OutFix.CodeToInsert = InFix.CodeToInsert;
1276 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001277 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001278}
1279
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001280static ASTUnit::StandaloneDiagnostic
1281makeStandaloneDiagnostic(const LangOptions &LangOpts,
1282 const StoredDiagnostic &InDiag) {
1283 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001284 OutDiag.ID = InDiag.getID();
1285 OutDiag.Level = InDiag.getLevel();
1286 OutDiag.Message = InDiag.getMessage();
1287 OutDiag.LocOffset = 0;
1288 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001289 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001290 const SourceManager &SM = InDiag.getLocation().getManager();
1291 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1292 OutDiag.Filename = SM.getFilename(FileLoc);
1293 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001294 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001295 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001296 for (const CharSourceRange &Range : InDiag.getRanges())
1297 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1298 for (const FixItHint &FixIt : InDiag.getFixIts())
1299 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001300
1301 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001302}
1303
Douglas Gregor4dde7492010-07-23 23:58:40 +00001304/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1305/// the source file.
1306///
1307/// This routine will compute the preamble of the main source file. If a
1308/// non-trivial preamble is found, it will precompile that preamble into a
1309/// precompiled header so that the precompiled preamble can be used to reduce
1310/// reparsing time. If a precompiled preamble has already been constructed,
1311/// this routine will determine if it is still valid and, if so, avoid
1312/// rebuilding the precompiled preamble.
1313///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001314/// \param AllowRebuild When true (the default), this routine is
1315/// allowed to rebuild the precompiled preamble if it is found to be
1316/// out-of-date.
1317///
1318/// \param MaxLines When non-zero, the maximum number of lines that
1319/// can occur within the preamble.
1320///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001321/// \returns If the precompiled preamble can be used, returns a newly-allocated
1322/// buffer that should be used in place of the main file when doing so.
1323/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001324std::unique_ptr<llvm::MemoryBuffer>
1325ASTUnit::getMainBufferWithPrecompiledPreamble(
1326 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1327 unsigned MaxLines) {
1328
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001329 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001330 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1331 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001332 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001333 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001334
David Blaikied6902a12014-08-29 06:34:53 +00001335 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001336
David Blaikied6902a12014-08-29 06:34:53 +00001337 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001338 // We couldn't find a preamble in the main source. Clear out the current
1339 // preamble, if we have one. It's obviously no good any more.
1340 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001341 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001342
1343 // The next time we actually see a preamble, precompile it.
1344 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001345 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001346 }
1347
1348 if (!Preamble.empty()) {
1349 // We've previously computed a preamble. Check whether we have the same
1350 // preamble now that we did before, and that there's enough space in
1351 // the main-file buffer within the precompiled preamble to fit the
1352 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001353 if (Preamble.size() == NewPreamble.Size &&
1354 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1355 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1356 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001357 // The preamble has not changed. We may be able to re-use the precompiled
1358 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001359
Douglas Gregor0e119552010-07-31 00:40:00 +00001360 // Check that none of the files used by the preamble have changed.
1361 bool AnyFileChanged = false;
1362
1363 // First, make a record of those files that have been overridden via
1364 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001365 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001366 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1367 if (AnyFileChanged)
1368 break;
1369
Ben Langmuirc8130a72014-02-20 21:59:23 +00001370 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001371 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001372 // If we can't stat the file we're remapping to, assume that something
1373 // horrible happened.
1374 AnyFileChanged = true;
1375 break;
1376 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001377
Alp Toker1b070d22014-07-07 07:47:20 +00001378 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001379 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001380 }
Alp Toker1b070d22014-07-07 07:47:20 +00001381
1382 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1383 if (AnyFileChanged)
1384 break;
1385 OverriddenFiles[RB.first] =
1386 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001387 }
1388
1389 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001390 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001391 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1392 !AnyFileChanged && F != FEnd;
1393 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001394 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001395 = OverriddenFiles.find(F->first());
1396 if (Overridden != OverriddenFiles.end()) {
1397 // This file was remapped; check whether the newly-mapped file
1398 // matches up with the previous mapping.
1399 if (Overridden->second != F->second)
1400 AnyFileChanged = true;
1401 continue;
1402 }
1403
1404 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001405 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001406 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001407 // If we can't stat the file, assume that something horrible happened.
1408 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001409 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001410 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001411 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001412 AnyFileChanged = true;
1413 }
1414
1415 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001416 // Okay! We can re-use the precompiled preamble.
1417
1418 // Set the state of the diagnostic object to mimic its state
1419 // after parsing the preamble.
1420 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001421 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001422 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001423 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001424
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001425 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001426 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001427 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001428 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001429
1430 // If we aren't allowed to rebuild the precompiled preamble, just
1431 // return now.
1432 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001433 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001434
Douglas Gregor4dde7492010-07-23 23:58:40 +00001435 // We can't reuse the previously-computed preamble. Build a new one.
1436 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001437 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001438 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001439 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001440 } else if (!AllowRebuild) {
1441 // We aren't allowed to rebuild the precompiled preamble; just
1442 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001443 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001444 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001445
1446 // If the preamble rebuild counter > 1, it's because we previously
1447 // failed to build a preamble and we're not yet ready to try
1448 // again. Decrement the counter and return a failure.
1449 if (PreambleRebuildCounter > 1) {
1450 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001451 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001452 }
1453
Douglas Gregore10f0e52010-09-11 17:56:52 +00001454 // Create a temporary file for the precompiled preamble. In rare
1455 // circumstances, this can fail.
1456 std::string PreamblePCHPath = GetPreamblePCHPath();
1457 if (PreamblePCHPath.empty()) {
1458 // Try again next time.
1459 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001460 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001461 }
1462
Douglas Gregor4dde7492010-07-23 23:58:40 +00001463 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001464 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001465 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001466
Douglas Gregord9a30af2010-08-02 20:51:39 +00001467 // Save the preamble text for later; we'll need to compare against it for
1468 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001469 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001470 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001471 NewPreamble.Buffer->getBufferStart(),
1472 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1473 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001474
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001475 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001476 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001477
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001478 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001479 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001480 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001481
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001482 // Tell the compiler invocation to generate a temporary precompiled header.
1483 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001484 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001485 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001486 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1487 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001488
1489 // Create the compiler instance to use for building the precompiled preamble.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001490 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001491
1492 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001493 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1494 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001495
Douglas Gregor3cc15812011-07-01 18:22:13 +00001496 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001497 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001498
Douglas Gregor8e984da2010-08-04 16:47:14 +00001499 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001500 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001501
1502 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001503 Clang->setTarget(TargetInfo::CreateTargetInfo(
1504 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001505 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001506 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001507 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001508 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001509 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001510 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001511 }
1512
1513 // Inform the target of the language options.
1514 //
1515 // FIXME: We shouldn't need to do this, the target should be immutable once
1516 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001517 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001518
Ted Kremenek84de4a12011-03-21 18:40:07 +00001519 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001520 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001521 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001522 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001523 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001524 "IR inputs not support here!");
1525
1526 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001527 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001528 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001529 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001530 TopLevelDecls.clear();
1531 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001532 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001533
1534 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1535 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1536 if (!VFS)
1537 return nullptr;
1538
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001539 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001540 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001541
1542 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001543 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001544 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001545
Ben Langmuir33c80902014-06-30 20:04:14 +00001546 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1547 Clang->addDependencyCollector(PreambleDepCollector);
1548
Ahmed Charlesb8984322014-03-07 20:03:18 +00001549 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001550 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001551 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001552 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001553 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001554 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001555 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001556 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001557 }
1558
1559 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001560
1561 // Transfer any diagnostics generated when parsing the preamble into the set
1562 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001563 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1564 E = stored_diag_end();
1565 I != E; ++I)
1566 PreambleDiagnostics.push_back(
1567 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001568
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001569 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001570
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001571 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1572
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001573 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001574 // The preamble PCH failed (e.g. there was a module loading fatal error),
1575 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001576 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001577 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001578 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001579 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001580 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001581 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001582 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001583 }
1584
1585 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001586 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001587 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001588
1589 // Keep track of all of the files that the source manager knows about,
1590 // so we can verify whether they have changed or not.
1591 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001592 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001593 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1594 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1595 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001596 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001597 if (time_t ModTime = File->getModificationTime()) {
1598 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001599 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001600 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001601 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001602 FilesInPreamble[File->getName()] =
1603 PreambleFileHash::createForMemoryBuffer(Buffer);
1604 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001605 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001606
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001607 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001608 PreprocessorOpts.RemappedFileBuffers.pop_back();
1609
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001610 // If the hash of top-level entities differs from the hash of the top-level
1611 // entities the last time we rebuilt the preamble, clear out the completion
1612 // cache.
1613 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1614 CompletionCacheTopLevelHashValue = 0;
1615 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1616 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001617
David Blaikied6902a12014-08-29 06:34:53 +00001618 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001619 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001620}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001621
Douglas Gregore9db88f2010-08-03 19:06:41 +00001622void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1623 std::vector<Decl *> Resolved;
1624 Resolved.reserve(TopLevelDeclsInPreamble.size());
1625 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001626 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001627 // Resolve the declaration ID to an actual declaration, possibly
1628 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001629 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001630 Resolved.push_back(D);
1631 }
1632 TopLevelDeclsInPreamble.clear();
1633 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1634}
1635
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001636void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001637 // Steal the created target, context, and preprocessor if they have been
1638 // created.
1639 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001640 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001641 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001642 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001643 if (CI.hasASTContext())
1644 Ctx = &CI.getASTContext();
1645 if (CI.hasPreprocessor())
1646 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001647 CI.setSourceManager(nullptr);
1648 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001649 if (CI.hasTarget())
1650 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001651 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001652 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001653}
1654
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001655StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001656 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1657 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1658 if (Input.isFile())
1659 return Input.getFile();
1660 else
1661 return Input.getBuffer()->getBufferIdentifier();
1662 }
1663
1664 if (SourceMgr) {
1665 if (const FileEntry *
1666 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1667 return FE->getName();
1668 }
1669
1670 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001671}
1672
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001673StringRef ASTUnit::getASTFileName() const {
1674 if (!isMainFileAST())
1675 return StringRef();
1676
1677 serialization::ModuleFile &
1678 Mod = Reader->getModuleManager().getPrimaryModule();
1679 return Mod.FileName;
1680}
1681
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001682ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001683 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001684 bool CaptureDiagnostics,
1685 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001686 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001687 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001688 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001689 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001690 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001691 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001692 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1693 createVFSFromCompilerInvocation(*CI, *Diags);
1694 if (!VFS)
1695 return nullptr;
1696 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001697 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1698 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1699 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001700
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001701 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001702}
1703
Ahmed Charlesb8984322014-03-07 20:03:18 +00001704ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1705 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1706 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1707 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1708 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1709 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1710 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001711 assert(CI && "A CompilerInvocation is required");
1712
Ahmed Charlesb8984322014-03-07 20:03:18 +00001713 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001714 ASTUnit *AST = Unit;
1715 if (!AST) {
1716 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001717 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001718 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001719 if (!AST)
1720 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001721 }
1722
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001723 if (!ResourceFilesPath.empty()) {
1724 // Override the resources path.
1725 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1726 }
1727 AST->OnlyLocalDecls = OnlyLocalDecls;
1728 AST->CaptureDiagnostics = CaptureDiagnostics;
1729 if (PrecompilePreamble)
1730 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001731 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001732 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001733 AST->IncludeBriefCommentsInCodeCompletion
1734 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001735
1736 // Recover resources if we crash before exiting this method.
1737 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001738 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001739 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1740 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001741 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001742
1743 // We'll manage file buffers ourselves.
1744 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1745 CI->getFrontendOpts().DisableFree = false;
1746 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1747
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001748 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001749 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001750
1751 // Recover resources if we crash before exiting this method.
1752 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1753 CICleanup(Clang.get());
1754
1755 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001756 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001757
1758 // Set up diagnostics, capturing any diagnostics that would
1759 // otherwise be dropped.
1760 Clang->setDiagnostics(&AST->getDiagnostics());
1761
1762 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001763 Clang->setTarget(TargetInfo::CreateTargetInfo(
1764 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001765 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001766 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001767
1768 // Inform the target of the language options.
1769 //
1770 // FIXME: We shouldn't need to do this, the target should be immutable once
1771 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001772 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001773
1774 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1775 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001776 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001777 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001778 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001779 "IR inputs not supported here!");
1780
1781 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001782 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001783 AST->Ctx = nullptr;
1784 AST->PP = nullptr;
1785 AST->Reader = nullptr;
1786
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001787 // Create a file manager object to provide access to and cache the filesystem.
1788 Clang->setFileManager(&AST->getFileManager());
1789
1790 // Create the source manager.
1791 Clang->setSourceManager(&AST->getSourceManager());
1792
1793 ASTFrontendAction *Act = Action;
1794
Ahmed Charlesb8984322014-03-07 20:03:18 +00001795 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001796 if (!Act) {
1797 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1798 Act = TrackerAct.get();
1799 }
1800
1801 // Recover resources if we crash before exiting this method.
1802 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1803 ActCleanup(TrackerAct.get());
1804
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001805 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1806 AST->transferASTDataFromCompilerInstance(*Clang);
1807 if (OwnAST && ErrAST)
1808 ErrAST->swap(OwnAST);
1809
Craig Topper49a27902014-05-22 04:46:25 +00001810 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001811 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001812
1813 if (Persistent && !TrackerAct) {
1814 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001815 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1816 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001817 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001818 if (Clang->hasASTConsumer())
1819 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001820 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1821 *AST, AST->getCurrentTopLevelHashValue()));
1822 Clang->setASTConsumer(
1823 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001824 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001825 if (!Act->Execute()) {
1826 AST->transferASTDataFromCompilerInstance(*Clang);
1827 if (OwnAST && ErrAST)
1828 ErrAST->swap(OwnAST);
1829
Craig Topper49a27902014-05-22 04:46:25 +00001830 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001831 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001832
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001833 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001834 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001835
1836 Act->EndSourceFile();
1837
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001838 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001839 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001840 else
1841 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001842}
1843
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001844bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1845 if (!Invocation)
1846 return true;
1847
1848 // We'll manage file buffers ourselves.
1849 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1850 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001851 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001852
Rafael Espindola32482082014-08-18 16:23:45 +00001853 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001854 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001855 PreambleRebuildCounter = 2;
Rafael Espindola2346a372014-08-18 18:47:08 +00001856 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001857 }
1858
Douglas Gregor16896c42010-10-28 15:44:59 +00001859 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001860 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001861
Ted Kremenek022a4902011-03-22 01:15:24 +00001862 // Recover resources if we crash before exiting this method.
1863 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001864 MemBufferCleanup(OverrideMainBuffer.get());
1865
1866 return Parse(std::move(OverrideMainBuffer));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001867}
1868
David Blaikie103a2de2014-04-25 17:01:33 +00001869std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1870 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1871 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1872 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1873 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001874 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001875 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001876 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001877 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001878 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001879 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001880 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001881 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001882 AST->IncludeBriefCommentsInCodeCompletion
1883 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001884 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001885 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001886 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1887 createVFSFromCompilerInvocation(*CI, *Diags);
1888 if (!VFS)
1889 return nullptr;
1890 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001891 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001892
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001893 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001894 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1895 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001896 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1897 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001898 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001899
David Blaikie103a2de2014-04-25 17:01:33 +00001900 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1901 return nullptr;
1902 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001903}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001904
Ahmed Charlesb8984322014-03-07 20:03:18 +00001905ASTUnit *ASTUnit::LoadFromCommandLine(
1906 const char **ArgBegin, const char **ArgEnd,
1907 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1908 bool OnlyLocalDecls, bool CaptureDiagnostics,
1909 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1910 bool PrecompilePreamble, TranslationUnitKind TUKind,
1911 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1912 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1913 bool UserFilesAreVolatile, bool ForSerialization,
1914 std::unique_ptr<ASTUnit> *ErrAST) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001915 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001916
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001917 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001918
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001919 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001920
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001921 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001922
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001923 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001924 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001925
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001926 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001927 llvm::makeArrayRef(ArgBegin, ArgEnd),
1928 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001929 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001930 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001931 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001932
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001933 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001934 for (const auto &RemappedFile : RemappedFiles) {
1935 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1936 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001937 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001938 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1939 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1940 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001941
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001942 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001943 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001944
Erik Verbruggen6e922512012-04-12 10:11:59 +00001945 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1946
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001947 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001948 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001949 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001950 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001951 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001952 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001953 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1954 createVFSFromCompilerInvocation(*CI, *Diags);
1955 if (!VFS)
1956 return nullptr;
1957 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001958 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001959 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001960 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001961 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001962 AST->IncludeBriefCommentsInCodeCompletion
1963 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001964 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001965 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001966 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001967 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001968 if (ForSerialization)
1969 AST->WriterData.reset(new ASTWriterData());
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001970 // Zero out now to ease cleanup during crash recovery.
1971 CI = nullptr;
1972 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001973
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001974 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001975 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1976 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001977
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001978 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1979 // Some error occurred, if caller wants to examine diagnostics, pass it the
1980 // ASTUnit.
1981 if (ErrAST) {
1982 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1983 ErrAST->swap(AST);
1984 }
Craig Topper49a27902014-05-22 04:46:25 +00001985 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001986 }
1987
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001988 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001989}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001990
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001991bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001992 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001993 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001994
1995 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001996
Douglas Gregor16896c42010-10-28 15:44:59 +00001997 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001998 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001999
Douglas Gregor0e119552010-07-31 00:40:00 +00002000 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002001 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002002 for (const auto &RB : PPOpts.RemappedFileBuffers)
2003 delete RB.second;
2004
Douglas Gregor0e119552010-07-31 00:40:00 +00002005 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002006 for (const auto &RemappedFile : RemappedFiles) {
2007 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2008 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002009 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002010
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002011 // If we have a preamble file lying around, or if we might try to
2012 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002013 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002014 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Rafael Espindola2346a372014-08-18 18:47:08 +00002015 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002016
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002017 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002018 getDiagnostics().Reset();
2019 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002020 if (OverrideMainBuffer)
2021 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002022
Douglas Gregor4dde7492010-07-23 23:58:40 +00002023 // Parse the sources
Rafael Espindola32482082014-08-18 16:23:45 +00002024 bool Result = Parse(std::move(OverrideMainBuffer));
2025
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002026 // If we're caching global code-completion results, and the top-level
2027 // declarations have changed, clear out the code-completion cache.
2028 if (!Result && ShouldCacheCodeCompletionResults &&
2029 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2030 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002031
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002032 // We now need to clear out the completion info related to this translation
2033 // unit; it'll be recreated if necessary.
2034 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002035
Douglas Gregor4dde7492010-07-23 23:58:40 +00002036 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002037}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002038
Douglas Gregorb14904c2010-08-13 22:48:40 +00002039//----------------------------------------------------------------------------//
2040// Code completion
2041//----------------------------------------------------------------------------//
2042
2043namespace {
2044 /// \brief Code completion consumer that combines the cached code-completion
2045 /// results from an ASTUnit with the code-completion results provided to it,
2046 /// then passes the result on to
2047 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002048 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002049 ASTUnit &AST;
2050 CodeCompleteConsumer &Next;
2051
2052 public:
2053 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002054 const CodeCompleteOptions &CodeCompleteOpts)
2055 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2056 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002057 {
2058 // Compute the set of contexts in which we will look when we don't have
2059 // any information about the specific context.
2060 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002061 = (1LL << CodeCompletionContext::CCC_TopLevel)
2062 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2063 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2064 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2065 | (1LL << CodeCompletionContext::CCC_Statement)
2066 | (1LL << CodeCompletionContext::CCC_Expression)
2067 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2068 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2069 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2070 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2071 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2072 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2073 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002074
David Blaikiebbafb8a2012-03-11 07:00:24 +00002075 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002076 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2077 | (1LL << CodeCompletionContext::CCC_UnionTag)
2078 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002079 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002080
2081 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2082 CodeCompletionResult *Results,
2083 unsigned NumResults) override;
2084
2085 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2086 OverloadCandidate *Candidates,
2087 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002088 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2089 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002090
2091 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002092 return Next.getAllocator();
2093 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002094
Craig Topperafa7cb32014-03-13 06:07:04 +00002095 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002096 return Next.getCodeCompletionTUInfo();
2097 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002098 };
2099}
Douglas Gregord46cf182010-08-16 20:01:48 +00002100
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002101/// \brief Helper function that computes which global names are hidden by the
2102/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002103static void CalculateHiddenNames(const CodeCompletionContext &Context,
2104 CodeCompletionResult *Results,
2105 unsigned NumResults,
2106 ASTContext &Ctx,
2107 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002108 bool OnlyTagNames = false;
2109 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002110 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002111 case CodeCompletionContext::CCC_TopLevel:
2112 case CodeCompletionContext::CCC_ObjCInterface:
2113 case CodeCompletionContext::CCC_ObjCImplementation:
2114 case CodeCompletionContext::CCC_ObjCIvarList:
2115 case CodeCompletionContext::CCC_ClassStructUnion:
2116 case CodeCompletionContext::CCC_Statement:
2117 case CodeCompletionContext::CCC_Expression:
2118 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002119 case CodeCompletionContext::CCC_DotMemberAccess:
2120 case CodeCompletionContext::CCC_ArrowMemberAccess:
2121 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002122 case CodeCompletionContext::CCC_Namespace:
2123 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002124 case CodeCompletionContext::CCC_Name:
2125 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002126 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002127 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002128 break;
2129
2130 case CodeCompletionContext::CCC_EnumTag:
2131 case CodeCompletionContext::CCC_UnionTag:
2132 case CodeCompletionContext::CCC_ClassOrStructTag:
2133 OnlyTagNames = true;
2134 break;
2135
2136 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002137 case CodeCompletionContext::CCC_MacroName:
2138 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002139 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002140 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002141 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002142 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002143 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002144 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002145 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002146 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2147 case CodeCompletionContext::CCC_ObjCClassMessage:
2148 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002149 // We're looking for nothing, or we're looking for names that cannot
2150 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002151 return;
2152 }
2153
John McCall276321a2010-08-25 06:19:51 +00002154 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002155 for (unsigned I = 0; I != NumResults; ++I) {
2156 if (Results[I].Kind != Result::RK_Declaration)
2157 continue;
2158
2159 unsigned IDNS
2160 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2161
2162 bool Hiding = false;
2163 if (OnlyTagNames)
2164 Hiding = (IDNS & Decl::IDNS_Tag);
2165 else {
2166 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002167 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2168 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002169 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002170 HiddenIDNS |= Decl::IDNS_Tag;
2171 Hiding = (IDNS & HiddenIDNS);
2172 }
2173
2174 if (!Hiding)
2175 continue;
2176
2177 DeclarationName Name = Results[I].Declaration->getDeclName();
2178 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2179 HiddenNames.insert(Identifier->getName());
2180 else
2181 HiddenNames.insert(Name.getAsString());
2182 }
2183}
2184
2185
Douglas Gregord46cf182010-08-16 20:01:48 +00002186void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2187 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002188 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002189 unsigned NumResults) {
2190 // Merge the results we were given with the results we cached.
2191 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002192 uint64_t InContexts =
2193 Context.getKind() == CodeCompletionContext::CCC_Recovery
2194 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002195 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002196 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002197 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002198 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002199 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002200 C = AST.cached_completion_begin(),
2201 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002202 C != CEnd; ++C) {
2203 // If the context we are in matches any of the contexts we are
2204 // interested in, we'll add this result.
2205 if ((C->ShowInContexts & InContexts) == 0)
2206 continue;
2207
2208 // If we haven't added any results previously, do so now.
2209 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002210 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2211 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002212 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2213 AddedResult = true;
2214 }
2215
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002216 // Determine whether this global completion result is hidden by a local
2217 // completion result. If so, skip it.
2218 if (C->Kind != CXCursor_MacroDefinition &&
2219 HiddenNames.count(C->Completion->getTypedText()))
2220 continue;
2221
Douglas Gregord46cf182010-08-16 20:01:48 +00002222 // Adjust priority based on similar type classes.
2223 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002224 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002225 if (!Context.getPreferredType().isNull()) {
2226 if (C->Kind == CXCursor_MacroDefinition) {
2227 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002228 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002229 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002230 } else if (C->Type) {
2231 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002232 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002233 Context.getPreferredType().getUnqualifiedType());
2234 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2235 if (ExpectedSTC == C->TypeClass) {
2236 // We know this type is similar; check for an exact match.
2237 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002238 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002239 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002240 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002241 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2242 Priority /= CCF_ExactTypeMatch;
2243 else
2244 Priority /= CCF_SimilarTypeMatch;
2245 }
2246 }
2247 }
2248
Douglas Gregor12785102010-08-24 20:21:13 +00002249 // Adjust the completion string, if required.
2250 if (C->Kind == CXCursor_MacroDefinition &&
2251 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2252 // Create a new code-completion string that just contains the
2253 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002254 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2255 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002256 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002257 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002258 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002259 }
2260
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002261 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002262 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002263 }
2264
2265 // If we did not add any cached completion results, just forward the
2266 // results we were given to the next consumer.
2267 if (!AddedResult) {
2268 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2269 return;
2270 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002271
Douglas Gregord46cf182010-08-16 20:01:48 +00002272 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2273 AllResults.size());
2274}
2275
2276
2277
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002278void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002279 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002280 bool IncludeMacros,
2281 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002282 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002283 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002284 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002285 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002286 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2287 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002288 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002289 return;
2290
Douglas Gregor16896c42010-10-28 15:44:59 +00002291 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002292 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002293 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002294
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002295 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002296 CCInvocation(new CompilerInvocation(*Invocation));
2297
2298 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002299 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002300 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002301
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002302 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2303 CachedCompletionResults.empty();
2304 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2305 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2306 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2307
2308 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2309
Douglas Gregor8e984da2010-08-04 16:47:14 +00002310 FrontendOpts.CodeCompletionAt.FileName = File;
2311 FrontendOpts.CodeCompletionAt.Line = Line;
2312 FrontendOpts.CodeCompletionAt.Column = Column;
2313
2314 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002315 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002316
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002317 // Spell-checking and warnings are wasteful during code-completion.
2318 LangOpts.SpellChecking = false;
2319 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2320
Ahmed Charlesb8984322014-03-07 20:03:18 +00002321 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002322
2323 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002324 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2325 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002326
Ted Kremenek5e14d392011-03-21 18:40:17 +00002327 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002328 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002329
2330 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002331 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002332 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002333 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002334 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002335 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002336
2337 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002338 Clang->setTarget(TargetInfo::CreateTargetInfo(
2339 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002340 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002341 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002342 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002343 }
2344
2345 // Inform the target of the language options.
2346 //
2347 // FIXME: We shouldn't need to do this, the target should be immutable once
2348 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002349 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002350
Ted Kremenek84de4a12011-03-21 18:40:07 +00002351 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002352 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002353 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002354 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002355 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002356 "IR inputs not support here!");
2357
2358
2359 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002360 Clang->setFileManager(&FileMgr);
2361 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002362
2363 // Remap files.
2364 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002365 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002366 for (const auto &RemappedFile : RemappedFiles) {
2367 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2368 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002369 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002370
Douglas Gregorb14904c2010-08-13 22:48:40 +00002371 // Use the code completion consumer we were given, but adding any cached
2372 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002373 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002374 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002375 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002376
Douglas Gregor028d3e42010-08-09 20:45:32 +00002377 // If we have a precompiled preamble, try to use it. We only allow
2378 // the use of the precompiled preamble if we're if the completion
2379 // point is within the main file, after the end of the precompiled
2380 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002381 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002382 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002383 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002384 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002385
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002386 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002387 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002388 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002389 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002390 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002391 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2392 *CCInvocation, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002393 }
2394 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002395 }
2396
2397 // If the main file has been overridden due to the use of a preamble,
2398 // make that override happen and introduce the preamble.
2399 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002400 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2401 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002402 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2403 PreprocessorOpts.PrecompiledPreambleBytes.second
2404 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002405 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002406 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002407
2408 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002409 } else {
2410 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2411 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002412 }
2413
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002414 // Disable the preprocessing record if modules are not enabled.
2415 if (!Clang->getLangOpts().Modules)
2416 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002417
2418 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002419 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002420 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002421 Act->Execute();
2422 Act->EndSourceFile();
2423 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002424}
Douglas Gregore9386682010-08-13 05:36:37 +00002425
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002426bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002427 if (HadModuleLoaderFatalFailure)
2428 return true;
2429
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002430 // Write to a temporary file and later rename it to the actual file, to avoid
2431 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002432 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002433 TempPath = File;
2434 TempPath += "-%%%%%%%%";
2435 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002436 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002437 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002438
Douglas Gregore9386682010-08-13 05:36:37 +00002439 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2440 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002441 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002442
2443 serialize(Out);
2444 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002445 if (Out.has_error()) {
2446 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002447 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002448 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002449
Rafael Espindola65e025c2011-12-25 01:18:52 +00002450 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002451 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002452 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002453 }
2454
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002455 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002456}
2457
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002458static bool serializeUnit(ASTWriter &Writer,
2459 SmallVectorImpl<char> &Buffer,
2460 Sema &S,
2461 bool hasErrors,
2462 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002463 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002464
2465 // Write the generated bitstream to "Out".
2466 if (!Buffer.empty())
2467 OS.write(Buffer.data(), Buffer.size());
2468
2469 return false;
2470}
2471
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002472bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002473 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002474
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002475 if (WriterData)
2476 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2477 getSema(), hasErrors, OS);
2478
Daniel Dunbar9a963862012-02-29 20:31:23 +00002479 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002480 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002481 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002482 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002483}
Douglas Gregor925296b2011-07-19 16:10:42 +00002484
2485typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2486
Douglas Gregor925296b2011-07-19 16:10:42 +00002487void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002488 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002489 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002490 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002491 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002492 // Map the standalone diagnostic into the new source manager. We also need to
2493 // remap all the locations to the new view. This includes the diag location,
2494 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002495 // FIXME: There should be a cleaner way to do this.
2496
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002497 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002498 Result.reserve(Diags.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002499 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002500 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002501 if (SD.Filename.empty())
2502 continue;
2503 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2504 if (!FE)
2505 continue;
2506 FileID FID = SrcMgr.translateFile(FE);
2507 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2508 if (FileLoc.isInvalid())
2509 continue;
2510 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002511 FullSourceLoc Loc(L, SrcMgr);
2512
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002513 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002514 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002515 for (const auto &Range : SD.Ranges) {
2516 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2517 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002518 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002519 }
2520
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002521 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002522 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002523 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002524 FixIts.push_back(FixItHint());
2525 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002526 FH.CodeToInsert = FixIt.CodeToInsert;
2527 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2528 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002529 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002530 }
2531
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002532 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2533 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002534 }
2535 Result.swap(Out);
2536}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002537
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002538void ASTUnit::addFileLevelDecl(Decl *D) {
2539 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002540
2541 // We only care about local declarations.
2542 if (D->isFromASTFile())
2543 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002544
2545 SourceManager &SM = *SourceMgr;
2546 SourceLocation Loc = D->getLocation();
2547 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2548 return;
2549
2550 // We only keep track of the file-level declarations of each file.
2551 if (!D->getLexicalDeclContext()->isFileContext())
2552 return;
2553
2554 SourceLocation FileLoc = SM.getFileLoc(Loc);
2555 assert(SM.isLocalSourceLocation(FileLoc));
2556 FileID FID;
2557 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002558 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002559 if (FID.isInvalid())
2560 return;
2561
2562 LocDeclsTy *&Decls = FileDecls[FID];
2563 if (!Decls)
2564 Decls = new LocDeclsTy();
2565
2566 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2567
2568 if (Decls->empty() || Decls->back().first <= Offset) {
2569 Decls->push_back(LocDecl);
2570 return;
2571 }
2572
Benjamin Kramer45025c02013-08-24 13:22:59 +00002573 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2574 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002575
2576 Decls->insert(I, LocDecl);
2577}
2578
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002579void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2580 SmallVectorImpl<Decl *> &Decls) {
2581 if (File.isInvalid())
2582 return;
2583
2584 if (SourceMgr->isLoadedFileID(File)) {
2585 assert(Ctx->getExternalSource() && "No external source!");
2586 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2587 Decls);
2588 }
2589
2590 FileDeclsTy::iterator I = FileDecls.find(File);
2591 if (I == FileDecls.end())
2592 return;
2593
2594 LocDeclsTy &LocDecls = *I->second;
2595 if (LocDecls.empty())
2596 return;
2597
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002598 LocDeclsTy::iterator BeginIt =
2599 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002600 std::make_pair(Offset, (Decl *)nullptr),
2601 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002602 if (BeginIt != LocDecls.begin())
2603 --BeginIt;
2604
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002605 // If we are pointing at a top-level decl inside an objc container, we need
2606 // to backtrack until we find it otherwise we will fail to report that the
2607 // region overlaps with an objc container.
2608 while (BeginIt != LocDecls.begin() &&
2609 BeginIt->second->isTopLevelDeclInObjCContainer())
2610 --BeginIt;
2611
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002612 LocDeclsTy::iterator EndIt = std::upper_bound(
2613 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002614 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002615 if (EndIt != LocDecls.end())
2616 ++EndIt;
2617
2618 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2619 Decls.push_back(DIt->second);
2620}
2621
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002622SourceLocation ASTUnit::getLocation(const FileEntry *File,
2623 unsigned Line, unsigned Col) const {
2624 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002625 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002626 return SM.getMacroArgExpandedLocation(Loc);
2627}
2628
2629SourceLocation ASTUnit::getLocation(const FileEntry *File,
2630 unsigned Offset) const {
2631 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002632 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002633 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2634}
2635
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002636/// \brief If \arg Loc is a loaded location from the preamble, returns
2637/// the corresponding local location of the main file, otherwise it returns
2638/// \arg Loc.
2639SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2640 FileID PreambleID;
2641 if (SourceMgr)
2642 PreambleID = SourceMgr->getPreambleFileID();
2643
2644 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2645 return Loc;
2646
2647 unsigned Offs;
2648 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2649 SourceLocation FileLoc
2650 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2651 return FileLoc.getLocWithOffset(Offs);
2652 }
2653
2654 return Loc;
2655}
2656
2657/// \brief If \arg Loc is a local location of the main file but inside the
2658/// preamble chunk, returns the corresponding loaded location from the
2659/// preamble, otherwise it returns \arg Loc.
2660SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2661 FileID PreambleID;
2662 if (SourceMgr)
2663 PreambleID = SourceMgr->getPreambleFileID();
2664
2665 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2666 return Loc;
2667
2668 unsigned Offs;
2669 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2670 Offs < Preamble.size()) {
2671 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2672 return FileLoc.getLocWithOffset(Offs);
2673 }
2674
2675 return Loc;
2676}
2677
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002678bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2679 FileID FID;
2680 if (SourceMgr)
2681 FID = SourceMgr->getPreambleFileID();
2682
2683 if (Loc.isInvalid() || FID.isInvalid())
2684 return false;
2685
2686 return SourceMgr->isInFileID(Loc, FID);
2687}
2688
2689bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2690 FileID FID;
2691 if (SourceMgr)
2692 FID = SourceMgr->getMainFileID();
2693
2694 if (Loc.isInvalid() || FID.isInvalid())
2695 return false;
2696
2697 return SourceMgr->isInFileID(Loc, FID);
2698}
2699
2700SourceLocation ASTUnit::getEndOfPreambleFileID() {
2701 FileID FID;
2702 if (SourceMgr)
2703 FID = SourceMgr->getPreambleFileID();
2704
2705 if (FID.isInvalid())
2706 return SourceLocation();
2707
2708 return SourceMgr->getLocForEndOfFile(FID);
2709}
2710
2711SourceLocation ASTUnit::getStartOfMainFileID() {
2712 FileID FID;
2713 if (SourceMgr)
2714 FID = SourceMgr->getMainFileID();
2715
2716 if (FID.isInvalid())
2717 return SourceLocation();
2718
2719 return SourceMgr->getLocForStartOfFile(FID);
2720}
2721
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002722llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002723ASTUnit::getLocalPreprocessingEntities() const {
2724 if (isMainFileAST()) {
2725 serialization::ModuleFile &
2726 Mod = Reader->getModuleManager().getPrimaryModule();
2727 return Reader->getModulePreprocessedEntities(Mod);
2728 }
2729
2730 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002731 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002732
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002733 return llvm::make_range(PreprocessingRecord::iterator(),
2734 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002735}
2736
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002737bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002738 if (isMainFileAST()) {
2739 serialization::ModuleFile &
2740 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002741 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2742 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002743 return false;
2744 }
2745
2746 return true;
2747 }
2748
2749 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2750 TLEnd = top_level_end();
2751 TL != TLEnd; ++TL) {
2752 if (!Fn(context, *TL))
2753 return false;
2754 }
2755
2756 return true;
2757}
2758
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002759namespace {
2760struct PCHLocatorInfo {
2761 serialization::ModuleFile *Mod;
Craig Topper49a27902014-05-22 04:46:25 +00002762 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002763};
2764}
2765
2766static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2767 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2768 switch (M.Kind) {
Richard Smithe842a472014-10-22 02:05:46 +00002769 case serialization::MK_ImplicitModule:
2770 case serialization::MK_ExplicitModule:
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002771 return true; // skip dependencies.
2772 case serialization::MK_PCH:
2773 Info.Mod = &M;
2774 return true; // found it.
2775 case serialization::MK_Preamble:
2776 return false; // look in dependencies.
2777 case serialization::MK_MainFile:
2778 return false; // look in dependencies.
2779 }
2780
2781 return true;
2782}
2783
2784const FileEntry *ASTUnit::getPCHFile() {
2785 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002786 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002787
2788 PCHLocatorInfo Info;
2789 Reader->getModuleManager().visit(PCHLocator, &Info);
2790 if (Info.Mod)
2791 return Info.Mod->File;
2792
Craig Topper49a27902014-05-22 04:46:25 +00002793 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002794}
2795
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002796bool ASTUnit::isModuleFile() {
2797 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2798}
2799
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002800void ASTUnit::PreambleData::countLines() const {
2801 NumLines = 0;
2802 if (empty())
2803 return;
2804
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002805 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2806
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002807 if (Buffer.back() != '\n')
2808 ++NumLines;
2809}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002810
2811#ifndef NDEBUG
2812ASTUnit::ConcurrencyState::ConcurrencyState() {
2813 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2814}
2815
2816ASTUnit::ConcurrencyState::~ConcurrencyState() {
2817 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2818}
2819
2820void ASTUnit::ConcurrencyState::start() {
2821 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2822 assert(acquired && "Concurrent access to ASTUnit!");
2823}
2824
2825void ASTUnit::ConcurrencyState::finish() {
2826 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2827}
2828
2829#else // NDEBUG
2830
Alp Tokerb159c132013-11-22 07:49:39 +00002831ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002832ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2833void ASTUnit::ConcurrencyState::start() {}
2834void ASTUnit::ConcurrencyState::finish() {}
2835
2836#endif