blob: b6a35c8cd3ad0cca3da99011a29b2ec13a6d2640 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Serialization/ASTReader.h"
33#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000034#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000035#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000037#include "llvm/Support/Atomic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000039#include "llvm/Support/FileSystem.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000048#include <cstdlib>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000049#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor213f18b2010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek1872b312011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
Rafael Espindolab804cb32013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek1872b312011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolab804cb32013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek1872b312011-10-27 17:55:18 +000090 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000107
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 M.erase(AU);
155 }
156}
157
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolab804cb32013-06-26 03:52:38 +0000168 llvm::sys::fs::remove(TemporaryFiles[I]);
169 TemporaryFiles.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +0000170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
Rafael Espindola85d28482013-06-26 04:02:37 +0000174 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek1872b312011-10-27 17:55:18 +0000175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
193 for (FileDeclsTy::iterator
194 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
195 delete I->second;
196 FileDecls.clear();
197}
198
Ted Kremenek1872b312011-10-27 17:55:18 +0000199void ASTUnit::CleanTemporaryFiles() {
200 getOnDiskData(this).CleanTemporaryFiles();
201}
202
Rafael Espindolab804cb32013-06-26 03:52:38 +0000203void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000204 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000205}
206
Douglas Gregoreababfb2010-08-04 05:53:38 +0000207/// \brief After failing to build a precompiled preamble (due to
208/// errors in the source that occurs in the preamble), the number of
209/// reparses during which we'll skip even trying to precompile the
210/// preamble.
211const unsigned DefaultPreambleRebuildInterval = 5;
212
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213/// \brief Tracks the number of ASTUnit objects that are currently active.
214///
215/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000216static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000217
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000218ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +0000219 : Reader(0), HadModuleLoaderFatalFailure(false),
220 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000221 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000222 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000223 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000224 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000225 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000226 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000227 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000228 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000229 CompletionCacheTopLevelHashValue(0),
230 PreambleTopLevelHashValue(0),
231 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000232 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000233 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000234 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000235 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
236 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000237}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000238
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000239ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000240 // If we loaded from an AST file, balance out the BeginSourceFile call.
241 if (MainFileIsAST && getDiagnostics().getClient()) {
242 getDiagnostics().getClient()->EndSourceFile();
243 }
244
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000245 clearFileLevelDecls();
246
Ted Kremenek1872b312011-10-27 17:55:18 +0000247 // Clean up the temporary files and the preamble file.
248 removeOnDiskEntry(this);
249
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000250 // Free the buffers associated with remapped files. We are required to
251 // perform this operation here because we explicitly request that the
252 // compiler instance *not* free these buffers for each invocation of the
253 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000254 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000255 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
256 for (PreprocessorOptions::remapped_file_buffer_iterator
257 FB = PPOpts.remapped_file_buffer_begin(),
258 FBEnd = PPOpts.remapped_file_buffer_end();
259 FB != FBEnd;
260 ++FB)
261 delete FB->second;
262 }
Douglas Gregor28233422010-07-27 14:52:07 +0000263
264 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000265 delete PreambleBuffer;
266
Douglas Gregor213f18b2010-10-28 15:44:59 +0000267 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000268
269 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000270 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000271 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
272 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000273}
274
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000275void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277/// \brief Determine the set of code-completion contexts in which this
278/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000279static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000280 const LangOptions &LangOpts,
281 bool &IsNestedNameSpecifier) {
282 IsNestedNameSpecifier = false;
283
Douglas Gregor8071e422010-08-15 06:18:01 +0000284 if (isa<UsingShadowDecl>(ND))
285 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
286 if (!ND)
287 return 0;
288
Richard Smith026b3582012-08-14 03:13:00 +0000289 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000290 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
291 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
292 // Types can appear in these contexts.
293 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000294 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
295 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
296 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
297 | (1LL << CodeCompletionContext::CCC_Statement)
298 | (1LL << CodeCompletionContext::CCC_Type)
299 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000300
301 // In C++, types can appear in expressions contexts (for functional casts).
302 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000303 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000304
305 // In Objective-C, message sends can send interfaces. In Objective-C++,
306 // all types are available due to functional casts.
307 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000308 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000309
310 // In Objective-C, you can only be a subclass of another Objective-C class
311 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000312 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000313
314 // Deal with tag names.
315 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000316 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000317
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000318 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000319 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000320 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000321 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000322 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000323 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000324 else
Richard Smith026b3582012-08-14 03:13:00 +0000325 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000326
Douglas Gregor8071e422010-08-15 06:18:01 +0000327 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000328 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000329 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
332 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000333 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
334 | (1LL << CodeCompletionContext::CCC_Expression)
335 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
336 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000337 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000338 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000339 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000340 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000341 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000342 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000343
344 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000345 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000346 }
347
348 return Contexts;
349}
350
Douglas Gregor87c08a52010-08-13 22:48:40 +0000351void ASTUnit::CacheCodeCompletionResults() {
352 if (!TheSema)
353 return;
354
Douglas Gregor213f18b2010-10-28 15:44:59 +0000355 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000356 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000357
358 // Clear out the previous results.
359 ClearCachedCompletionResults();
360
361 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000362 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000363 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000364 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000365 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000366 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000367 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000368
369 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000370 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
371
Douglas Gregor87c08a52010-08-13 22:48:40 +0000372 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
373 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000374 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000375 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000376 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000377 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000378 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000379 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000380 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000381 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000382 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000383 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000384 CachedResult.Priority = Results[I].Priority;
385 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000386 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000387
Douglas Gregorf5586f62010-08-16 18:08:11 +0000388 // Keep track of the type of this completion in an ASTContext-agnostic
389 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000390 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000391 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000392 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000393 CachedResult.Type = 0;
394 } else {
395 CanQualType CanUsageType
396 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
397 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
398
399 // Determine whether we have already seen this type. If so, we save
400 // ourselves the work of formatting the type string by using the
401 // temporary, CanQualType-based hash table to find the associated value.
402 unsigned &TypeValue = CompletionTypes[CanUsageType];
403 if (TypeValue == 0) {
404 TypeValue = CompletionTypes.size();
405 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
406 = TypeValue;
407 }
408
409 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000410 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000411
Douglas Gregor8071e422010-08-15 06:18:01 +0000412 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000413
414 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000415 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000416 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
417 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000418 uint64_t NNSContexts
419 = (1LL << CodeCompletionContext::CCC_TopLevel)
420 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
421 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
422 | (1LL << CodeCompletionContext::CCC_Statement)
423 | (1LL << CodeCompletionContext::CCC_Expression)
424 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
425 | (1LL << CodeCompletionContext::CCC_EnumTag)
426 | (1LL << CodeCompletionContext::CCC_UnionTag)
427 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
428 | (1LL << CodeCompletionContext::CCC_Type)
429 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
430 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000431
432 if (isa<NamespaceDecl>(Results[I].Declaration) ||
433 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000434 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000435
436 if (unsigned RemainingContexts
437 = NNSContexts & ~CachedResult.ShowInContexts) {
438 // If there any contexts where this completion can be a
439 // nested-name-specifier but isn't already an option, create a
440 // nested-name-specifier completion.
441 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000442 CachedResult.Completion
443 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000444 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000445 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000446 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000447 CachedResult.ShowInContexts = RemainingContexts;
448 CachedResult.Priority = CCP_NestedNameSpecifier;
449 CachedResult.TypeClass = STC_Void;
450 CachedResult.Type = 0;
451 CachedCompletionResults.push_back(CachedResult);
452 }
453 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000454 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000455 }
456
Douglas Gregor87c08a52010-08-13 22:48:40 +0000457 case Result::RK_Keyword:
458 case Result::RK_Pattern:
459 // Ignore keywords and patterns; we don't care, since they are so
460 // easily regenerated.
461 break;
462
463 case Result::RK_Macro: {
464 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000465 CachedResult.Completion
466 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000467 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000468 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000469 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000470 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000471 = (1LL << CodeCompletionContext::CCC_TopLevel)
472 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
473 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
474 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
475 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
476 | (1LL << CodeCompletionContext::CCC_Statement)
477 | (1LL << CodeCompletionContext::CCC_Expression)
478 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
479 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
480 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
481 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
482 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000483
Douglas Gregor87c08a52010-08-13 22:48:40 +0000484 CachedResult.Priority = Results[I].Priority;
485 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000486 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000487 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000488 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000489 CachedCompletionResults.push_back(CachedResult);
490 break;
491 }
492 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000493 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000494
495 // Save the current top-level hash value.
496 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000497}
498
499void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000500 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000501 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000502 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000503}
504
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505namespace {
506
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000507/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000508/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000509class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000510 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000512 LangOptions &LangOpt;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000513 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000514 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000517 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000518public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000519 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000520 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000521 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000522 unsigned &Counter)
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000523 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000524 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000525 Counter(Counter),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000526 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000528 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000529 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000530 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000531 return false;
532
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000533 LangOpt = LangOpts;
534 InitializedLanguage = true;
535
536 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000537 return false;
538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000540 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000541 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000542 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000543 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000544 return false;
545
Douglas Gregor57016dd2012-10-16 23:40:58 +0000546 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000547 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
548 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000549
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000550 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000551 return false;
552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000554 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000555 Counter = Value;
556 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000557
558private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000559 void updated() {
560 if (!Target || !InitializedLanguage)
561 return;
562
563 // Inform the target of the language options.
564 //
565 // FIXME: We shouldn't need to do this, the target should be immutable once
566 // created. This complexity should be lifted elsewhere.
567 Target->setForcedLangOptions(LangOpt);
568
569 // Initialize the preprocessor.
570 PP.Initialize(*Target);
571
572 // Initialize the ASTContext
573 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000574
575 // We didn't have access to the comment options when the ASTContext was
576 // constructed, so register them now.
577 Context.getCommentCommandTraits().registerCommentOptions(
578 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000579 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000580};
581
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000582 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000583class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000585 SourceManager *SourceMgr;
586
Douglas Gregora88084b2010-02-18 18:08:43 +0000587public:
David Blaikie26e7a902011-09-26 00:01:39 +0000588 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000590 : StoredDiags(StoredDiags), SourceMgr(0) { }
591
592 virtual void BeginSourceFile(const LangOptions &LangOpts,
593 const Preprocessor *PP = 0) {
594 if (PP)
595 SourceMgr = &PP->getSourceManager();
596 }
597
David Blaikied6471f72011-09-25 23:23:43 +0000598 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000599 const Diagnostic &Info);
Douglas Gregora88084b2010-02-18 18:08:43 +0000600};
601
602/// \brief RAII object that optionally captures diagnostics, if
603/// there is no diagnostic client to capture them already.
604class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000605 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000606 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000607 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000608
609public:
David Blaikied6471f72011-09-25 23:23:43 +0000610 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000611 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000612 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000613 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000614 if (RequestCapture || Diags.getClient() == 0) {
615 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000616 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000617 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000618 }
619
620 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000621 if (Diags.getClient() == &Client) {
622 Diags.takeClient();
623 Diags.setClient(PreviousClient);
624 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000625 }
626};
627
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000628} // anonymous namespace
629
David Blaikie26e7a902011-09-26 00:01:39 +0000630void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000631 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000632 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000633 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000634
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000635 // Only record the diagnostic if it's part of the source manager we know
636 // about. This effectively drops diagnostics from modules we're building.
637 // FIXME: In the long run, ee don't want to drop source managers from modules.
638 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
639 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000640}
641
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000642ASTMutationListener *ASTUnit::getASTMutationListener() {
643 if (WriterData)
644 return &WriterData->Writer;
645 return 0;
646}
647
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000648ASTDeserializationListener *ASTUnit::getDeserializationListener() {
649 if (WriterData)
650 return &WriterData->Writer;
651 return 0;
652}
653
Chris Lattner5f9e2722011-07-23 10:55:15 +0000654llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000655 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000656 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000657 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000658}
659
Douglas Gregore47be3e2010-11-11 00:39:14 +0000660/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000661void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000662 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000663 ASTUnit &AST, bool CaptureDiagnostics) {
664 if (!Diags.getPtr()) {
665 // No diagnostics engine was provided, so create our own diagnostics object
666 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000667 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000668 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000669 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000670 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000671 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000672 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000673 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000674 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000675 }
676}
677
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000678ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000679 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000680 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000681 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000682 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000683 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000684 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000685 bool AllowPCHWithCompilerErrors,
686 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000687 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000688
689 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000690 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
691 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000692 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
693 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000694 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000695
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000696 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000697
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000698 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000699 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000700 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000701 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000702 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000703 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000704 AST->getFileManager(),
705 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000706 AST->HSOpts = new HeaderSearchOptions();
707
708 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
709 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000710 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000711 AST->ASTFileLangOpts,
712 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000713
Douglas Gregor4db64a42010-01-23 00:14:00 +0000714 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000715 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
716 if (const llvm::MemoryBuffer *
717 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
718 // Create the file entry for the file that we're mapping from.
719 const FileEntry *FromFile
720 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
721 memBuf->getBufferSize(),
722 0);
723 if (!FromFile) {
724 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
725 << RemappedFiles[I].first;
726 delete memBuf;
727 continue;
728 }
729
730 // Override the contents of the "from" file with the contents of
731 // the "to" file.
732 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
733
734 } else {
735 const char *fname = fileOrBuf.get<const char *>();
736 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
737 if (!ToFile) {
738 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
739 << RemappedFiles[I].first << fname;
740 continue;
741 }
742
743 // Create the file entry for the file that we're mapping from.
744 const FileEntry *FromFile
745 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
746 ToFile->getSize(),
747 0);
748 if (!FromFile) {
749 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
750 << RemappedFiles[I].first;
751 delete memBuf;
752 continue;
753 }
754
755 // Override the contents of the "from" file with the contents of
756 // the "to" file.
757 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000758 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000759 }
760
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000761 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000763 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000764 unsigned Counter;
765
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000766 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000767
Douglas Gregor36a16492012-10-24 17:46:57 +0000768 AST->PP = new Preprocessor(new PreprocessorOptions(),
769 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000770 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
771 *AST,
772 /*IILookup=*/0,
773 /*OwnsHeaderSearch=*/false,
774 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000775 Preprocessor &PP = *AST->PP;
776
777 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
778 AST->getSourceManager(),
779 /*Target=*/0,
780 PP.getIdentifierTable(),
781 PP.getSelectorTable(),
782 PP.getBuiltinInfo(),
783 /* size_reserve = */0,
784 /*DelayInitialization=*/true);
785 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000786
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000787 bool disableValid = false;
788 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
789 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000790 Reader.reset(new ASTReader(PP, Context,
791 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000792 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000793 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000794
795 // Recover resources if we crash before exiting this method.
796 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
797 ReaderCleanup(Reader.get());
798
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000799 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000800 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000801 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000802 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000803
Douglas Gregor38295be2012-10-22 23:51:00 +0000804 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000805 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000806 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000807 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000809 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000810 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000811 case ASTReader::OutOfDate:
812 case ASTReader::VersionMismatch:
813 case ASTReader::ConfigurationMismatch:
814 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000815 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000816 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000817 }
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000819 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
820
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000821 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000823 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000824 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000825 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000826 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000827 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000828
829 // Unregister the cleanup for ASTReader. It will get cleaned up
830 // by the ASTUnit cleanup.
831 ReaderCleanup.unregister();
832
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000833 Context.setExternalSource(Source);
834
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000835 // Create an AST consumer, even though it isn't used.
836 AST->Consumer.reset(new ASTConsumer);
837
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000838 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000839 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
840 AST->TheSema->Initialize();
841 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000842 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000843
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000844 // Tell the diagnostic client that we have started a source file.
845 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
846
Mike Stump1eb44332009-09-09 15:08:12 +0000847 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000848}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000849
850namespace {
851
Douglas Gregor9b7db622011-02-16 18:16:54 +0000852/// \brief Preprocessor callback class that updates a hash value with the names
853/// of all macros that have been defined by the translation unit.
854class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
855 unsigned &Hash;
856
857public:
858 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
859
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000860 virtual void MacroDefined(const Token &MacroNameTok,
861 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000862 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
863 }
864};
865
866/// \brief Add the given declaration to the hash of all top-level entities.
867void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
868 if (!D)
869 return;
870
871 DeclContext *DC = D->getDeclContext();
872 if (!DC)
873 return;
874
875 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
876 return;
877
878 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
879 if (ND->getIdentifier())
880 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
881 else if (DeclarationName Name = ND->getDeclName()) {
882 std::string NameStr = Name.getAsString();
883 Hash = llvm::HashString(NameStr, Hash);
884 }
885 return;
Argyrios Kyrtzidis1f3ff6a2013-06-24 21:19:12 +0000886 }
887
888 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
889 if (Module *Mod = ImportD->getImportedModule()) {
890 std::string ModName = Mod->getFullModuleName();
891 Hash = llvm::HashString(ModName, Hash);
892 }
893 return;
894 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000895}
896
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000897class TopLevelDeclTrackerConsumer : public ASTConsumer {
898 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000899 unsigned &Hash;
900
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000901public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000902 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
903 : Unit(_Unit), Hash(Hash) {
904 Hash = 0;
905 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000906
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000907 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000908 if (!D)
909 return;
910
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000911 // FIXME: Currently ObjC method declarations are incorrectly being
912 // reported as top-level declarations, even though their DeclContext
913 // is the containing ObjC @interface/@implementation. This is a
914 // fundamental problem in the parser right now.
915 if (isa<ObjCMethodDecl>(D))
916 return;
917
918 AddTopLevelDeclarationToHash(D, Hash);
919 Unit.addTopLevelDecl(D);
920
921 handleFileLevelDecl(D);
922 }
923
924 void handleFileLevelDecl(Decl *D) {
925 Unit.addFileLevelDecl(D);
926 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
927 for (NamespaceDecl::decl_iterator
928 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
929 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000930 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000931 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000932
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000933 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000934 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
935 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000936 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000937 }
938
Sebastian Redl27372b42010-08-11 18:52:41 +0000939 // We're not interested in "interesting" decls.
940 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000941
942 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
943 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
944 handleTopLevelDecl(*it);
945 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000946
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000947 virtual ASTMutationListener *GetASTMutationListener() {
948 return Unit.getASTMutationListener();
949 }
950
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000951 virtual ASTDeserializationListener *GetASTDeserializationListener() {
952 return Unit.getDeserializationListener();
953 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000954};
955
956class TopLevelDeclTrackerAction : public ASTFrontendAction {
957public:
958 ASTUnit &Unit;
959
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000960 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000961 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000962 CI.getPreprocessor().addPPCallbacks(
963 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
964 return new TopLevelDeclTrackerConsumer(Unit,
965 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000966 }
967
968public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000969 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
970
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000971 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000972 virtual TranslationUnitKind getTranslationUnitKind() {
973 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000974 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000975};
976
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000977class PrecompilePreambleAction : public ASTFrontendAction {
978 ASTUnit &Unit;
979 bool HasEmittedPreamblePCH;
980
981public:
982 explicit PrecompilePreambleAction(ASTUnit &Unit)
983 : Unit(Unit), HasEmittedPreamblePCH(false) {}
984
985 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
986 StringRef InFile);
987 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
988 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
989 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
990
991 virtual bool hasCodeCompletionSupport() const { return false; }
992 virtual bool hasASTFileSupport() const { return false; }
993 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
994};
995
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000996class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000997 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000998 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000999 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001000 PrecompilePreambleAction *Action;
1001
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001002public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001003 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
1004 const Preprocessor &PP, StringRef isysroot,
1005 raw_ostream *Out)
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001006 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001007 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +00001008 Hash = 0;
1009 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001010
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001011 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001012 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
1013 Decl *D = *it;
1014 // FIXME: Currently ObjC method declarations are incorrectly being
1015 // reported as top-level declarations, even though their DeclContext
1016 // is the containing ObjC @interface/@implementation. This is a
1017 // fundamental problem in the parser right now.
1018 if (isa<ObjCMethodDecl>(D))
1019 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +00001020 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001021 TopLevelDecls.push_back(D);
1022 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001023 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001024 }
1025
1026 virtual void HandleTranslationUnit(ASTContext &Ctx) {
1027 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001028 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001029 // Translate the top-level declarations we captured during
1030 // parsing into declaration IDs in the precompiled
1031 // preamble. This will allow us to deserialize those top-level
1032 // declarations when requested.
Argyrios Kyrtzidis51e75ae2013-08-07 21:17:33 +00001033 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
1034 Decl *D = TopLevelDecls[I];
1035 // Invalid top-level decls may not have been serialized.
1036 if (D->isInvalidDecl())
1037 continue;
1038 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
1039 }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001040
1041 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001042 }
1043 }
1044};
1045
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001046}
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001047
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001048ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1049 StringRef InFile) {
1050 std::string Sysroot;
1051 std::string OutputFile;
1052 raw_ostream *OS = 0;
1053 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1054 OutputFile, OS))
1055 return 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001056
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001057 if (!CI.getFrontendOpts().RelocatablePCH)
1058 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +00001059
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001060 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1061 Unit.getCurrentTopLevelHashValue()));
1062 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1063 Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001064}
1065
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001066static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1067 return StoredDiag.getLocation().isValid();
1068}
1069
1070static void
1071checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001072 // Get rid of stored diagnostics except the ones from the driver which do not
1073 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001074 StoredDiags.erase(
1075 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1076 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001077}
1078
1079static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1080 StoredDiagnostics,
1081 SourceManager &SM) {
1082 // The stored diagnostic has the old source manager in it; update
1083 // the locations to refer into the new source manager. Since we've
1084 // been careful to make sure that the source manager's state
1085 // before and after are identical, so that we can reuse the source
1086 // location itself.
1087 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1088 if (StoredDiagnostics[I].getLocation().isValid()) {
1089 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1090 StoredDiagnostics[I].setLocation(Loc);
1091 }
1092 }
1093}
1094
Douglas Gregorabc563f2010-07-19 21:46:24 +00001095/// Parse the source file into a translation unit using the given compiler
1096/// invocation, replacing the current translation unit.
1097///
1098/// \returns True if a failure occurred that causes the ASTUnit not to
1099/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001100bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001101 delete SavedMainFileBuffer;
1102 SavedMainFileBuffer = 0;
1103
Ted Kremenek4f327862011-03-21 18:40:17 +00001104 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001105 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001106 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001107 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001108
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001109 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001110 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001111
1112 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001113 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1114 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001115
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001116 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001117 CCInvocation(new CompilerInvocation(*Invocation));
1118
1119 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001120 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001121
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001122 // Set up diagnostics, capturing any diagnostics that would
1123 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001124 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001125
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001126 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001127 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001128 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001129 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001130 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001131 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001132 }
1133
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001134 // Inform the target of the language options.
1135 //
1136 // FIXME: We shouldn't need to do this, the target should be immutable once
1137 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001138 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001139
Ted Kremenek03201fb2011-03-21 18:40:07 +00001140 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001141 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001142 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001143 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001144 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001145 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001146
Douglas Gregorabc563f2010-07-19 21:46:24 +00001147 // Configure the various subsystems.
1148 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001149 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001150 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001151 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001152 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1153 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001154 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001155 Ctx = 0;
1156 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001157 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001158
1159 // Clear out old caches and data.
1160 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001161 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001162 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001163
Douglas Gregorf128fed2010-08-20 00:02:33 +00001164 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001165 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001166 TopLevelDeclsInPreamble.clear();
1167 }
1168
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001169 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001170 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001171
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001172 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001173 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001174
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001175 // If the main file has been overridden due to the use of a preamble,
1176 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001177 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001178 if (OverrideMainBuffer) {
1179 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1180 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1181 PreprocessorOpts.PrecompiledPreambleBytes.second
1182 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001183 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001184 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001185
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001186 // The stored diagnostic has the old source manager in it; update
1187 // the locations to refer into the new source manager. Since we've
1188 // been careful to make sure that the source manager's state
1189 // before and after are identical, so that we can reuse the source
1190 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001191 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001192
1193 // Keep track of the override buffer;
1194 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001195 }
1196
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001197 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001198 new TopLevelDeclTrackerAction(*this));
1199
1200 // Recover resources if we crash before exiting this method.
1201 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1202 ActCleanup(Act.get());
1203
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001204 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001205 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001206
1207 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001208 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001209 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1210 getSourceManager(), PreambleDiagnostics,
1211 StoredDiagnostics);
1212 }
1213
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001214 if (!Act->Execute())
1215 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001216
1217 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001218
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001219 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001220
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001221 FailedParseDiagnostics.clear();
1222
Douglas Gregorabc563f2010-07-19 21:46:24 +00001223 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001224
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001225error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001226 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001227 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001228 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001229 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001230 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001231
1232 // Keep the ownership of the data in the ASTUnit because the client may
1233 // want to see the diagnostics.
1234 transferASTDataFromCompilerInstance(*Clang);
1235 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001236 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001237 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001238 return true;
1239}
1240
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241/// \brief Simple function to retrieve a path for a preamble precompiled header.
1242static std::string GetPreamblePCHPath() {
Douglas Gregor424668c2010-09-11 18:05:19 +00001243 // FIXME: This is a hack so that we can override the preamble file during
1244 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindola85d28482013-06-26 04:02:37 +00001245 // are not necessarily cleaned up.
Douglas Gregor424668c2010-09-11 18:05:19 +00001246 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1247 if (TmpFile)
1248 return TmpFile;
Rafael Espindola85d28482013-06-26 04:02:37 +00001249
1250 SmallString<128> Path;
Rafael Espindola1ec4a862013-07-05 20:00:06 +00001251 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindola85d28482013-06-26 04:02:37 +00001252
1253 return Path.str();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001254}
1255
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001256/// \brief Compute the preamble for the main file, providing the source buffer
1257/// that corresponds to the main file along with a pair (bytes, start-of-line)
1258/// that describes the preamble.
1259std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001260ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1261 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001262 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001263 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001264 CreatedBuffer = false;
1265
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 // Try to determine if the main file has been remapped, either from the
1267 // command line (to another file) or directly through the compiler invocation
1268 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001269 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindola105b2072013-06-18 19:40:07 +00001270 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola44888352013-07-29 21:26:52 +00001271 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001272 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001273 // Check whether there is a file-file remapping of the main file
1274 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001275 M = PreprocessorOpts.remapped_file_begin(),
1276 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001277 M != E;
1278 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001279 std::string MPath(M->first);
Rafael Espindola44888352013-07-29 21:26:52 +00001280 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001281 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001282 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001284 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001285 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001286 CreatedBuffer = false;
1287 }
1288
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001289 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001290 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001291 return std::make_pair((llvm::MemoryBuffer*)0,
1292 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001293 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001294 }
1295 }
1296 }
1297
1298 // Check whether there is a file-buffer remapping. It supercedes the
1299 // file-file remapping.
1300 for (PreprocessorOptions::remapped_file_buffer_iterator
1301 M = PreprocessorOpts.remapped_file_buffer_begin(),
1302 E = PreprocessorOpts.remapped_file_buffer_end();
1303 M != E;
1304 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001305 std::string MPath(M->first);
Rafael Espindola44888352013-07-29 21:26:52 +00001306 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001307 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001308 if (MainFileID == MID) {
1309 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001310 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001311 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001312 CreatedBuffer = false;
1313 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001314
Douglas Gregor175c4a92010-07-23 23:58:40 +00001315 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001316 }
1317 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001318 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001319 }
1320
1321 // If the main source file was not remapped, load it now.
1322 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001323 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001324 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001325 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001326
1327 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001328 }
1329
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001330 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001331 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001332 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001333}
1334
Douglas Gregor754f3492010-07-24 00:38:13 +00001335static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001336 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001337 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001338 llvm::MemoryBuffer *Result
1339 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1340 memcpy(const_cast<char*>(Result->getBufferStart()),
1341 Old->getBufferStart(), Old->getBufferSize());
1342 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001343 ' ', NewSize - Old->getBufferSize() - 1);
1344 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001345
Douglas Gregor754f3492010-07-24 00:38:13 +00001346 return Result;
1347}
1348
Douglas Gregor175c4a92010-07-23 23:58:40 +00001349/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1350/// the source file.
1351///
1352/// This routine will compute the preamble of the main source file. If a
1353/// non-trivial preamble is found, it will precompile that preamble into a
1354/// precompiled header so that the precompiled preamble can be used to reduce
1355/// reparsing time. If a precompiled preamble has already been constructed,
1356/// this routine will determine if it is still valid and, if so, avoid
1357/// rebuilding the precompiled preamble.
1358///
Douglas Gregordf95a132010-08-09 20:45:32 +00001359/// \param AllowRebuild When true (the default), this routine is
1360/// allowed to rebuild the precompiled preamble if it is found to be
1361/// out-of-date.
1362///
1363/// \param MaxLines When non-zero, the maximum number of lines that
1364/// can occur within the preamble.
1365///
Douglas Gregor754f3492010-07-24 00:38:13 +00001366/// \returns If the precompiled preamble can be used, returns a newly-allocated
1367/// buffer that should be used in place of the main file when doing so.
1368/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001369llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001370 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001371 bool AllowRebuild,
1372 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001373
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001374 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001375 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1376 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001377 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001378 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001379
1380 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001381 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001382 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001383
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001384 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001385 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001386 if (CreatedPreambleBuffer)
1387 OwnedPreambleBuffer.reset(NewPreamble.first);
1388
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001389 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001390 // We couldn't find a preamble in the main source. Clear out the current
1391 // preamble, if we have one. It's obviously no good any more.
1392 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001393 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001394
1395 // The next time we actually see a preamble, precompile it.
1396 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001397 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001398 }
1399
1400 if (!Preamble.empty()) {
1401 // We've previously computed a preamble. Check whether we have the same
1402 // preamble now that we did before, and that there's enough space in
1403 // the main-file buffer within the precompiled preamble to fit the
1404 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001405 if (Preamble.size() == NewPreamble.second.first &&
1406 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001407 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001408 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001409 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001410 // The preamble has not changed. We may be able to re-use the precompiled
1411 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001412
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001413 // Check that none of the files used by the preamble have changed.
1414 bool AnyFileChanged = false;
1415
1416 // First, make a record of those files that have been overridden via
1417 // remapping or unsaved_files.
1418 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1419 for (PreprocessorOptions::remapped_file_iterator
1420 R = PreprocessorOpts.remapped_file_begin(),
1421 REnd = PreprocessorOpts.remapped_file_end();
1422 !AnyFileChanged && R != REnd;
1423 ++R) {
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001424 llvm::sys::fs::file_status Status;
1425 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001426 // If we can't stat the file we're remapping to, assume that something
1427 // horrible happened.
1428 AnyFileChanged = true;
1429 break;
1430 }
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001431
1432 OverriddenFiles[R->first] = std::make_pair(
1433 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001434 }
1435 for (PreprocessorOptions::remapped_file_buffer_iterator
1436 R = PreprocessorOpts.remapped_file_buffer_begin(),
1437 REnd = PreprocessorOpts.remapped_file_buffer_end();
1438 !AnyFileChanged && R != REnd;
1439 ++R) {
1440 // FIXME: Should we actually compare the contents of file->buffer
1441 // remappings?
1442 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1443 0);
1444 }
1445
1446 // Check whether anything has changed.
1447 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1448 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1449 !AnyFileChanged && F != FEnd;
1450 ++F) {
1451 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1452 = OverriddenFiles.find(F->first());
1453 if (Overridden != OverriddenFiles.end()) {
1454 // This file was remapped; check whether the newly-mapped file
1455 // matches up with the previous mapping.
1456 if (Overridden->second != F->second)
1457 AnyFileChanged = true;
1458 continue;
1459 }
1460
1461 // The file was not remapped; check whether it has changed on disk.
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001462 llvm::sys::fs::file_status Status;
1463 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001464 // If we can't stat the file, assume that something horrible happened.
1465 AnyFileChanged = true;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001466 } else if (Status.getSize() != uint64_t(F->second.first) ||
1467 Status.getLastModificationTime().toEpochTime() !=
1468 uint64_t(F->second.second))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001469 AnyFileChanged = true;
1470 }
1471
1472 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001473 // Okay! We can re-use the precompiled preamble.
1474
1475 // Set the state of the diagnostic object to mimic its state
1476 // after parsing the preamble.
1477 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001478 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001479 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001480 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001481
1482 // Create a version of the main file buffer that is padded to
1483 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001484 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001485 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001486 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001487 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001488 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001489
1490 // If we aren't allowed to rebuild the precompiled preamble, just
1491 // return now.
1492 if (!AllowRebuild)
1493 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001494
Douglas Gregor175c4a92010-07-23 23:58:40 +00001495 // We can't reuse the previously-computed preamble. Build a new one.
1496 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001497 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001498 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001499 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001500 } else if (!AllowRebuild) {
1501 // We aren't allowed to rebuild the precompiled preamble; just
1502 // return now.
1503 return 0;
1504 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001505
1506 // If the preamble rebuild counter > 1, it's because we previously
1507 // failed to build a preamble and we're not yet ready to try
1508 // again. Decrement the counter and return a failure.
1509 if (PreambleRebuildCounter > 1) {
1510 --PreambleRebuildCounter;
1511 return 0;
1512 }
1513
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001514 // Create a temporary file for the precompiled preamble. In rare
1515 // circumstances, this can fail.
1516 std::string PreamblePCHPath = GetPreamblePCHPath();
1517 if (PreamblePCHPath.empty()) {
1518 // Try again next time.
1519 PreambleRebuildCounter = 1;
1520 return 0;
1521 }
1522
Douglas Gregor175c4a92010-07-23 23:58:40 +00001523 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001524 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001525 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001526
1527 // Create a new buffer that stores the preamble. The buffer also contains
1528 // extra space for the original contents of the file (which will be present
1529 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001530 // grows.
1531 PreambleReservedSize = NewPreamble.first->getBufferSize();
1532 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001533 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001534 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001535 PreambleReservedSize *= 2;
1536
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001537 // Save the preamble text for later; we'll need to compare against it for
1538 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001539 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001540 Preamble.assign(FileMgr->getFile(MainFilename),
1541 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001542 NewPreamble.first->getBufferStart()
1543 + NewPreamble.second.first);
1544 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1545
Douglas Gregor671947b2010-08-19 01:33:06 +00001546 delete PreambleBuffer;
1547 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001548 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001549 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001550 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001551 NewPreamble.first->getBufferStart(), Preamble.size());
1552 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001553 ' ', PreambleReservedSize - Preamble.size() - 1);
1554 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001555
Douglas Gregor44c181a2010-07-23 00:33:23 +00001556 // Remap the main source file to the preamble buffer.
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001557 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1558 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1559
Douglas Gregor44c181a2010-07-23 00:33:23 +00001560 // Tell the compiler invocation to generate a temporary precompiled header.
1561 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001562 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001563 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001564 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1565 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001566
1567 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001568 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001569
1570 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001571 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1572 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001573
Douglas Gregor01b6e312011-07-01 18:22:13 +00001574 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001575 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001576
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001577 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001578 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579
1580 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001581 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001582 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001583 if (!Clang->hasTarget()) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001584 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001585 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001586 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001587 PreprocessorOpts.eraseRemappedFile(
1588 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001589 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590 }
1591
1592 // Inform the target of the language options.
1593 //
1594 // FIXME: We shouldn't need to do this, the target should be immutable once
1595 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001596 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001597
Ted Kremenek03201fb2011-03-21 18:40:07 +00001598 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001599 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001600 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001601 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001602 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001603 "IR inputs not support here!");
1604
1605 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001606 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001607 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001608 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001609 TopLevelDecls.clear();
1610 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001611
1612 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001613 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001614
1615 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001616 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001617 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001618
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001619 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001620 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001621 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001622 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001623 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001624 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001625 PreprocessorOpts.eraseRemappedFile(
1626 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001627 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001628 }
1629
1630 Act->Execute();
1631 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001632
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001633 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001634 // The preamble PCH failed (e.g. there was a module loading fatal error),
1635 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001636 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindola21b18242013-06-26 04:26:38 +00001637 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001638 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001639 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001640 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001641 PreprocessorOpts.eraseRemappedFile(
1642 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001643 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001644 }
1645
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001646 // Transfer any diagnostics generated when parsing the preamble into the set
1647 // of preamble diagnostics.
1648 PreambleDiagnostics.clear();
1649 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001650 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001651 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001652
Douglas Gregor175c4a92010-07-23 23:58:40 +00001653 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001654 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001655 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001656
1657 // Keep track of all of the files that the source manager knows about,
1658 // so we can verify whether they have changed or not.
1659 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001660 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001661 const llvm::MemoryBuffer *MainFileBuffer
1662 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1663 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1664 FEnd = SourceMgr.fileinfo_end();
1665 F != FEnd;
1666 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001667 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001668 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1669 continue;
1670
1671 FilesInPreamble[File->getName()]
1672 = std::make_pair(F->second->getSize(), File->getModificationTime());
1673 }
1674
Douglas Gregoreababfb2010-08-04 05:53:38 +00001675 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001676 PreprocessorOpts.eraseRemappedFile(
1677 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001678
1679 // If the hash of top-level entities differs from the hash of the top-level
1680 // entities the last time we rebuilt the preamble, clear out the completion
1681 // cache.
1682 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1683 CompletionCacheTopLevelHashValue = 0;
1684 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1685 }
1686
Douglas Gregor754f3492010-07-24 00:38:13 +00001687 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001688 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001689 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001690}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001691
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001692void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1693 std::vector<Decl *> Resolved;
1694 Resolved.reserve(TopLevelDeclsInPreamble.size());
1695 ExternalASTSource &Source = *getASTContext().getExternalSource();
1696 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1697 // Resolve the declaration ID to an actual declaration, possibly
1698 // deserializing the declaration in the process.
1699 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1700 if (D)
1701 Resolved.push_back(D);
1702 }
1703 TopLevelDeclsInPreamble.clear();
1704 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1705}
1706
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001707void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1708 // Steal the created target, context, and preprocessor.
1709 TheSema.reset(CI.takeSema());
1710 Consumer.reset(CI.takeASTConsumer());
1711 Ctx = &CI.getASTContext();
1712 PP = &CI.getPreprocessor();
1713 CI.setSourceManager(0);
1714 CI.setFileManager(0);
1715 Target = &CI.getTarget();
1716 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001717 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001718}
1719
Chris Lattner5f9e2722011-07-23 10:55:15 +00001720StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001721 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1722 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1723 if (Input.isFile())
1724 return Input.getFile();
1725 else
1726 return Input.getBuffer()->getBufferIdentifier();
1727 }
1728
1729 if (SourceMgr) {
1730 if (const FileEntry *
1731 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1732 return FE->getName();
1733 }
1734
1735 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001736}
1737
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001738StringRef ASTUnit::getASTFileName() const {
1739 if (!isMainFileAST())
1740 return StringRef();
1741
1742 serialization::ModuleFile &
1743 Mod = Reader->getModuleManager().getPrimaryModule();
1744 return Mod.FileName;
1745}
1746
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001747ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001748 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001749 bool CaptureDiagnostics,
1750 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001751 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001752 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001753 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001754 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001755 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001756 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001757 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001758 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1759 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1760 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001761
1762 return AST.take();
1763}
1764
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001766 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001767 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001768 ASTUnit *Unit,
1769 bool Persistent,
1770 StringRef ResourceFilesPath,
1771 bool OnlyLocalDecls,
1772 bool CaptureDiagnostics,
1773 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001774 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001775 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001776 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001777 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001778 assert(CI && "A CompilerInvocation is required");
1779
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001780 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001781 ASTUnit *AST = Unit;
1782 if (!AST) {
1783 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001784 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001785 AST = OwnAST.get();
1786 }
1787
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001788 if (!ResourceFilesPath.empty()) {
1789 // Override the resources path.
1790 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1791 }
1792 AST->OnlyLocalDecls = OnlyLocalDecls;
1793 AST->CaptureDiagnostics = CaptureDiagnostics;
1794 if (PrecompilePreamble)
1795 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001796 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001797 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001798 AST->IncludeBriefCommentsInCodeCompletion
1799 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001800
1801 // Recover resources if we crash before exiting this method.
1802 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001803 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001804 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1805 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001806 DiagCleanup(Diags.getPtr());
1807
1808 // We'll manage file buffers ourselves.
1809 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1810 CI->getFrontendOpts().DisableFree = false;
1811 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1812
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001814 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001815
1816 // Recover resources if we crash before exiting this method.
1817 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1818 CICleanup(Clang.get());
1819
1820 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001821 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001822
1823 // Set up diagnostics, capturing any diagnostics that would
1824 // otherwise be dropped.
1825 Clang->setDiagnostics(&AST->getDiagnostics());
1826
1827 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001828 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001829 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001830 if (!Clang->hasTarget())
1831 return 0;
1832
1833 // Inform the target of the language options.
1834 //
1835 // FIXME: We shouldn't need to do this, the target should be immutable once
1836 // created. This complexity should be lifted elsewhere.
1837 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1838
1839 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1840 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001841 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001842 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001843 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001844 "IR inputs not supported here!");
1845
1846 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001847 AST->TheSema.reset();
1848 AST->Ctx = 0;
1849 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001850 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001851
1852 // Create a file manager object to provide access to and cache the filesystem.
1853 Clang->setFileManager(&AST->getFileManager());
1854
1855 // Create the source manager.
1856 Clang->setSourceManager(&AST->getSourceManager());
1857
1858 ASTFrontendAction *Act = Action;
1859
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001860 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001861 if (!Act) {
1862 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1863 Act = TrackerAct.get();
1864 }
1865
1866 // Recover resources if we crash before exiting this method.
1867 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1868 ActCleanup(TrackerAct.get());
1869
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001870 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1871 AST->transferASTDataFromCompilerInstance(*Clang);
1872 if (OwnAST && ErrAST)
1873 ErrAST->swap(OwnAST);
1874
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001875 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001876 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001877
1878 if (Persistent && !TrackerAct) {
1879 Clang->getPreprocessor().addPPCallbacks(
1880 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1881 std::vector<ASTConsumer*> Consumers;
1882 if (Clang->hasASTConsumer())
1883 Consumers.push_back(Clang->takeASTConsumer());
1884 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1885 AST->getCurrentTopLevelHashValue()));
1886 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1887 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001888 if (!Act->Execute()) {
1889 AST->transferASTDataFromCompilerInstance(*Clang);
1890 if (OwnAST && ErrAST)
1891 ErrAST->swap(OwnAST);
1892
1893 return 0;
1894 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001895
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001896 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001897 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001898
1899 Act->EndSourceFile();
1900
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001901 if (OwnAST)
1902 return OwnAST.take();
1903 else
1904 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001905}
1906
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001907bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1908 if (!Invocation)
1909 return true;
1910
1911 // We'll manage file buffers ourselves.
1912 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1913 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001914 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001915
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001916 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001917 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001918 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001919 OverrideMainBuffer
1920 = getMainBufferWithPrecompiledPreamble(*Invocation);
1921 }
1922
Douglas Gregor213f18b2010-10-28 15:44:59 +00001923 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001924 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001925
Ted Kremenek25a11e12011-03-22 01:15:24 +00001926 // Recover resources if we crash before exiting this method.
1927 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1928 MemBufferCleanup(OverrideMainBuffer);
1929
Douglas Gregor213f18b2010-10-28 15:44:59 +00001930 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001931}
1932
Douglas Gregorabc563f2010-07-19 21:46:24 +00001933ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001934 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001935 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001936 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001937 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001938 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001939 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001940 bool IncludeBriefCommentsInCodeCompletion,
1941 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001942 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001943 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001944 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001945 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001946 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001947 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001948 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001949 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001950 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001951 AST->IncludeBriefCommentsInCodeCompletion
1952 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001953 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001954 AST->FileSystemOpts = CI->getFileSystemOpts();
1955 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001956 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001957
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001958 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001959 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1960 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001961 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1962 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001963 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001964
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001965 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001966}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001967
1968ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1969 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001970 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001971 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001972 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001973 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001974 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001975 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001976 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001977 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001978 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001979 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001980 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001981 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001982 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001983 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001984 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001985 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001986 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001987 // No diagnostics engine was provided, so create our own diagnostics object
1988 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001989 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001990 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001991
Chris Lattner5f9e2722011-07-23 10:55:15 +00001992 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001993
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001994 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001995
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001996 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001997
Douglas Gregore47be3e2010-11-11 00:39:14 +00001998 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001999 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00002000
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00002001 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00002002 llvm::makeArrayRef(ArgBegin, ArgEnd),
2003 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00002004 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00002005 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002006 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00002007
Douglas Gregor4db64a42010-01-23 00:14:00 +00002008 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002009 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2010 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2011 if (const llvm::MemoryBuffer *
2012 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2013 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2014 } else {
2015 const char *fname = fileOrBuf.get<const char *>();
2016 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2017 }
2018 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002019 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2020 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2021 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002022
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002023 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002024 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002025
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002026 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2027
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002028 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002029 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002030 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002031 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002032 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002033 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002034 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002035 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002036 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002037 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002038 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002039 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002040 AST->IncludeBriefCommentsInCodeCompletion
2041 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002042 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002043 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002044 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002045 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002046 if (ForSerialization)
2047 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002048 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002049
2050 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002051 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2052 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002053
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002054 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2055 // Some error occurred, if caller wants to examine diagnostics, pass it the
2056 // ASTUnit.
2057 if (ErrAST) {
2058 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2059 ErrAST->swap(AST);
2060 }
2061 return 0;
2062 }
2063
2064 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002065}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002066
2067bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002068 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002069 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002070
2071 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002072
Douglas Gregor213f18b2010-10-28 15:44:59 +00002073 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002074 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002075
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002076 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002077 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2078 for (PreprocessorOptions::remapped_file_buffer_iterator
2079 R = PPOpts.remapped_file_buffer_begin(),
2080 REnd = PPOpts.remapped_file_buffer_end();
2081 R != REnd;
2082 ++R) {
2083 delete R->second;
2084 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002085 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002086 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2087 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2088 if (const llvm::MemoryBuffer *
2089 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2090 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2091 memBuf);
2092 } else {
2093 const char *fname = fileOrBuf.get<const char *>();
2094 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2095 fname);
2096 }
2097 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002098
Douglas Gregoreababfb2010-08-04 05:53:38 +00002099 // If we have a preamble file lying around, or if we might try to
2100 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002101 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002102 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002103 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002104
Douglas Gregorabc563f2010-07-19 21:46:24 +00002105 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002106 getDiagnostics().Reset();
2107 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002108 if (OverrideMainBuffer)
2109 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002110
Douglas Gregor175c4a92010-07-23 23:58:40 +00002111 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002112 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002113
2114 // If we're caching global code-completion results, and the top-level
2115 // declarations have changed, clear out the code-completion cache.
2116 if (!Result && ShouldCacheCodeCompletionResults &&
2117 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2118 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002119
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002120 // We now need to clear out the completion info related to this translation
2121 // unit; it'll be recreated if necessary.
2122 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002123
Douglas Gregor175c4a92010-07-23 23:58:40 +00002124 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002125}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002126
Douglas Gregor87c08a52010-08-13 22:48:40 +00002127//----------------------------------------------------------------------------//
2128// Code completion
2129//----------------------------------------------------------------------------//
2130
2131namespace {
2132 /// \brief Code completion consumer that combines the cached code-completion
2133 /// results from an ASTUnit with the code-completion results provided to it,
2134 /// then passes the result on to
2135 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002136 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002137 ASTUnit &AST;
2138 CodeCompleteConsumer &Next;
2139
2140 public:
2141 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002142 const CodeCompleteOptions &CodeCompleteOpts)
2143 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2144 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002145 {
2146 // Compute the set of contexts in which we will look when we don't have
2147 // any information about the specific context.
2148 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002149 = (1LL << CodeCompletionContext::CCC_TopLevel)
2150 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2151 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2152 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2153 | (1LL << CodeCompletionContext::CCC_Statement)
2154 | (1LL << CodeCompletionContext::CCC_Expression)
2155 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2156 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2157 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2158 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2159 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2160 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2161 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002162
David Blaikie4e4d0842012-03-11 07:00:24 +00002163 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002164 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2165 | (1LL << CodeCompletionContext::CCC_UnionTag)
2166 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002167 }
2168
2169 virtual void ProcessCodeCompleteResults(Sema &S,
2170 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002171 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002172 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002173
2174 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2175 OverloadCandidate *Candidates,
2176 unsigned NumCandidates) {
2177 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2178 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002179
Douglas Gregordae68752011-02-01 22:57:45 +00002180 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002181 return Next.getAllocator();
2182 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002183
2184 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2185 return Next.getCodeCompletionTUInfo();
2186 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002187 };
2188}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002189
Douglas Gregor5f808c22010-08-16 21:18:39 +00002190/// \brief Helper function that computes which global names are hidden by the
2191/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002192static void CalculateHiddenNames(const CodeCompletionContext &Context,
2193 CodeCompletionResult *Results,
2194 unsigned NumResults,
2195 ASTContext &Ctx,
2196 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002197 bool OnlyTagNames = false;
2198 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002199 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002200 case CodeCompletionContext::CCC_TopLevel:
2201 case CodeCompletionContext::CCC_ObjCInterface:
2202 case CodeCompletionContext::CCC_ObjCImplementation:
2203 case CodeCompletionContext::CCC_ObjCIvarList:
2204 case CodeCompletionContext::CCC_ClassStructUnion:
2205 case CodeCompletionContext::CCC_Statement:
2206 case CodeCompletionContext::CCC_Expression:
2207 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002208 case CodeCompletionContext::CCC_DotMemberAccess:
2209 case CodeCompletionContext::CCC_ArrowMemberAccess:
2210 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002211 case CodeCompletionContext::CCC_Namespace:
2212 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002213 case CodeCompletionContext::CCC_Name:
2214 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002215 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002216 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002217 break;
2218
2219 case CodeCompletionContext::CCC_EnumTag:
2220 case CodeCompletionContext::CCC_UnionTag:
2221 case CodeCompletionContext::CCC_ClassOrStructTag:
2222 OnlyTagNames = true;
2223 break;
2224
2225 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002226 case CodeCompletionContext::CCC_MacroName:
2227 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002228 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002229 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002230 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002231 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002232 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002233 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002234 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002235 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2236 case CodeCompletionContext::CCC_ObjCClassMessage:
2237 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002238 // We're looking for nothing, or we're looking for names that cannot
2239 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002240 return;
2241 }
2242
John McCall0a2c5e22010-08-25 06:19:51 +00002243 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002244 for (unsigned I = 0; I != NumResults; ++I) {
2245 if (Results[I].Kind != Result::RK_Declaration)
2246 continue;
2247
2248 unsigned IDNS
2249 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2250
2251 bool Hiding = false;
2252 if (OnlyTagNames)
2253 Hiding = (IDNS & Decl::IDNS_Tag);
2254 else {
2255 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002256 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2257 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002258 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002259 HiddenIDNS |= Decl::IDNS_Tag;
2260 Hiding = (IDNS & HiddenIDNS);
2261 }
2262
2263 if (!Hiding)
2264 continue;
2265
2266 DeclarationName Name = Results[I].Declaration->getDeclName();
2267 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2268 HiddenNames.insert(Identifier->getName());
2269 else
2270 HiddenNames.insert(Name.getAsString());
2271 }
2272}
2273
2274
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002275void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2276 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002277 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002278 unsigned NumResults) {
2279 // Merge the results we were given with the results we cached.
2280 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002281 uint64_t InContexts =
2282 Context.getKind() == CodeCompletionContext::CCC_Recovery
2283 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002284 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002285 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002286 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002287 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002288 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002289 C = AST.cached_completion_begin(),
2290 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002291 C != CEnd; ++C) {
2292 // If the context we are in matches any of the contexts we are
2293 // interested in, we'll add this result.
2294 if ((C->ShowInContexts & InContexts) == 0)
2295 continue;
2296
2297 // If we haven't added any results previously, do so now.
2298 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002299 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2300 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2302 AddedResult = true;
2303 }
2304
Douglas Gregor5f808c22010-08-16 21:18:39 +00002305 // Determine whether this global completion result is hidden by a local
2306 // completion result. If so, skip it.
2307 if (C->Kind != CXCursor_MacroDefinition &&
2308 HiddenNames.count(C->Completion->getTypedText()))
2309 continue;
2310
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002311 // Adjust priority based on similar type classes.
2312 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002313 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002314 if (!Context.getPreferredType().isNull()) {
2315 if (C->Kind == CXCursor_MacroDefinition) {
2316 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002317 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002318 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002319 } else if (C->Type) {
2320 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002321 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002322 Context.getPreferredType().getUnqualifiedType());
2323 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2324 if (ExpectedSTC == C->TypeClass) {
2325 // We know this type is similar; check for an exact match.
2326 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002327 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002328 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002329 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002330 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2331 Priority /= CCF_ExactTypeMatch;
2332 else
2333 Priority /= CCF_SimilarTypeMatch;
2334 }
2335 }
2336 }
2337
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002338 // Adjust the completion string, if required.
2339 if (C->Kind == CXCursor_MacroDefinition &&
2340 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2341 // Create a new code-completion string that just contains the
2342 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002343 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2344 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002345 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002346 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002347 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002348 }
2349
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002350 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002351 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002352 }
2353
2354 // If we did not add any cached completion results, just forward the
2355 // results we were given to the next consumer.
2356 if (!AddedResult) {
2357 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2358 return;
2359 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002360
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002361 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2362 AllResults.size());
2363}
2364
2365
2366
Chris Lattner5f9e2722011-07-23 10:55:15 +00002367void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368 RemappedFile *RemappedFiles,
2369 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002370 bool IncludeMacros,
2371 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002372 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002373 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002374 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002376 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2377 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002378 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002379 return;
2380
Douglas Gregor213f18b2010-10-28 15:44:59 +00002381 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002382 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002383 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002384
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002385 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002386 CCInvocation(new CompilerInvocation(*Invocation));
2387
2388 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002389 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002390 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002391
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002392 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2393 CachedCompletionResults.empty();
2394 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2395 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2396 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2397
2398 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2399
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002400 FrontendOpts.CodeCompletionAt.FileName = File;
2401 FrontendOpts.CodeCompletionAt.Line = Line;
2402 FrontendOpts.CodeCompletionAt.Column = Column;
2403
2404 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002405 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002406
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002407 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002408
2409 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002410 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2411 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002412
Ted Kremenek4f327862011-03-21 18:40:17 +00002413 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002414 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002415
2416 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002417 Clang->setDiagnostics(&Diag);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002419 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002420 StoredDiagnostics);
Manuel Klimekf0c06a32013-07-18 14:23:12 +00002421 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002422
2423 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002424 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002425 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002426 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002427 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002428 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002429 }
2430
2431 // Inform the target of the language options.
2432 //
2433 // FIXME: We shouldn't need to do this, the target should be immutable once
2434 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002435 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002436
Ted Kremenek03201fb2011-03-21 18:40:07 +00002437 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002438 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002439 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002440 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002441 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002442 "IR inputs not support here!");
2443
2444
2445 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002446 Clang->setFileManager(&FileMgr);
2447 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002448
2449 // Remap files.
2450 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002451 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002452 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002453 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2454 if (const llvm::MemoryBuffer *
2455 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2456 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2457 OwnedBuffers.push_back(memBuf);
2458 } else {
2459 const char *fname = fileOrBuf.get<const char *>();
2460 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2461 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002462 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002463
Douglas Gregor87c08a52010-08-13 22:48:40 +00002464 // Use the code completion consumer we were given, but adding any cached
2465 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002466 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002467 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002468 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002469
Douglas Gregordf95a132010-08-09 20:45:32 +00002470 // If we have a precompiled preamble, try to use it. We only allow
2471 // the use of the precompiled preamble if we're if the completion
2472 // point is within the main file, after the end of the precompiled
2473 // preamble.
2474 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002475 if (!getPreambleFile(this).empty()) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002476 std::string CompleteFilePath(File);
Rafael Espindola44888352013-07-29 21:26:52 +00002477 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindola105b2072013-06-18 19:40:07 +00002478
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002479 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002480 std::string MainPath(OriginalSourceFile);
Rafael Espindola44888352013-07-29 21:26:52 +00002481 llvm::sys::fs::UniqueID MainID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002482 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002483 if (CompleteFileID == MainID && Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002484 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002485 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002486 Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002487 }
2488 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002489 }
2490
2491 // If the main file has been overridden due to the use of a preamble,
2492 // make that override happen and introduce the preamble.
2493 if (OverrideMainBuffer) {
2494 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2495 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2496 PreprocessorOpts.PrecompiledPreambleBytes.second
2497 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002498 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002499 PreprocessorOpts.DisablePCHValidation = true;
2500
Douglas Gregor2283d792010-08-20 00:59:43 +00002501 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002502 } else {
2503 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2504 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002505 }
2506
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002507 // Disable the preprocessing record if modules are not enabled.
2508 if (!Clang->getLangOpts().Modules)
2509 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002510
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002511 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002512 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002513 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002514 Act->Execute();
2515 Act->EndSourceFile();
2516 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002517}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002518
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002519bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002520 if (HadModuleLoaderFatalFailure)
2521 return true;
2522
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002523 // Write to a temporary file and later rename it to the actual file, to avoid
2524 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002525 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002526 TempPath = File;
2527 TempPath += "-%%%%%%%%";
2528 int fd;
Rafael Espindola70e7aec2013-07-05 21:13:58 +00002529 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002530 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002531
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002532 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2533 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002534 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002535
2536 serialize(Out);
2537 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002538 if (Out.has_error()) {
2539 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002540 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002541 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002542
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002543 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002544 bool exists;
2545 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002546 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002547 }
2548
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002549 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002550}
2551
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002552static bool serializeUnit(ASTWriter &Writer,
2553 SmallVectorImpl<char> &Buffer,
2554 Sema &S,
2555 bool hasErrors,
2556 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002557 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002558
2559 // Write the generated bitstream to "Out".
2560 if (!Buffer.empty())
2561 OS.write(Buffer.data(), Buffer.size());
2562
2563 return false;
2564}
2565
Chris Lattner5f9e2722011-07-23 10:55:15 +00002566bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002567 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002568
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002569 if (WriterData)
2570 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2571 getSema(), hasErrors, OS);
2572
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002573 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002574 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002575 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002576 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002577}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002578
2579typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2580
2581static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2582 unsigned Raw = L.getRawEncoding();
2583 const unsigned MacroBit = 1U << 31;
2584 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2585 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2586}
2587
2588void ASTUnit::TranslateStoredDiagnostics(
2589 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002590 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002591 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592 const SmallVectorImpl<StoredDiagnostic> &Diags,
2593 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002594 // The stored diagnostic has the old source manager in it; update
2595 // the locations to refer into the new source manager. We also need to remap
2596 // all the locations to the new view. This includes the diag location, any
2597 // associated source ranges, and the source ranges of associated fix-its.
2598 // FIXME: There should be a cleaner way to do this.
2599
Chris Lattner5f9e2722011-07-23 10:55:15 +00002600 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002601 Result.reserve(Diags.size());
2602 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002603 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002604 assert(Mod && "Don't have preamble module");
2605 SLocRemap &Remap = Mod->SLocRemap;
2606 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2607 // Rebuild the StoredDiagnostic.
2608 const StoredDiagnostic &SD = Diags[I];
2609 SourceLocation L = SD.getLocation();
2610 TranslateSLoc(L, Remap);
2611 FullSourceLoc Loc(L, SrcMgr);
2612
Chris Lattner5f9e2722011-07-23 10:55:15 +00002613 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002614 Ranges.reserve(SD.range_size());
2615 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2616 E = SD.range_end();
2617 I != E; ++I) {
2618 SourceLocation BL = I->getBegin();
2619 TranslateSLoc(BL, Remap);
2620 SourceLocation EL = I->getEnd();
2621 TranslateSLoc(EL, Remap);
2622 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2623 }
2624
Chris Lattner5f9e2722011-07-23 10:55:15 +00002625 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002626 FixIts.reserve(SD.fixit_size());
2627 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2628 E = SD.fixit_end();
2629 I != E; ++I) {
2630 FixIts.push_back(FixItHint());
2631 FixItHint &FH = FixIts.back();
2632 FH.CodeToInsert = I->CodeToInsert;
2633 SourceLocation BL = I->RemoveRange.getBegin();
2634 TranslateSLoc(BL, Remap);
2635 SourceLocation EL = I->RemoveRange.getEnd();
2636 TranslateSLoc(EL, Remap);
2637 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2638 I->RemoveRange.isTokenRange());
2639 }
2640
2641 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2642 SD.getMessage(), Loc, Ranges, FixIts));
2643 }
2644 Result.swap(Out);
2645}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002646
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002647void ASTUnit::addFileLevelDecl(Decl *D) {
2648 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002649
2650 // We only care about local declarations.
2651 if (D->isFromASTFile())
2652 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002653
2654 SourceManager &SM = *SourceMgr;
2655 SourceLocation Loc = D->getLocation();
2656 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2657 return;
2658
2659 // We only keep track of the file-level declarations of each file.
2660 if (!D->getLexicalDeclContext()->isFileContext())
2661 return;
2662
2663 SourceLocation FileLoc = SM.getFileLoc(Loc);
2664 assert(SM.isLocalSourceLocation(FileLoc));
2665 FileID FID;
2666 unsigned Offset;
2667 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2668 if (FID.isInvalid())
2669 return;
2670
2671 LocDeclsTy *&Decls = FileDecls[FID];
2672 if (!Decls)
2673 Decls = new LocDeclsTy();
2674
2675 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2676
2677 if (Decls->empty() || Decls->back().first <= Offset) {
2678 Decls->push_back(LocDecl);
2679 return;
2680 }
2681
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002682 LocDeclsTy::iterator I =
2683 std::upper_bound(Decls->begin(), Decls->end(), LocDecl, less_first());
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002684
2685 Decls->insert(I, LocDecl);
2686}
2687
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002688void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2689 SmallVectorImpl<Decl *> &Decls) {
2690 if (File.isInvalid())
2691 return;
2692
2693 if (SourceMgr->isLoadedFileID(File)) {
2694 assert(Ctx->getExternalSource() && "No external source!");
2695 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2696 Decls);
2697 }
2698
2699 FileDeclsTy::iterator I = FileDecls.find(File);
2700 if (I == FileDecls.end())
2701 return;
2702
2703 LocDeclsTy &LocDecls = *I->second;
2704 if (LocDecls.empty())
2705 return;
2706
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002707 LocDeclsTy::iterator BeginIt =
2708 std::lower_bound(LocDecls.begin(), LocDecls.end(),
2709 std::make_pair(Offset, (Decl *)0), less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002710 if (BeginIt != LocDecls.begin())
2711 --BeginIt;
2712
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002713 // If we are pointing at a top-level decl inside an objc container, we need
2714 // to backtrack until we find it otherwise we will fail to report that the
2715 // region overlaps with an objc container.
2716 while (BeginIt != LocDecls.begin() &&
2717 BeginIt->second->isTopLevelDeclInObjCContainer())
2718 --BeginIt;
2719
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002720 LocDeclsTy::iterator EndIt = std::upper_bound(
2721 LocDecls.begin(), LocDecls.end(),
2722 std::make_pair(Offset + Length, (Decl *)0), less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002723 if (EndIt != LocDecls.end())
2724 ++EndIt;
2725
2726 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2727 Decls.push_back(DIt->second);
2728}
2729
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002730SourceLocation ASTUnit::getLocation(const FileEntry *File,
2731 unsigned Line, unsigned Col) const {
2732 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002733 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002734 return SM.getMacroArgExpandedLocation(Loc);
2735}
2736
2737SourceLocation ASTUnit::getLocation(const FileEntry *File,
2738 unsigned Offset) const {
2739 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002740 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002741 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2742}
2743
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002744/// \brief If \arg Loc is a loaded location from the preamble, returns
2745/// the corresponding local location of the main file, otherwise it returns
2746/// \arg Loc.
2747SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2748 FileID PreambleID;
2749 if (SourceMgr)
2750 PreambleID = SourceMgr->getPreambleFileID();
2751
2752 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2753 return Loc;
2754
2755 unsigned Offs;
2756 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2757 SourceLocation FileLoc
2758 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2759 return FileLoc.getLocWithOffset(Offs);
2760 }
2761
2762 return Loc;
2763}
2764
2765/// \brief If \arg Loc is a local location of the main file but inside the
2766/// preamble chunk, returns the corresponding loaded location from the
2767/// preamble, otherwise it returns \arg Loc.
2768SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2769 FileID PreambleID;
2770 if (SourceMgr)
2771 PreambleID = SourceMgr->getPreambleFileID();
2772
2773 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2774 return Loc;
2775
2776 unsigned Offs;
2777 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2778 Offs < Preamble.size()) {
2779 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2780 return FileLoc.getLocWithOffset(Offs);
2781 }
2782
2783 return Loc;
2784}
2785
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002786bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2787 FileID FID;
2788 if (SourceMgr)
2789 FID = SourceMgr->getPreambleFileID();
2790
2791 if (Loc.isInvalid() || FID.isInvalid())
2792 return false;
2793
2794 return SourceMgr->isInFileID(Loc, FID);
2795}
2796
2797bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2798 FileID FID;
2799 if (SourceMgr)
2800 FID = SourceMgr->getMainFileID();
2801
2802 if (Loc.isInvalid() || FID.isInvalid())
2803 return false;
2804
2805 return SourceMgr->isInFileID(Loc, FID);
2806}
2807
2808SourceLocation ASTUnit::getEndOfPreambleFileID() {
2809 FileID FID;
2810 if (SourceMgr)
2811 FID = SourceMgr->getPreambleFileID();
2812
2813 if (FID.isInvalid())
2814 return SourceLocation();
2815
2816 return SourceMgr->getLocForEndOfFile(FID);
2817}
2818
2819SourceLocation ASTUnit::getStartOfMainFileID() {
2820 FileID FID;
2821 if (SourceMgr)
2822 FID = SourceMgr->getMainFileID();
2823
2824 if (FID.isInvalid())
2825 return SourceLocation();
2826
2827 return SourceMgr->getLocForStartOfFile(FID);
2828}
2829
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002830std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2831ASTUnit::getLocalPreprocessingEntities() const {
2832 if (isMainFileAST()) {
2833 serialization::ModuleFile &
2834 Mod = Reader->getModuleManager().getPrimaryModule();
2835 return Reader->getModulePreprocessedEntities(Mod);
2836 }
2837
2838 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2839 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2840
2841 return std::make_pair(PreprocessingRecord::iterator(),
2842 PreprocessingRecord::iterator());
2843}
2844
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002845bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002846 if (isMainFileAST()) {
2847 serialization::ModuleFile &
2848 Mod = Reader->getModuleManager().getPrimaryModule();
2849 ASTReader::ModuleDeclIterator MDI, MDE;
2850 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2851 for (; MDI != MDE; ++MDI) {
2852 if (!Fn(context, *MDI))
2853 return false;
2854 }
2855
2856 return true;
2857 }
2858
2859 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2860 TLEnd = top_level_end();
2861 TL != TLEnd; ++TL) {
2862 if (!Fn(context, *TL))
2863 return false;
2864 }
2865
2866 return true;
2867}
2868
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002869namespace {
2870struct PCHLocatorInfo {
2871 serialization::ModuleFile *Mod;
2872 PCHLocatorInfo() : Mod(0) {}
2873};
2874}
2875
2876static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2877 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2878 switch (M.Kind) {
2879 case serialization::MK_Module:
2880 return true; // skip dependencies.
2881 case serialization::MK_PCH:
2882 Info.Mod = &M;
2883 return true; // found it.
2884 case serialization::MK_Preamble:
2885 return false; // look in dependencies.
2886 case serialization::MK_MainFile:
2887 return false; // look in dependencies.
2888 }
2889
2890 return true;
2891}
2892
2893const FileEntry *ASTUnit::getPCHFile() {
2894 if (!Reader)
2895 return 0;
2896
2897 PCHLocatorInfo Info;
2898 Reader->getModuleManager().visit(PCHLocator, &Info);
2899 if (Info.Mod)
2900 return Info.Mod->File;
2901
2902 return 0;
2903}
2904
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002905bool ASTUnit::isModuleFile() {
2906 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2907}
2908
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002909void ASTUnit::PreambleData::countLines() const {
2910 NumLines = 0;
2911 if (empty())
2912 return;
2913
2914 for (std::vector<char>::const_iterator
2915 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2916 if (*I == '\n')
2917 ++NumLines;
2918 }
2919 if (Buffer.back() != '\n')
2920 ++NumLines;
2921}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002922
2923#ifndef NDEBUG
2924ASTUnit::ConcurrencyState::ConcurrencyState() {
2925 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2926}
2927
2928ASTUnit::ConcurrencyState::~ConcurrencyState() {
2929 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2930}
2931
2932void ASTUnit::ConcurrencyState::start() {
2933 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2934 assert(acquired && "Concurrent access to ASTUnit!");
2935}
2936
2937void ASTUnit::ConcurrencyState::finish() {
2938 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2939}
2940
2941#else // NDEBUG
2942
2943ASTUnit::ConcurrencyState::ConcurrencyState() {}
2944ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2945void ASTUnit::ConcurrencyState::start() {}
2946void ASTUnit::ConcurrencyState::finish() {}
2947
2948#endif