blob: 952992a9e8b70384b8a08de261f977228f8fed31 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00002//
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"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000021#include "clang/Basic/MemoryBufferCache.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000024#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000029#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000033#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000034#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Serialization/ASTReader.h"
36#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000037#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000038#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000039#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#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>
Hans Wennborgdcfba332015-10-06 23:40:43 +000050
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000082
83 struct OnDiskData {
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
86
Rafael Espindolabc7d9492013-06-26 03:52:38 +000087 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000088 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000089 SmallVector<std::string, 4> TemporaryFiles;
90
Ted Kremenek06b4f912011-10-27 17:55:18 +000091 /// \brief Erase temporary files.
92 void CleanTemporaryFiles();
93
94 /// \brief Erase the preamble file.
95 void CleanPreambleFile();
96
97 /// \brief Erase temporary files and the preamble file.
98 void Cleanup();
99 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000100}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000101
Ted Kremenekbd307a52011-10-27 19:44:25 +0000102static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
103 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
104 return M;
105}
106
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000108
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000109typedef llvm::DenseMap<const ASTUnit *,
110 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000111static OnDiskDataMap &getOnDiskDataMap() {
112 static OnDiskDataMap M;
113 static bool hasRegisteredAtExit = false;
114 if (!hasRegisteredAtExit) {
115 hasRegisteredAtExit = true;
116 atexit(cleanupOnDiskMapAtExit);
117 }
118 return M;
119}
120
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000121static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000122 // Use the mutex because there can be an alive thread destroying an ASTUnit.
123 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000124 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000127 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000128 }
129}
130
131static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000132 // We require the mutex since we are modifying the structure of the
133 // DenseMap.
134 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000135 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000136 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000137 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000138 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000139 return *D;
140}
141
142static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
144}
145
146static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000147 // We require the mutex since we are modifying the structure of the
148 // DenseMap.
149 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
152 if (I != M.end()) {
153 I->second->Cleanup();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000154 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000155 }
156}
157
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000167 for (StringRef File : TemporaryFiles)
168 llvm::sys::fs::remove(File);
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000169 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000174 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000189 ASTWriterData(MemoryBufferCache &PCMCache)
190 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000191};
192
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000193void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000194 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000195}
196
Ted Kremenek06b4f912011-10-27 17:55:18 +0000197void ASTUnit::CleanTemporaryFiles() {
198 getOnDiskData(this).CleanTemporaryFiles();
199}
200
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000201void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000202 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000203}
204
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000205/// \brief After failing to build a precompiled preamble (due to
206/// errors in the source that occurs in the preamble), the number of
207/// reparses during which we'll skip even trying to precompile the
208/// preamble.
209const unsigned DefaultPreambleRebuildInterval = 5;
210
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000211/// \brief Tracks the number of ASTUnit objects that are currently active.
212///
213/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000214static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000215
Douglas Gregord03e8232010-04-05 21:10:19 +0000216ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000217 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000218 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000223 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000224 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING"))
232 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000233}
Douglas Gregord03e8232010-04-05 21:10:19 +0000234
Daniel Dunbar764c0822009-12-01 09:51:01 +0000235ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000236 // If we loaded from an AST file, balance out the BeginSourceFile call.
237 if (MainFileIsAST && getDiagnostics().getClient()) {
238 getDiagnostics().getClient()->EndSourceFile();
239 }
240
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000241 clearFileLevelDecls();
242
Ted Kremenek06b4f912011-10-27 17:55:18 +0000243 // Clean up the temporary files and the preamble file.
244 removeOnDiskEntry(this);
245
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000246 // Free the buffers associated with remapped files. We are required to
247 // perform this operation here because we explicitly request that the
248 // compiler instance *not* free these buffers for each invocation of the
249 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000250 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000251 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000252 for (const auto &RB : PPOpts.RemappedFileBuffers)
253 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000254 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000255
Douglas Gregor16896c42010-10-28 15:44:59 +0000256 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000257
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000258 if (getenv("LIBCLANG_OBJTRACKING"))
259 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000260}
261
David Blaikie41565462017-01-05 19:48:07 +0000262void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
263 this->PP = std::move(PP);
264}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000265
Douglas Gregor39982192010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000268static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor39982192010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
Richard Smith697cc9e2012-08-14 03:13:00 +0000278 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
284 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
285 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
286 | (1LL << CodeCompletionContext::CCC_Statement)
287 | (1LL << CodeCompletionContext::CCC_Type)
288 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000306
Douglas Gregor59cab552010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000308 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000310 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000311 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000312 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000313 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000315
Douglas Gregor39982192010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000322 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
323 | (1LL << CodeCompletionContext::CCC_Expression)
324 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
325 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000326 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000329 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor16896c42010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000353 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000354 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000355 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000356 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000357
358 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000359 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000360 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000361
362 for (Result &R : Results) {
363 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000364 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000365 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000366 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000367 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000368 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000369 IncludeBriefCommentsInCodeCompletion);
370 CachedResult.ShowInContexts = getDeclShowContexts(
371 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
372 CachedResult.Priority = R.Priority;
373 CachedResult.Kind = R.CursorKind;
374 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000375
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000376 // Keep track of the type of this completion in an ASTContext-agnostic
377 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000378 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000379 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000380 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000381 CachedResult.Type = 0;
382 } else {
383 CanQualType CanUsageType
384 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
385 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
386
387 // Determine whether we have already seen this type. If so, we save
388 // ourselves the work of formatting the type string by using the
389 // temporary, CanQualType-based hash table to find the associated value.
390 unsigned &TypeValue = CompletionTypes[CanUsageType];
391 if (TypeValue == 0) {
392 TypeValue = CompletionTypes.size();
393 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
394 = TypeValue;
395 }
396
397 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000398 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000399
Douglas Gregor39982192010-08-15 06:18:01 +0000400 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000401
402 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000403 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
404 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000405 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000406 uint64_t NNSContexts
407 = (1LL << CodeCompletionContext::CCC_TopLevel)
408 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
409 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
410 | (1LL << CodeCompletionContext::CCC_Statement)
411 | (1LL << CodeCompletionContext::CCC_Expression)
412 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
413 | (1LL << CodeCompletionContext::CCC_EnumTag)
414 | (1LL << CodeCompletionContext::CCC_UnionTag)
415 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
416 | (1LL << CodeCompletionContext::CCC_Type)
417 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
418 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000419
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000420 if (isa<NamespaceDecl>(R.Declaration) ||
421 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000422 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000423
424 if (unsigned RemainingContexts
425 = NNSContexts & ~CachedResult.ShowInContexts) {
426 // If there any contexts where this completion can be a
427 // nested-name-specifier but isn't already an option, create a
428 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000429 R.StartsNestedNameSpecifier = true;
430 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000431 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000432 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000433 CachedResult.ShowInContexts = RemainingContexts;
434 CachedResult.Priority = CCP_NestedNameSpecifier;
435 CachedResult.TypeClass = STC_Void;
436 CachedResult.Type = 0;
437 CachedCompletionResults.push_back(CachedResult);
438 }
439 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000440 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000441 }
442
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 case Result::RK_Keyword:
444 case Result::RK_Pattern:
445 // Ignore keywords and patterns; we don't care, since they are so
446 // easily regenerated.
447 break;
448
449 case Result::RK_Macro: {
450 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000451 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000452 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000453 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000454 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000455 = (1LL << CodeCompletionContext::CCC_TopLevel)
456 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
457 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
458 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
459 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
460 | (1LL << CodeCompletionContext::CCC_Statement)
461 | (1LL << CodeCompletionContext::CCC_Expression)
462 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
463 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
464 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
465 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
466 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000467
468 CachedResult.Priority = R.Priority;
469 CachedResult.Kind = R.CursorKind;
470 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000471 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000472 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000473 CachedCompletionResults.push_back(CachedResult);
474 break;
475 }
476 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000477 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000478
479 // Save the current top-level hash value.
480 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000481}
482
483void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000484 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000485 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000486 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000487}
488
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000489namespace {
490
Sebastian Redl2c499f62010-08-18 23:56:43 +0000491/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000492/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000493class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000494 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000495 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000496 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000497 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000498 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregore8bbc122011-09-02 00:18:52 +0000501 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000502public:
Alp Toker80758082014-07-06 05:26:44 +0000503 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
504 std::shared_ptr<TargetOptions> &TargetOpts,
505 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
506 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
507 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000508
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000509 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
510 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000511 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000512 return false;
513
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000514 LangOpt = LangOpts;
515 InitializedLanguage = true;
516
517 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000518 return false;
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000521 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
522 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000523 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000524 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000525 return false;
Alp Toker80758082014-07-06 05:26:44 +0000526
527 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
528 Target =
529 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000530
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000531 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000532 return false;
533 }
Mike Stump11289f42009-09-09 15:08:12 +0000534
Craig Topperafa7cb32014-03-13 06:07:04 +0000535 void ReadCounter(const serialization::ModuleFile &M,
536 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000537 Counter = Value;
538 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000539
540private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000541 void updated() {
542 if (!Target || !InitializedLanguage)
543 return;
544
545 // Inform the target of the language options.
546 //
547 // FIXME: We shouldn't need to do this, the target should be immutable once
548 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000549 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000550
551 // Initialize the preprocessor.
552 PP.Initialize(*Target);
553
554 // Initialize the ASTContext
555 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000556
557 // We didn't have access to the comment options when the ASTContext was
558 // constructed, so register them now.
559 Context.getCommentCommandTraits().registerCommentOptions(
560 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000561 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000562};
563
Douglas Gregor6b930962013-05-03 22:58:43 +0000564 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000565class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000566 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000567 SourceManager *SourceMgr;
568
Douglas Gregor33cdd812010-02-18 18:08:43 +0000569public:
David Blaikief18d91a2011-09-26 00:01:39 +0000570 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000571 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000572 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000573
Craig Topperafa7cb32014-03-13 06:07:04 +0000574 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000575 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000576 if (PP)
577 SourceMgr = &PP->getSourceManager();
578 }
579
Craig Topperafa7cb32014-03-13 06:07:04 +0000580 void HandleDiagnostic(DiagnosticsEngine::Level Level,
581 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000582};
583
584/// \brief RAII object that optionally captures diagnostics, if
585/// there is no diagnostic client to capture them already.
586class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000587 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000588 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000589 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000590 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000591
592public:
David Blaikie9c902b52011-09-25 23:23:43 +0000593 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000594 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000595 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000596 {
Craig Topper49a27902014-05-22 04:46:25 +0000597 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000598 OwningPreviousClient = Diags.takeClient();
599 PreviousClient = Diags.getClient();
600 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000601 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000602 }
603
604 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000605 if (Diags.getClient() == &Client)
606 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000607 }
608};
609
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000610} // anonymous namespace
611
David Blaikief18d91a2011-09-26 00:01:39 +0000612void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000613 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000614 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000615 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000616
Douglas Gregor6b930962013-05-03 22:58:43 +0000617 // Only record the diagnostic if it's part of the source manager we know
618 // about. This effectively drops diagnostics from modules we're building.
619 // FIXME: In the long run, ee don't want to drop source managers from modules.
620 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000621 StoredDiags.emplace_back(Level, Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000622}
623
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000624IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
625 return Reader;
626}
627
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000628ASTMutationListener *ASTUnit::getASTMutationListener() {
629 if (WriterData)
630 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000631 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000632}
633
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000634ASTDeserializationListener *ASTUnit::getDeserializationListener() {
635 if (WriterData)
636 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000637 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000638}
639
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000640std::unique_ptr<llvm::MemoryBuffer>
641ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000642 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000643 auto Buffer = FileMgr->getBufferForFile(Filename);
644 if (Buffer)
645 return std::move(*Buffer);
646 if (ErrorStr)
647 *ErrorStr = Buffer.getError().message();
648 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000649}
650
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000651/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000652void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000653 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000654 assert(Diags.get() && "no DiagnosticsEngine was provided");
655 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000656 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000657}
658
David Blaikie6f7382d2014-08-10 19:08:04 +0000659std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000660 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000661 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000662 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
663 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
664 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
665 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000666 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000667
668 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000669 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
670 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000671 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
672 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000673 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000674
Justin Bognerdbbcb112014-10-14 23:36:06 +0000675 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000676
Douglas Gregor16bef852009-10-16 20:01:17 +0000677 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000678 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000679 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000680 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
681 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000682 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000683 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000684 AST->getFileManager(),
685 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000686 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000687 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000688 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000689 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000690 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000691 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000692 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000693 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000694
David Blaikiee3041682017-01-05 19:11:36 +0000695 auto PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000696
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000697 for (const auto &RemappedFile : RemappedFiles)
698 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000699
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000700 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000701
David Blaikie6f7382d2014-08-10 19:08:04 +0000702 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000703 unsigned Counter;
704
David Blaikie41565462017-01-05 19:48:07 +0000705 AST->PP = std::make_shared<Preprocessor>(
706 std::move(PPOpts), AST->getDiagnostics(), AST->ASTFileLangOpts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000707 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, *AST,
David Blaikie41565462017-01-05 19:48:07 +0000708 /*IILookup=*/nullptr,
709 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 Preprocessor &PP = *AST->PP;
711
Alp Toker08043432014-05-03 03:46:04 +0000712 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
713 PP.getIdentifierTable(), PP.getSelectorTable(),
714 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000716
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000717 bool disableValid = false;
718 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
719 disableValid = true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000720 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000721 /*isysroot=*/"",
722 /*DisableValidation=*/disableValid,
723 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000724
David Blaikie2721c322014-08-10 16:54:39 +0000725 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
726 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
727 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000728
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000729 // Attach the AST reader to the AST context as an external AST
730 // source, so that declarations will be deserialized from the
731 // AST file as needed.
732 // We need the external source to be set up before we read the AST, because
733 // eagerly-deserialized declarations may use it.
734 Context.setExternalSource(AST->Reader);
735
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000736 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000737 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000738 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000739 break;
Mike Stump11289f42009-09-09 15:08:12 +0000740
Sebastian Redl2c499f62010-08-18 23:56:43 +0000741 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000742 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000743 case ASTReader::OutOfDate:
744 case ASTReader::VersionMismatch:
745 case ASTReader::ConfigurationMismatch:
746 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000747 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000748 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000749 }
Mike Stump11289f42009-09-09 15:08:12 +0000750
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000751 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000752
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000753 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000755 // Create an AST consumer, even though it isn't used.
756 AST->Consumer.reset(new ASTConsumer);
757
Sebastian Redl2c499f62010-08-18 23:56:43 +0000758 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000759 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
760 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000761 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000762
Douglas Gregor6b930962013-05-03 22:58:43 +0000763 // Tell the diagnostic client that we have started a source file.
764 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
765
David Blaikie6f7382d2014-08-10 19:08:04 +0000766 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000767}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000768
769namespace {
770
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000771/// \brief Preprocessor callback class that updates a hash value with the names
772/// of all macros that have been defined by the translation unit.
773class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
774 unsigned &Hash;
775
776public:
777 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000778
779 void MacroDefined(const Token &MacroNameTok,
780 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000781 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
782 }
783};
784
785/// \brief Add the given declaration to the hash of all top-level entities.
786void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
787 if (!D)
788 return;
789
790 DeclContext *DC = D->getDeclContext();
791 if (!DC)
792 return;
793
794 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
795 return;
796
797 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000798 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
799 // For an unscoped enum include the enumerators in the hash since they
800 // enter the top-level namespace.
801 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000802 for (const auto *EI : EnumD->enumerators()) {
803 if (EI->getIdentifier())
804 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000805 }
806 }
807 }
808
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000809 if (ND->getIdentifier())
810 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
811 else if (DeclarationName Name = ND->getDeclName()) {
812 std::string NameStr = Name.getAsString();
813 Hash = llvm::HashString(NameStr, Hash);
814 }
815 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000816 }
817
818 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
819 if (Module *Mod = ImportD->getImportedModule()) {
820 std::string ModName = Mod->getFullModuleName();
821 Hash = llvm::HashString(ModName, Hash);
822 }
823 return;
824 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000825}
826
Daniel Dunbar644dca02009-12-04 08:17:33 +0000827class TopLevelDeclTrackerConsumer : public ASTConsumer {
828 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000829 unsigned &Hash;
830
Daniel Dunbar644dca02009-12-04 08:17:33 +0000831public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000832 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
833 : Unit(_Unit), Hash(Hash) {
834 Hash = 0;
835 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000836
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000837 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000838 if (!D)
839 return;
840
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000841 // FIXME: Currently ObjC method declarations are incorrectly being
842 // reported as top-level declarations, even though their DeclContext
843 // is the containing ObjC @interface/@implementation. This is a
844 // fundamental problem in the parser right now.
845 if (isa<ObjCMethodDecl>(D))
846 return;
847
848 AddTopLevelDeclarationToHash(D, Hash);
849 Unit.addTopLevelDecl(D);
850
851 handleFileLevelDecl(D);
852 }
853
854 void handleFileLevelDecl(Decl *D) {
855 Unit.addFileLevelDecl(D);
856 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000857 for (auto *I : NSD->decls())
858 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000859 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000860 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000861
Craig Topperafa7cb32014-03-13 06:07:04 +0000862 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000863 for (Decl *TopLevelDecl : D)
864 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000865 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000866 }
867
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000868 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000869 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000870
Craig Topperafa7cb32014-03-13 06:07:04 +0000871 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000872 for (Decl *TopLevelDecl : D)
873 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000874 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000875
Craig Topperafa7cb32014-03-13 06:07:04 +0000876 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000877 return Unit.getASTMutationListener();
878 }
879
Craig Topperafa7cb32014-03-13 06:07:04 +0000880 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000881 return Unit.getDeserializationListener();
882 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000883};
884
885class TopLevelDeclTrackerAction : public ASTFrontendAction {
886public:
887 ASTUnit &Unit;
888
David Blaikie6beb6aa2014-08-10 19:56:51 +0000889 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
890 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000891 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000892 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
893 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000894 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
895 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000896 }
897
898public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000899 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
900
Craig Topperafa7cb32014-03-13 06:07:04 +0000901 bool hasCodeCompletionSupport() const override { return false; }
902 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000903 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000904 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000905};
906
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000907class PrecompilePreambleAction : public ASTFrontendAction {
908 ASTUnit &Unit;
909 bool HasEmittedPreamblePCH;
910
911public:
912 explicit PrecompilePreambleAction(ASTUnit &Unit)
913 : Unit(Unit), HasEmittedPreamblePCH(false) {}
914
David Blaikie6beb6aa2014-08-10 19:56:51 +0000915 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
916 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000917 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
918 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000919 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000920
Craig Topperafa7cb32014-03-13 06:07:04 +0000921 bool hasCodeCompletionSupport() const override { return false; }
922 bool hasASTFileSupport() const override { return false; }
923 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000924};
925
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000926class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000927 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000928 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000929 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000930 PrecompilePreambleAction *Action;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000931 std::unique_ptr<raw_ostream> Out;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000932
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000933public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000934 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
935 const Preprocessor &PP, StringRef isysroot,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000936 std::unique_ptr<raw_ostream> Out)
Richard Smithbd97f352016-08-25 18:26:30 +0000937 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
David Blaikie61137e12017-01-05 18:23:18 +0000938 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000939 /*AllowASTWithErrors=*/true),
940 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000941 Out(std::move(Out)) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000942 Hash = 0;
943 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000944
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000945 bool HandleTopLevelDecl(DeclGroupRef DG) override {
946 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000947 // FIXME: Currently ObjC method declarations are incorrectly being
948 // reported as top-level declarations, even though their DeclContext
949 // is the containing ObjC @interface/@implementation. This is a
950 // fundamental problem in the parser right now.
951 if (isa<ObjCMethodDecl>(D))
952 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000953 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000954 TopLevelDecls.push_back(D);
955 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000956 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000957 }
958
Craig Topperafa7cb32014-03-13 06:07:04 +0000959 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000960 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000961 if (hasEmittedPCH()) {
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000962 // Write the generated bitstream to "Out".
963 *Out << getPCH();
964 // Make sure it hits disk now.
965 Out->flush();
966 // Free the buffer.
967 llvm::SmallVector<char, 0> Empty;
968 getPCH() = std::move(Empty);
969
Douglas Gregore9db88f2010-08-03 19:06:41 +0000970 // Translate the top-level declarations we captured during
971 // parsing into declaration IDs in the precompiled
972 // preamble. This will allow us to deserialize those top-level
973 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000974 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000975 // Invalid top-level decls may not have been serialized.
976 if (D->isInvalidDecl())
977 continue;
978 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
979 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000980
981 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000982 }
983 }
984};
985
Hans Wennborgdcfba332015-10-06 23:40:43 +0000986} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000987
David Blaikie6beb6aa2014-08-10 19:56:51 +0000988std::unique_ptr<ASTConsumer>
989PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
990 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000991 std::string Sysroot;
992 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000993 std::unique_ptr<raw_ostream> OS =
994 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
995 OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +0000996 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000997 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000998
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000999 if (!CI.getFrontendOpts().RelocatablePCH)
1000 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001001
Craig Topperb8a70532014-09-10 04:53:53 +00001002 CI.getPreprocessor().addPPCallbacks(
1003 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1004 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001005 return llvm::make_unique<PrecompilePreambleConsumer>(
Peter Collingbourne03f89072016-07-15 00:55:40 +00001006 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
Daniel Dunbar764c0822009-12-01 09:51:01 +00001007}
1008
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001009static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1010 return StoredDiag.getLocation().isValid();
1011}
1012
1013static void
1014checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001015 // Get rid of stored diagnostics except the ones from the driver which do not
1016 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001017 StoredDiags.erase(
1018 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1019 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001020}
1021
1022static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1023 StoredDiagnostics,
1024 SourceManager &SM) {
1025 // The stored diagnostic has the old source manager in it; update
1026 // the locations to refer into the new source manager. Since we've
1027 // been careful to make sure that the source manager's state
1028 // before and after are identical, so that we can reuse the source
1029 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001030 for (StoredDiagnostic &SD : StoredDiagnostics) {
1031 if (SD.getLocation().isValid()) {
1032 FullSourceLoc Loc(SD.getLocation(), SM);
1033 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001034 }
1035 }
1036}
1037
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001038/// Parse the source file into a translation unit using the given compiler
1039/// invocation, replacing the current translation unit.
1040///
1041/// \returns True if a failure occurred that causes the ASTUnit not to
1042/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001043bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1044 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
Rafael Espindola4674a872014-08-13 17:08:22 +00001045 SavedMainFileBuffer.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001046
Rafael Espindola32482082014-08-18 16:23:45 +00001047 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001048 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001049
Daniel Dunbar764c0822009-12-01 09:51:01 +00001050 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001051 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001052 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001053
1054 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001055 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1056 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001057
David Blaikieea4395e2017-01-06 19:49:01 +00001058 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001059 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001060
Douglas Gregor8e984da2010-08-04 16:47:14 +00001061 // Set up diagnostics, capturing any diagnostics that would
1062 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001063 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001064
Daniel Dunbar764c0822009-12-01 09:51:01 +00001065 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001066 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001067 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001068 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001069 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001070
Daniel Dunbar764c0822009-12-01 09:51:01 +00001071 // Inform the target of the language options.
1072 //
1073 // FIXME: We shouldn't need to do this, the target should be immutable once
1074 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001075 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001076
Ted Kremenek84de4a12011-03-21 18:40:07 +00001077 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001078 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001079 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001080 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001081 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001082 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001083
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001084 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001085 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001086 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001087 if (!FileMgr) {
1088 Clang->createFileManager();
1089 FileMgr = &Clang->getFileManager();
1090 }
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001091 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1092 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001093 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001094 Ctx = nullptr;
1095 PP = nullptr;
1096 Reader = nullptr;
1097
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001098 // Clear out old caches and data.
1099 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001100 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001101 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001102
Douglas Gregor7b02b582010-08-20 00:02:33 +00001103 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001104 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001105 TopLevelDeclsInPreamble.clear();
1106 }
1107
Daniel Dunbar764c0822009-12-01 09:51:01 +00001108 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001109 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001110
Daniel Dunbar764c0822009-12-01 09:51:01 +00001111 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001112 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001113
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001114 // If the main file has been overridden due to the use of a preamble,
1115 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001116 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001117 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001118 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1119 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001120 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1121 PreprocessorOpts.PrecompiledPreambleBytes.second
1122 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001123 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001124 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001125
Douglas Gregord9a30af2010-08-02 20:51:39 +00001126 // The stored diagnostic has the old source manager in it; update
1127 // the locations to refer into the new source manager. Since we've
1128 // been careful to make sure that the source manager's state
1129 // before and after are identical, so that we can reuse the source
1130 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001131 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001132
1133 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001134 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001135 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001136
1137 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1138 new TopLevelDeclTrackerAction(*this));
1139
Ted Kremenek022a4902011-03-22 01:15:24 +00001140 // Recover resources if we crash before exiting this method.
1141 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1142 ActCleanup(Act.get());
1143
Douglas Gregor32fbe312012-01-20 16:28:04 +00001144 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001145 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001146
Richard Smith26b8f782016-03-25 21:46:44 +00001147 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001148 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1149 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001150
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001151 if (!Act->Execute())
1152 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001153
1154 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001155
Daniel Dunbar644dca02009-12-04 08:17:33 +00001156 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001157
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001158 FailedParseDiagnostics.clear();
1159
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001160 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001161
Daniel Dunbar764c0822009-12-01 09:51:01 +00001162error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001163 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001164 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001165
1166 // Keep the ownership of the data in the ASTUnit because the client may
1167 // want to see the diagnostics.
1168 transferASTDataFromCompilerInstance(*Clang);
1169 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001170 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001171 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001172 return true;
1173}
1174
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001175/// \brief Simple function to retrieve a path for a preamble precompiled header.
1176static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001177 // FIXME: This is a hack so that we can override the preamble file during
1178 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001179 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001180 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1181 if (TmpFile)
1182 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001183
1184 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001185 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001186
1187 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001188}
1189
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001190/// \brief Compute the preamble for the main file, providing the source buffer
1191/// that corresponds to the main file along with a pair (bytes, start-of-line)
1192/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001193ASTUnit::ComputedPreamble
1194ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001195 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001196 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001197
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001198 // Try to determine if the main file has been remapped, either from the
1199 // command line (to another file) or directly through the compiler invocation
1200 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001201 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001202 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001203 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001204 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001205 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001207 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1208 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001209 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001210 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001211 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 // We found a remapping. Try to load the resulting, remapped source.
David Blaikied6902a12014-08-29 06:34:53 +00001213 BufferOwner = getBufferForFile(RF.second);
1214 if (!BufferOwner)
1215 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001216 }
1217 }
1218 }
1219
1220 // Check whether there is a file-buffer remapping. It supercedes the
1221 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001222 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1223 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001224 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001225 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001226 if (MainFileID == MID) {
1227 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001228 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001229 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001230 }
1231 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001232 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001233 }
1234
1235 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001236 if (!Buffer && !BufferOwner) {
1237 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1238 if (!BufferOwner)
1239 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001240 }
David Blaikie3d95d852014-08-11 22:08:06 +00001241
David Blaikied6902a12014-08-29 06:34:53 +00001242 if (!Buffer)
1243 Buffer = BufferOwner.get();
1244 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1245 *Invocation.getLangOpts(), MaxLines);
1246 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1247 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001248}
1249
Dmitri Gribenko47652522013-12-20 00:16:25 +00001250ASTUnit::PreambleFileHash
1251ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1252 PreambleFileHash Result;
1253 Result.Size = Size;
1254 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001255 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001256 return Result;
1257}
1258
1259ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1260 const llvm::MemoryBuffer *Buffer) {
1261 PreambleFileHash Result;
1262 Result.Size = Buffer->getBufferSize();
1263 Result.ModTime = 0;
1264
1265 llvm::MD5 MD5Ctx;
1266 MD5Ctx.update(Buffer->getBuffer().data());
1267 MD5Ctx.final(Result.MD5);
1268
1269 return Result;
1270}
1271
1272namespace clang {
1273bool operator==(const ASTUnit::PreambleFileHash &LHS,
1274 const ASTUnit::PreambleFileHash &RHS) {
1275 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001276 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001277}
1278} // namespace clang
1279
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001280static std::pair<unsigned, unsigned>
1281makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1282 const LangOptions &LangOpts) {
1283 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1284 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1285 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1286 return std::make_pair(Offset, EndOffset);
1287}
1288
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001289static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1290 const LangOptions &LangOpts,
1291 const FixItHint &InFix) {
1292 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001293 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1294 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1295 LangOpts);
1296 OutFix.CodeToInsert = InFix.CodeToInsert;
1297 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001298 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001299}
1300
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001301static ASTUnit::StandaloneDiagnostic
1302makeStandaloneDiagnostic(const LangOptions &LangOpts,
1303 const StoredDiagnostic &InDiag) {
1304 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001305 OutDiag.ID = InDiag.getID();
1306 OutDiag.Level = InDiag.getLevel();
1307 OutDiag.Message = InDiag.getMessage();
1308 OutDiag.LocOffset = 0;
1309 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001310 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001311 const SourceManager &SM = InDiag.getLocation().getManager();
1312 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1313 OutDiag.Filename = SM.getFilename(FileLoc);
1314 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001315 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001316 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001317 for (const CharSourceRange &Range : InDiag.getRanges())
1318 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1319 for (const FixItHint &FixIt : InDiag.getFixIts())
1320 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001321
1322 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001323}
1324
Douglas Gregor4dde7492010-07-23 23:58:40 +00001325/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1326/// the source file.
1327///
1328/// This routine will compute the preamble of the main source file. If a
1329/// non-trivial preamble is found, it will precompile that preamble into a
1330/// precompiled header so that the precompiled preamble can be used to reduce
1331/// reparsing time. If a precompiled preamble has already been constructed,
1332/// this routine will determine if it is still valid and, if so, avoid
1333/// rebuilding the precompiled preamble.
1334///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001335/// \param AllowRebuild When true (the default), this routine is
1336/// allowed to rebuild the precompiled preamble if it is found to be
1337/// out-of-date.
1338///
1339/// \param MaxLines When non-zero, the maximum number of lines that
1340/// can occur within the preamble.
1341///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001342/// \returns If the precompiled preamble can be used, returns a newly-allocated
1343/// buffer that should be used in place of the main file when doing so.
1344/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001345std::unique_ptr<llvm::MemoryBuffer>
1346ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001347 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Rafael Espindola2346a372014-08-18 18:47:08 +00001348 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1349 unsigned MaxLines) {
1350
David Blaikieea4395e2017-01-06 19:49:01 +00001351 auto PreambleInvocation =
1352 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
Douglas Gregor3cc15812011-07-01 18:22:13 +00001353 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001354 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001355 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001356
David Blaikied6902a12014-08-29 06:34:53 +00001357 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001358
David Blaikied6902a12014-08-29 06:34:53 +00001359 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001360 // We couldn't find a preamble in the main source. Clear out the current
1361 // preamble, if we have one. It's obviously no good any more.
1362 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001363 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001364
1365 // The next time we actually see a preamble, precompile it.
1366 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001367 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001368 }
1369
1370 if (!Preamble.empty()) {
1371 // We've previously computed a preamble. Check whether we have the same
1372 // preamble now that we did before, and that there's enough space in
1373 // the main-file buffer within the precompiled preamble to fit the
1374 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001375 if (Preamble.size() == NewPreamble.Size &&
1376 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1377 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1378 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001379 // The preamble has not changed. We may be able to re-use the precompiled
1380 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001381
Douglas Gregor0e119552010-07-31 00:40:00 +00001382 // Check that none of the files used by the preamble have changed.
1383 bool AnyFileChanged = false;
1384
1385 // First, make a record of those files that have been overridden via
1386 // remapping or unsaved_files.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001387 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001388 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1389 if (AnyFileChanged)
1390 break;
1391
Ben Langmuirc8130a72014-02-20 21:59:23 +00001392 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001393 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001394 // If we can't stat the file we're remapping to, assume that something
1395 // horrible happened.
1396 AnyFileChanged = true;
1397 break;
1398 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001399
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001400 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001401 Status.getSize(),
1402 llvm::sys::toTimeT(Status.getLastModificationTime()));
Douglas Gregor0e119552010-07-31 00:40:00 +00001403 }
Alp Toker1b070d22014-07-07 07:47:20 +00001404
1405 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1406 if (AnyFileChanged)
1407 break;
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001408
1409 vfs::Status Status;
1410 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1411 AnyFileChanged = true;
1412 break;
1413 }
1414
1415 OverriddenFiles[Status.getUniqueID()] =
Alp Toker1b070d22014-07-07 07:47:20 +00001416 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001417 }
1418
1419 // Check whether anything has changed.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001420 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001421 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1422 !AnyFileChanged && F != FEnd;
1423 ++F) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001424 vfs::Status Status;
1425 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1426 // If we can't stat the file, assume that something horrible happened.
1427 AnyFileChanged = true;
1428 break;
1429 }
1430
1431 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1432 = OverriddenFiles.find(Status.getUniqueID());
Douglas Gregor0e119552010-07-31 00:40:00 +00001433 if (Overridden != OverriddenFiles.end()) {
1434 // This file was remapped; check whether the newly-mapped file
1435 // matches up with the previous mapping.
1436 if (Overridden->second != F->second)
1437 AnyFileChanged = true;
1438 continue;
1439 }
1440
1441 // The file was not remapped; check whether it has changed on disk.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001442 if (Status.getSize() != uint64_t(F->second.Size) ||
Pavel Labathac71c8e2016-11-09 10:52:22 +00001443 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1444 F->second.ModTime)
Douglas Gregor0e119552010-07-31 00:40:00 +00001445 AnyFileChanged = true;
1446 }
1447
1448 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001449 // Okay! We can re-use the precompiled preamble.
1450
1451 // Set the state of the diagnostic object to mimic its state
1452 // after parsing the preamble.
1453 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001454 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001455 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001456 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001457
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001458 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001459 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001460 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001461 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001462
1463 // If we aren't allowed to rebuild the precompiled preamble, just
1464 // return now.
1465 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001466 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001467
Douglas Gregor4dde7492010-07-23 23:58:40 +00001468 // We can't reuse the previously-computed preamble. Build a new one.
1469 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001470 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001471 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001472 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001473 } else if (!AllowRebuild) {
1474 // We aren't allowed to rebuild the precompiled preamble; just
1475 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001476 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001477 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001478
1479 // If the preamble rebuild counter > 1, it's because we previously
1480 // failed to build a preamble and we're not yet ready to try
1481 // again. Decrement the counter and return a failure.
1482 if (PreambleRebuildCounter > 1) {
1483 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001484 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001485 }
1486
Douglas Gregore10f0e52010-09-11 17:56:52 +00001487 // Create a temporary file for the precompiled preamble. In rare
1488 // circumstances, this can fail.
1489 std::string PreamblePCHPath = GetPreamblePCHPath();
1490 if (PreamblePCHPath.empty()) {
1491 // Try again next time.
1492 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001493 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001494 }
1495
Douglas Gregor4dde7492010-07-23 23:58:40 +00001496 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001497 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001498 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001499
Douglas Gregord9a30af2010-08-02 20:51:39 +00001500 // Save the preamble text for later; we'll need to compare against it for
1501 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001502 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001503 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001504 NewPreamble.Buffer->getBufferStart(),
1505 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1506 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001507
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001508 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001509 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001510
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001511 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001512 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001513 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001514
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001515 // Tell the compiler invocation to generate a temporary precompiled header.
1516 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001517 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001518 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001519 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1520 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001521
1522 // Create the compiler instance to use for building the precompiled preamble.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001523 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001524 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001525
1526 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001527 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1528 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001529
David Blaikieea4395e2017-01-06 19:49:01 +00001530 Clang->setInvocation(std::move(PreambleInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001531 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001532
Douglas Gregor8e984da2010-08-04 16:47:14 +00001533 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001534 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001535
1536 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001537 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001538 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001539 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001540 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001541 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001542 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001543 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001544 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001545 }
1546
1547 // Inform the target of the language options.
1548 //
1549 // FIXME: We shouldn't need to do this, the target should be immutable once
1550 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001551 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001552
Ted Kremenek84de4a12011-03-21 18:40:07 +00001553 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001555 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001556 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001557 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001558 "IR inputs not support here!");
1559
1560 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001561 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001562 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001563 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001564 TopLevelDecls.clear();
1565 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001566 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001567
1568 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1569 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1570 if (!VFS)
1571 return nullptr;
1572
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001573 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001574 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001575
1576 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001577 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001578 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001579
Ben Langmuir33c80902014-06-30 20:04:14 +00001580 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1581 Clang->addDependencyCollector(PreambleDepCollector);
1582
Ahmed Charlesb8984322014-03-07 20:03:18 +00001583 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001584 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001585 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001586 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001587 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001588 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001589 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001590 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001591 }
1592
1593 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001594
1595 // Transfer any diagnostics generated when parsing the preamble into the set
1596 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001597 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1598 E = stored_diag_end();
1599 I != E; ++I)
1600 PreambleDiagnostics.push_back(
1601 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001602
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001603 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001604
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001605 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1606
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001607 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001608 // The preamble PCH failed (e.g. there was a module loading fatal error),
1609 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001610 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001611 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001612 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001613 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001614 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001615 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001616 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001617 }
1618
1619 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001620 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001621 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001622
1623 // Keep track of all of the files that the source manager knows about,
1624 // so we can verify whether they have changed or not.
1625 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001626 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001627 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1628 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1629 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001630 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001631 if (time_t ModTime = File->getModificationTime()) {
1632 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001633 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001634 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001635 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001636 FilesInPreamble[File->getName()] =
1637 PreambleFileHash::createForMemoryBuffer(Buffer);
1638 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001639 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001640
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001641 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001642 PreprocessorOpts.RemappedFileBuffers.pop_back();
1643
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001644 // If the hash of top-level entities differs from the hash of the top-level
1645 // entities the last time we rebuilt the preamble, clear out the completion
1646 // cache.
1647 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1648 CompletionCacheTopLevelHashValue = 0;
1649 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1650 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001651
David Blaikied6902a12014-08-29 06:34:53 +00001652 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001653 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001654}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001655
Douglas Gregore9db88f2010-08-03 19:06:41 +00001656void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1657 std::vector<Decl *> Resolved;
1658 Resolved.reserve(TopLevelDeclsInPreamble.size());
1659 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001660 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001661 // Resolve the declaration ID to an actual declaration, possibly
1662 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001663 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001664 Resolved.push_back(D);
1665 }
1666 TopLevelDeclsInPreamble.clear();
1667 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1668}
1669
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001670void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001671 // Steal the created target, context, and preprocessor if they have been
1672 // created.
1673 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001674 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001675 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001676 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001677 if (CI.hasASTContext())
1678 Ctx = &CI.getASTContext();
1679 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001680 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001681 CI.setSourceManager(nullptr);
1682 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001683 if (CI.hasTarget())
1684 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001685 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001686 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001687}
1688
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001689StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001690 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1691 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1692 if (Input.isFile())
1693 return Input.getFile();
1694 else
1695 return Input.getBuffer()->getBufferIdentifier();
1696 }
1697
1698 if (SourceMgr) {
1699 if (const FileEntry *
1700 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1701 return FE->getName();
1702 }
1703
1704 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001705}
1706
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001707StringRef ASTUnit::getASTFileName() const {
1708 if (!isMainFileAST())
1709 return StringRef();
1710
1711 serialization::ModuleFile &
1712 Mod = Reader->getModuleManager().getPrimaryModule();
1713 return Mod.FileName;
1714}
1715
David Blaikieea4395e2017-01-06 19:49:01 +00001716std::unique_ptr<ASTUnit>
1717ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1718 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1719 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1720 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001721 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001722 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1723 createVFSFromCompilerInvocation(*CI, *Diags);
1724 if (!VFS)
1725 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001726 AST->Diagnostics = Diags;
1727 AST->FileSystemOpts = CI->getFileSystemOpts();
1728 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001729 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001730 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1731 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1732 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001733 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001734
David Blaikieea4395e2017-01-06 19:49:01 +00001735 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001736}
1737
Ahmed Charlesb8984322014-03-07 20:03:18 +00001738ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001739 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001740 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001741 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001742 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001743 bool OnlyLocalDecls, bool CaptureDiagnostics,
1744 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1745 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1746 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001747 assert(CI && "A CompilerInvocation is required");
1748
Ahmed Charlesb8984322014-03-07 20:03:18 +00001749 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001750 ASTUnit *AST = Unit;
1751 if (!AST) {
1752 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001753 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001754 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001755 if (!AST)
1756 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001757 }
1758
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001759 if (!ResourceFilesPath.empty()) {
1760 // Override the resources path.
1761 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1762 }
1763 AST->OnlyLocalDecls = OnlyLocalDecls;
1764 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001765 if (PrecompilePreambleAfterNParses > 0)
1766 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001767 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001768 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001769 AST->IncludeBriefCommentsInCodeCompletion
1770 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001771
1772 // Recover resources if we crash before exiting this method.
1773 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001774 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001775 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1776 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001777 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001778
1779 // We'll manage file buffers ourselves.
1780 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1781 CI->getFrontendOpts().DisableFree = false;
1782 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1783
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001784 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001785 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001786 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001787
1788 // Recover resources if we crash before exiting this method.
1789 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1790 CICleanup(Clang.get());
1791
David Blaikieea4395e2017-01-06 19:49:01 +00001792 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001793 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001794
1795 // Set up diagnostics, capturing any diagnostics that would
1796 // otherwise be dropped.
1797 Clang->setDiagnostics(&AST->getDiagnostics());
1798
1799 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001800 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001801 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001802 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001803 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001804
1805 // Inform the target of the language options.
1806 //
1807 // FIXME: We shouldn't need to do this, the target should be immutable once
1808 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001809 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001810
1811 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1812 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001813 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001814 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001815 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001816 "IR inputs not supported here!");
1817
1818 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001819 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001820 AST->Ctx = nullptr;
1821 AST->PP = nullptr;
1822 AST->Reader = nullptr;
1823
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001824 // Create a file manager object to provide access to and cache the filesystem.
1825 Clang->setFileManager(&AST->getFileManager());
1826
1827 // Create the source manager.
1828 Clang->setSourceManager(&AST->getSourceManager());
1829
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001830 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001831
Ahmed Charlesb8984322014-03-07 20:03:18 +00001832 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001833 if (!Act) {
1834 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1835 Act = TrackerAct.get();
1836 }
1837
1838 // Recover resources if we crash before exiting this method.
1839 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1840 ActCleanup(TrackerAct.get());
1841
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001842 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1843 AST->transferASTDataFromCompilerInstance(*Clang);
1844 if (OwnAST && ErrAST)
1845 ErrAST->swap(OwnAST);
1846
Craig Topper49a27902014-05-22 04:46:25 +00001847 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001848 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001849
1850 if (Persistent && !TrackerAct) {
1851 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001852 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1853 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001854 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001855 if (Clang->hasASTConsumer())
1856 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001857 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1858 *AST, AST->getCurrentTopLevelHashValue()));
1859 Clang->setASTConsumer(
1860 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001861 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001862 if (!Act->Execute()) {
1863 AST->transferASTDataFromCompilerInstance(*Clang);
1864 if (OwnAST && ErrAST)
1865 ErrAST->swap(OwnAST);
1866
Craig Topper49a27902014-05-22 04:46:25 +00001867 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001868 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001869
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001870 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001871 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001872
1873 Act->EndSourceFile();
1874
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001875 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001876 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001877 else
1878 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001879}
1880
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001881bool ASTUnit::LoadFromCompilerInvocation(
1882 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001883 unsigned PrecompilePreambleAfterNParses) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001884 if (!Invocation)
1885 return true;
1886
1887 // We'll manage file buffers ourselves.
1888 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1889 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001890 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001891 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001892
Rafael Espindola32482082014-08-18 16:23:45 +00001893 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001894 if (PrecompilePreambleAfterNParses > 0) {
1895 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001896 OverrideMainBuffer =
1897 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001898 getDiagnostics().Reset();
1899 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001900 }
1901
Douglas Gregor16896c42010-10-28 15:44:59 +00001902 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001903 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001904
Ted Kremenek022a4902011-03-22 01:15:24 +00001905 // Recover resources if we crash before exiting this method.
1906 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001907 MemBufferCleanup(OverrideMainBuffer.get());
1908
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001909 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001910}
1911
David Blaikie103a2de2014-04-25 17:01:33 +00001912std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001913 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001914 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001915 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001916 bool OnlyLocalDecls, bool CaptureDiagnostics,
1917 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1918 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1919 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001920 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001921 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001922 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001923 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001924 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001925 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001926 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001927 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001928 AST->IncludeBriefCommentsInCodeCompletion
1929 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001930 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001931 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1932 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001933 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001934
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001935 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001936 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1937 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001938 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1939 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001940 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001941
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001942 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001943 PrecompilePreambleAfterNParses))
David Blaikie103a2de2014-04-25 17:01:33 +00001944 return nullptr;
1945 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001946}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001947
Ahmed Charlesb8984322014-03-07 20:03:18 +00001948ASTUnit *ASTUnit::LoadFromCommandLine(
1949 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001950 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001951 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1952 bool OnlyLocalDecls, bool CaptureDiagnostics,
1953 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001954 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001955 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1956 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1957 bool UserFilesAreVolatile, bool ForSerialization,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001958 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001959 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001960
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001961 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001962
1963 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001964
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001965 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001966
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001967 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001968 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001969
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001970 CI = clang::createInvocationFromCommandLine(
David Blaikieea4395e2017-01-06 19:49:01 +00001971 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001972 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001973 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001974 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001975
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001976 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001977 for (const auto &RemappedFile : RemappedFiles) {
1978 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1979 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001980 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001981 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1982 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1983 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001984
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001985 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001986 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001987
Erik Verbruggen6e922512012-04-12 10:11:59 +00001988 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1989
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001990 if (ModuleFormat)
1991 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1992
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001993 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001994 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001995 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001996 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001997 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001998 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001999 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2000 createVFSFromCompilerInvocation(*CI, *Diags);
2001 if (!VFS)
2002 return nullptr;
2003 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002004 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002005 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002006 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002007 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002008 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002009 AST->IncludeBriefCommentsInCodeCompletion
2010 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002011 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002012 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002013 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002014 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002015 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002016 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00002017 // Zero out now to ease cleanup during crash recovery.
2018 CI = nullptr;
2019 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00002020
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002021 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002022 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2023 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002024
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002025 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00002026 PrecompilePreambleAfterNParses)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002027 // Some error occurred, if caller wants to examine diagnostics, pass it the
2028 // ASTUnit.
2029 if (ErrAST) {
2030 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2031 ErrAST->swap(AST);
2032 }
Craig Topper49a27902014-05-22 04:46:25 +00002033 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002034 }
2035
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002036 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002037}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002038
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002039bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2040 ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002041 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002042 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002043
2044 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002045
Douglas Gregor16896c42010-10-28 15:44:59 +00002046 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002047 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002048
Douglas Gregor0e119552010-07-31 00:40:00 +00002049 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002050 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002051 for (const auto &RB : PPOpts.RemappedFileBuffers)
2052 delete RB.second;
2053
Douglas Gregor0e119552010-07-31 00:40:00 +00002054 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002055 for (const auto &RemappedFile : RemappedFiles) {
2056 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2057 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002058 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002059
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002060 // If we have a preamble file lying around, or if we might try to
2061 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002062 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002063 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002064 OverrideMainBuffer =
2065 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2066
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002067 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00002068 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002069 getDiagnostics().Reset();
2070 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002071 if (OverrideMainBuffer)
2072 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002073
Douglas Gregor4dde7492010-07-23 23:58:40 +00002074 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002075 bool Result =
2076 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
Rafael Espindola32482082014-08-18 16:23:45 +00002077
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002078 // If we're caching global code-completion results, and the top-level
2079 // declarations have changed, clear out the code-completion cache.
2080 if (!Result && ShouldCacheCodeCompletionResults &&
2081 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2082 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002083
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002084 // We now need to clear out the completion info related to this translation
2085 // unit; it'll be recreated if necessary.
2086 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002087
Douglas Gregor4dde7492010-07-23 23:58:40 +00002088 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002089}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002090
Douglas Gregorb14904c2010-08-13 22:48:40 +00002091//----------------------------------------------------------------------------//
2092// Code completion
2093//----------------------------------------------------------------------------//
2094
2095namespace {
2096 /// \brief Code completion consumer that combines the cached code-completion
2097 /// results from an ASTUnit with the code-completion results provided to it,
2098 /// then passes the result on to
2099 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002100 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002101 ASTUnit &AST;
2102 CodeCompleteConsumer &Next;
2103
2104 public:
2105 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002106 const CodeCompleteOptions &CodeCompleteOpts)
2107 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2108 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002109 {
2110 // Compute the set of contexts in which we will look when we don't have
2111 // any information about the specific context.
2112 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002113 = (1LL << CodeCompletionContext::CCC_TopLevel)
2114 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2115 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2116 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2117 | (1LL << CodeCompletionContext::CCC_Statement)
2118 | (1LL << CodeCompletionContext::CCC_Expression)
2119 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2120 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2121 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2122 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2123 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2124 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2125 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002126
David Blaikiebbafb8a2012-03-11 07:00:24 +00002127 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002128 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2129 | (1LL << CodeCompletionContext::CCC_UnionTag)
2130 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002131 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002132
2133 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2134 CodeCompletionResult *Results,
2135 unsigned NumResults) override;
2136
2137 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2138 OverloadCandidate *Candidates,
2139 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002140 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2141 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002142
2143 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002144 return Next.getAllocator();
2145 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002146
Craig Topperafa7cb32014-03-13 06:07:04 +00002147 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002148 return Next.getCodeCompletionTUInfo();
2149 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002150 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002151} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00002152
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002153/// \brief Helper function that computes which global names are hidden by the
2154/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002155static void CalculateHiddenNames(const CodeCompletionContext &Context,
2156 CodeCompletionResult *Results,
2157 unsigned NumResults,
2158 ASTContext &Ctx,
2159 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002160 bool OnlyTagNames = false;
2161 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002162 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002163 case CodeCompletionContext::CCC_TopLevel:
2164 case CodeCompletionContext::CCC_ObjCInterface:
2165 case CodeCompletionContext::CCC_ObjCImplementation:
2166 case CodeCompletionContext::CCC_ObjCIvarList:
2167 case CodeCompletionContext::CCC_ClassStructUnion:
2168 case CodeCompletionContext::CCC_Statement:
2169 case CodeCompletionContext::CCC_Expression:
2170 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002171 case CodeCompletionContext::CCC_DotMemberAccess:
2172 case CodeCompletionContext::CCC_ArrowMemberAccess:
2173 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002174 case CodeCompletionContext::CCC_Namespace:
2175 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002176 case CodeCompletionContext::CCC_Name:
2177 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002178 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002179 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002180 break;
2181
2182 case CodeCompletionContext::CCC_EnumTag:
2183 case CodeCompletionContext::CCC_UnionTag:
2184 case CodeCompletionContext::CCC_ClassOrStructTag:
2185 OnlyTagNames = true;
2186 break;
2187
2188 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002189 case CodeCompletionContext::CCC_MacroName:
2190 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002191 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002192 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002193 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002194 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002195 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002196 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002197 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002198 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2199 case CodeCompletionContext::CCC_ObjCClassMessage:
2200 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002201 // We're looking for nothing, or we're looking for names that cannot
2202 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002203 return;
2204 }
2205
John McCall276321a2010-08-25 06:19:51 +00002206 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002207 for (unsigned I = 0; I != NumResults; ++I) {
2208 if (Results[I].Kind != Result::RK_Declaration)
2209 continue;
2210
2211 unsigned IDNS
2212 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2213
2214 bool Hiding = false;
2215 if (OnlyTagNames)
2216 Hiding = (IDNS & Decl::IDNS_Tag);
2217 else {
2218 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002219 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2220 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002221 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002222 HiddenIDNS |= Decl::IDNS_Tag;
2223 Hiding = (IDNS & HiddenIDNS);
2224 }
2225
2226 if (!Hiding)
2227 continue;
2228
2229 DeclarationName Name = Results[I].Declaration->getDeclName();
2230 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2231 HiddenNames.insert(Identifier->getName());
2232 else
2233 HiddenNames.insert(Name.getAsString());
2234 }
2235}
2236
Douglas Gregord46cf182010-08-16 20:01:48 +00002237void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2238 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002239 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002240 unsigned NumResults) {
2241 // Merge the results we were given with the results we cached.
2242 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002243 uint64_t InContexts =
2244 Context.getKind() == CodeCompletionContext::CCC_Recovery
2245 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002246 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002247 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002248 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002249 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002250 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002251 C = AST.cached_completion_begin(),
2252 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002253 C != CEnd; ++C) {
2254 // If the context we are in matches any of the contexts we are
2255 // interested in, we'll add this result.
2256 if ((C->ShowInContexts & InContexts) == 0)
2257 continue;
2258
2259 // If we haven't added any results previously, do so now.
2260 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002261 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2262 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002263 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2264 AddedResult = true;
2265 }
2266
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002267 // Determine whether this global completion result is hidden by a local
2268 // completion result. If so, skip it.
2269 if (C->Kind != CXCursor_MacroDefinition &&
2270 HiddenNames.count(C->Completion->getTypedText()))
2271 continue;
2272
Douglas Gregord46cf182010-08-16 20:01:48 +00002273 // Adjust priority based on similar type classes.
2274 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002275 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002276 if (!Context.getPreferredType().isNull()) {
2277 if (C->Kind == CXCursor_MacroDefinition) {
2278 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002279 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002280 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002281 } else if (C->Type) {
2282 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002283 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002284 Context.getPreferredType().getUnqualifiedType());
2285 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2286 if (ExpectedSTC == C->TypeClass) {
2287 // We know this type is similar; check for an exact match.
2288 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002289 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002290 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002291 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002292 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2293 Priority /= CCF_ExactTypeMatch;
2294 else
2295 Priority /= CCF_SimilarTypeMatch;
2296 }
2297 }
2298 }
2299
Douglas Gregor12785102010-08-24 20:21:13 +00002300 // Adjust the completion string, if required.
2301 if (C->Kind == CXCursor_MacroDefinition &&
2302 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2303 // Create a new code-completion string that just contains the
2304 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002305 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2306 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002307 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002308 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002309 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002310 }
2311
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002312 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002313 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002314 }
2315
2316 // If we did not add any cached completion results, just forward the
2317 // results we were given to the next consumer.
2318 if (!AddedResult) {
2319 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2320 return;
2321 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002322
Douglas Gregord46cf182010-08-16 20:01:48 +00002323 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2324 AllResults.size());
2325}
2326
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002327void ASTUnit::CodeComplete(
2328 StringRef File, unsigned Line, unsigned Column,
2329 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2330 bool IncludeCodePatterns, bool IncludeBriefComments,
2331 CodeCompleteConsumer &Consumer,
2332 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2333 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2334 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2335 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002336 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002337 return;
2338
Douglas Gregor16896c42010-10-28 15:44:59 +00002339 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002340 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002341 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002342
David Blaikieea4395e2017-01-06 19:49:01 +00002343 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002344
2345 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002346 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002347 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002348
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002349 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2350 CachedCompletionResults.empty();
2351 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2352 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2353 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2354
2355 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2356
Douglas Gregor8e984da2010-08-04 16:47:14 +00002357 FrontendOpts.CodeCompletionAt.FileName = File;
2358 FrontendOpts.CodeCompletionAt.Line = Line;
2359 FrontendOpts.CodeCompletionAt.Column = Column;
2360
2361 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002362 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002363
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002364 // Spell-checking and warnings are wasteful during code-completion.
2365 LangOpts.SpellChecking = false;
2366 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2367
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002368 std::unique_ptr<CompilerInstance> Clang(
2369 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002370
2371 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002372 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2373 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002374
David Blaikieea4395e2017-01-06 19:49:01 +00002375 auto &Inv = *CCInvocation;
2376 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002377 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002378
2379 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002380 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002381 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002382 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002383 StoredDiagnostics);
David Blaikieea4395e2017-01-06 19:49:01 +00002384 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2385
Douglas Gregor8e984da2010-08-04 16:47:14 +00002386 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002387 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002388 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002389 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002390 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002391 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002392 }
2393
2394 // Inform the target of the language options.
2395 //
2396 // FIXME: We shouldn't need to do this, the target should be immutable once
2397 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002398 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002399
Ted Kremenek84de4a12011-03-21 18:40:07 +00002400 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002401 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002402 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002403 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002404 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002405 "IR inputs not support here!");
2406
2407
2408 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002409 Clang->setFileManager(&FileMgr);
2410 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002411
2412 // Remap files.
2413 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002414 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002415 for (const auto &RemappedFile : RemappedFiles) {
2416 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2417 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002418 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002419
Douglas Gregorb14904c2010-08-13 22:48:40 +00002420 // Use the code completion consumer we were given, but adding any cached
2421 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002422 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002423 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002424 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002425
Douglas Gregor028d3e42010-08-09 20:45:32 +00002426 // If we have a precompiled preamble, try to use it. We only allow
2427 // the use of the precompiled preamble if we're if the completion
2428 // point is within the main file, after the end of the precompiled
2429 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002430 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002431 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002432 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002433 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002434
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002435 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002436 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002437 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002438 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002439 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002440 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
David Blaikieea4395e2017-01-06 19:49:01 +00002441 PCHContainerOps, Inv, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002442 }
2443 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002444 }
2445
2446 // If the main file has been overridden due to the use of a preamble,
2447 // make that override happen and introduce the preamble.
2448 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002449 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2450 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002451 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2452 PreprocessorOpts.PrecompiledPreambleBytes.second
2453 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002454 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002455 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002456
2457 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002458 } else {
2459 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2460 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002461 }
2462
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002463 // Disable the preprocessing record if modules are not enabled.
2464 if (!Clang->getLangOpts().Modules)
2465 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002466
2467 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002468 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002469 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002470 Act->Execute();
2471 Act->EndSourceFile();
2472 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002473}
Douglas Gregore9386682010-08-13 05:36:37 +00002474
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002475bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002476 if (HadModuleLoaderFatalFailure)
2477 return true;
2478
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002479 // Write to a temporary file and later rename it to the actual file, to avoid
2480 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002481 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002482 TempPath = File;
2483 TempPath += "-%%%%%%%%";
2484 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002485 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002486 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002487
Douglas Gregore9386682010-08-13 05:36:37 +00002488 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2489 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002490 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002491
2492 serialize(Out);
2493 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002494 if (Out.has_error()) {
2495 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002496 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002497 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002498
Yaron Keren92e1b622015-03-18 10:17:07 +00002499 if (llvm::sys::fs::rename(TempPath, File)) {
2500 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002501 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002502 }
2503
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002504 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002505}
2506
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002507static bool serializeUnit(ASTWriter &Writer,
2508 SmallVectorImpl<char> &Buffer,
2509 Sema &S,
2510 bool hasErrors,
2511 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002512 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002513
2514 // Write the generated bitstream to "Out".
2515 if (!Buffer.empty())
2516 OS.write(Buffer.data(), Buffer.size());
2517
2518 return false;
2519}
2520
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002521bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002522 // For serialization we are lenient if the errors were only warn-as-error kind.
2523 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002524
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002525 if (WriterData)
2526 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2527 getSema(), hasErrors, OS);
2528
Daniel Dunbar9a963862012-02-29 20:31:23 +00002529 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002530 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002531 MemoryBufferCache PCMCache;
2532 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002533 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002534}
Douglas Gregor925296b2011-07-19 16:10:42 +00002535
2536typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2537
Douglas Gregor925296b2011-07-19 16:10:42 +00002538void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002539 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002540 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002541 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002542 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002543 // Map the standalone diagnostic into the new source manager. We also need to
2544 // remap all the locations to the new view. This includes the diag location,
2545 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002546 // FIXME: There should be a cleaner way to do this.
2547
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002548 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002549 Result.reserve(Diags.size());
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002550 const FileEntry *PreviousFE = nullptr;
2551 FileID FID;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002552 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002553 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002554 if (SD.Filename.empty())
2555 continue;
2556 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2557 if (!FE)
2558 continue;
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002559 if (FE != PreviousFE) {
2560 FID = SrcMgr.translateFile(FE);
2561 PreviousFE = FE;
2562 }
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002563 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2564 if (FileLoc.isInvalid())
2565 continue;
2566 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002567 FullSourceLoc Loc(L, SrcMgr);
2568
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002569 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002570 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002571 for (const auto &Range : SD.Ranges) {
2572 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2573 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002574 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002575 }
2576
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002577 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002578 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002579 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002580 FixIts.push_back(FixItHint());
2581 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002582 FH.CodeToInsert = FixIt.CodeToInsert;
2583 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2584 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002585 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002586 }
2587
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002588 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2589 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002590 }
2591 Result.swap(Out);
2592}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002593
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002594void ASTUnit::addFileLevelDecl(Decl *D) {
2595 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002596
2597 // We only care about local declarations.
2598 if (D->isFromASTFile())
2599 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002600
2601 SourceManager &SM = *SourceMgr;
2602 SourceLocation Loc = D->getLocation();
2603 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2604 return;
2605
2606 // We only keep track of the file-level declarations of each file.
2607 if (!D->getLexicalDeclContext()->isFileContext())
2608 return;
2609
2610 SourceLocation FileLoc = SM.getFileLoc(Loc);
2611 assert(SM.isLocalSourceLocation(FileLoc));
2612 FileID FID;
2613 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002614 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002615 if (FID.isInvalid())
2616 return;
2617
2618 LocDeclsTy *&Decls = FileDecls[FID];
2619 if (!Decls)
2620 Decls = new LocDeclsTy();
2621
2622 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2623
2624 if (Decls->empty() || Decls->back().first <= Offset) {
2625 Decls->push_back(LocDecl);
2626 return;
2627 }
2628
Benjamin Kramer45025c02013-08-24 13:22:59 +00002629 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2630 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002631
2632 Decls->insert(I, LocDecl);
2633}
2634
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002635void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2636 SmallVectorImpl<Decl *> &Decls) {
2637 if (File.isInvalid())
2638 return;
2639
2640 if (SourceMgr->isLoadedFileID(File)) {
2641 assert(Ctx->getExternalSource() && "No external source!");
2642 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2643 Decls);
2644 }
2645
2646 FileDeclsTy::iterator I = FileDecls.find(File);
2647 if (I == FileDecls.end())
2648 return;
2649
2650 LocDeclsTy &LocDecls = *I->second;
2651 if (LocDecls.empty())
2652 return;
2653
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002654 LocDeclsTy::iterator BeginIt =
2655 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002656 std::make_pair(Offset, (Decl *)nullptr),
2657 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002658 if (BeginIt != LocDecls.begin())
2659 --BeginIt;
2660
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002661 // If we are pointing at a top-level decl inside an objc container, we need
2662 // to backtrack until we find it otherwise we will fail to report that the
2663 // region overlaps with an objc container.
2664 while (BeginIt != LocDecls.begin() &&
2665 BeginIt->second->isTopLevelDeclInObjCContainer())
2666 --BeginIt;
2667
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002668 LocDeclsTy::iterator EndIt = std::upper_bound(
2669 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002670 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002671 if (EndIt != LocDecls.end())
2672 ++EndIt;
2673
2674 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2675 Decls.push_back(DIt->second);
2676}
2677
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002678SourceLocation ASTUnit::getLocation(const FileEntry *File,
2679 unsigned Line, unsigned Col) const {
2680 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002681 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002682 return SM.getMacroArgExpandedLocation(Loc);
2683}
2684
2685SourceLocation ASTUnit::getLocation(const FileEntry *File,
2686 unsigned Offset) const {
2687 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002688 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002689 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2690}
2691
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002692/// \brief If \arg Loc is a loaded location from the preamble, returns
2693/// the corresponding local location of the main file, otherwise it returns
2694/// \arg Loc.
2695SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2696 FileID PreambleID;
2697 if (SourceMgr)
2698 PreambleID = SourceMgr->getPreambleFileID();
2699
2700 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2701 return Loc;
2702
2703 unsigned Offs;
2704 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2705 SourceLocation FileLoc
2706 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2707 return FileLoc.getLocWithOffset(Offs);
2708 }
2709
2710 return Loc;
2711}
2712
2713/// \brief If \arg Loc is a local location of the main file but inside the
2714/// preamble chunk, returns the corresponding loaded location from the
2715/// preamble, otherwise it returns \arg Loc.
2716SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2717 FileID PreambleID;
2718 if (SourceMgr)
2719 PreambleID = SourceMgr->getPreambleFileID();
2720
2721 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2722 return Loc;
2723
2724 unsigned Offs;
2725 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2726 Offs < Preamble.size()) {
2727 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2728 return FileLoc.getLocWithOffset(Offs);
2729 }
2730
2731 return Loc;
2732}
2733
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002734bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2735 FileID FID;
2736 if (SourceMgr)
2737 FID = SourceMgr->getPreambleFileID();
2738
2739 if (Loc.isInvalid() || FID.isInvalid())
2740 return false;
2741
2742 return SourceMgr->isInFileID(Loc, FID);
2743}
2744
2745bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2746 FileID FID;
2747 if (SourceMgr)
2748 FID = SourceMgr->getMainFileID();
2749
2750 if (Loc.isInvalid() || FID.isInvalid())
2751 return false;
2752
2753 return SourceMgr->isInFileID(Loc, FID);
2754}
2755
2756SourceLocation ASTUnit::getEndOfPreambleFileID() {
2757 FileID FID;
2758 if (SourceMgr)
2759 FID = SourceMgr->getPreambleFileID();
2760
2761 if (FID.isInvalid())
2762 return SourceLocation();
2763
2764 return SourceMgr->getLocForEndOfFile(FID);
2765}
2766
2767SourceLocation ASTUnit::getStartOfMainFileID() {
2768 FileID FID;
2769 if (SourceMgr)
2770 FID = SourceMgr->getMainFileID();
2771
2772 if (FID.isInvalid())
2773 return SourceLocation();
2774
2775 return SourceMgr->getLocForStartOfFile(FID);
2776}
2777
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002778llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002779ASTUnit::getLocalPreprocessingEntities() const {
2780 if (isMainFileAST()) {
2781 serialization::ModuleFile &
2782 Mod = Reader->getModuleManager().getPrimaryModule();
2783 return Reader->getModulePreprocessedEntities(Mod);
2784 }
2785
2786 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002787 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002788
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002789 return llvm::make_range(PreprocessingRecord::iterator(),
2790 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002791}
2792
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002793bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002794 if (isMainFileAST()) {
2795 serialization::ModuleFile &
2796 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002797 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2798 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002799 return false;
2800 }
2801
2802 return true;
2803 }
2804
2805 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2806 TLEnd = top_level_end();
2807 TL != TLEnd; ++TL) {
2808 if (!Fn(context, *TL))
2809 return false;
2810 }
2811
2812 return true;
2813}
2814
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002815const FileEntry *ASTUnit::getPCHFile() {
2816 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002817 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002818
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002819 serialization::ModuleFile *Mod = nullptr;
2820 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2821 switch (M.Kind) {
2822 case serialization::MK_ImplicitModule:
2823 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002824 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002825 return true; // skip dependencies.
2826 case serialization::MK_PCH:
2827 Mod = &M;
2828 return true; // found it.
2829 case serialization::MK_Preamble:
2830 return false; // look in dependencies.
2831 case serialization::MK_MainFile:
2832 return false; // look in dependencies.
2833 }
2834
2835 return true;
2836 });
2837 if (Mod)
2838 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002839
Craig Topper49a27902014-05-22 04:46:25 +00002840 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002841}
2842
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002843bool ASTUnit::isModuleFile() {
Richard Smithbbcc9f02016-08-26 00:14:38 +00002844 return isMainFileAST() && ASTFileLangOpts.isCompilingModule();
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002845}
2846
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002847void ASTUnit::PreambleData::countLines() const {
2848 NumLines = 0;
2849 if (empty())
2850 return;
2851
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002852 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2853
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002854 if (Buffer.back() != '\n')
2855 ++NumLines;
2856}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002857
2858#ifndef NDEBUG
2859ASTUnit::ConcurrencyState::ConcurrencyState() {
2860 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2861}
2862
2863ASTUnit::ConcurrencyState::~ConcurrencyState() {
2864 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2865}
2866
2867void ASTUnit::ConcurrencyState::start() {
2868 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2869 assert(acquired && "Concurrent access to ASTUnit!");
2870}
2871
2872void ASTUnit::ConcurrencyState::finish() {
2873 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2874}
2875
2876#else // NDEBUG
2877
Hans Wennborgdcfba332015-10-06 23:40:43 +00002878ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002879ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002880void ASTUnit::ConcurrencyState::start() {}
2881void ASTUnit::ConcurrencyState::finish() {}
2882
Hans Wennborgdcfba332015-10-06 23:40:43 +00002883#endif // NDEBUG