blob: f05d7225465c17aaa4d7dbd040893db5014123ad [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
86 /// \brief Temporary files that should be removed when the ASTUnit is
87 /// destroyed.
88 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
89
90 /// \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)
168 TemporaryFiles[I].eraseFromDisk();
169 TemporaryFiles.clear();
170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::Path(PreambleFile).eraseFromDisk();
175 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
203void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
204 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 Kyrtzidis62ba9f62011-11-01 17:14:15 +0000219 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000220 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000221 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000222 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000223 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000224 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000225 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000226 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000227 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000228 CompletionCacheTopLevelHashValue(0),
229 PreambleTopLevelHashValue(0),
230 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000231 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000232 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000233 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000234 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
235 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000236}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000237
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000238ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000239 // If we loaded from an AST file, balance out the BeginSourceFile call.
240 if (MainFileIsAST && getDiagnostics().getClient()) {
241 getDiagnostics().getClient()->EndSourceFile();
242 }
243
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000244 clearFileLevelDecls();
245
Ted Kremenek1872b312011-10-27 17:55:18 +0000246 // Clean up the temporary files and the preamble file.
247 removeOnDiskEntry(this);
248
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 // Free the buffers associated with remapped files. We are required to
250 // perform this operation here because we explicitly request that the
251 // compiler instance *not* free these buffers for each invocation of the
252 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000253 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000254 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
255 for (PreprocessorOptions::remapped_file_buffer_iterator
256 FB = PPOpts.remapped_file_buffer_begin(),
257 FBEnd = PPOpts.remapped_file_buffer_end();
258 FB != FBEnd;
259 ++FB)
260 delete FB->second;
261 }
Douglas Gregor28233422010-07-27 14:52:07 +0000262
263 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000264 delete PreambleBuffer;
265
Douglas Gregor213f18b2010-10-28 15:44:59 +0000266 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000267
268 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000269 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000270 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
271 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000272}
273
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000274void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
275
Douglas Gregor8071e422010-08-15 06:18:01 +0000276/// \brief Determine the set of code-completion contexts in which this
277/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000278static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000279 const LangOptions &LangOpts,
280 bool &IsNestedNameSpecifier) {
281 IsNestedNameSpecifier = false;
282
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<UsingShadowDecl>(ND))
284 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
285 if (!ND)
286 return 0;
287
Richard Smith026b3582012-08-14 03:13:00 +0000288 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000289 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
290 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
291 // Types can appear in these contexts.
292 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
294 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
295 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
296 | (1LL << CodeCompletionContext::CCC_Statement)
297 | (1LL << CodeCompletionContext::CCC_Type)
298 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000299
300 // In C++, types can appear in expressions contexts (for functional casts).
301 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000303
304 // In Objective-C, message sends can send interfaces. In Objective-C++,
305 // all types are available due to functional casts.
306 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000307 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000308
309 // In Objective-C, you can only be a subclass of another Objective-C class
310 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000312
313 // Deal with tag names.
314 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000315 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000316
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000318 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000320 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000322 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 else
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000325
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000327 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000328 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
331 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
333 | (1LL << CodeCompletionContext::CCC_Expression)
334 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
335 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000337 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000338 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000342
343 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000344 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000345 }
346
347 return Contexts;
348}
349
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350void ASTUnit::CacheCodeCompletionResults() {
351 if (!TheSema)
352 return;
353
Douglas Gregor213f18b2010-10-28 15:44:59 +0000354 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000355 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356
357 // Clear out the previous results.
358 ClearCachedCompletionResults();
359
360 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000361 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000362 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000363 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000364 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000365 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000366 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000367
368 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
370
Douglas Gregor87c08a52010-08-13 22:48:40 +0000371 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
372 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000374 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000376 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000377 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000378 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000379 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000380 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000381 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000382 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000383 CachedResult.Priority = Results[I].Priority;
384 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000385 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000386
Douglas Gregorf5586f62010-08-16 18:08:11 +0000387 // Keep track of the type of this completion in an ASTContext-agnostic
388 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000389 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000390 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392 CachedResult.Type = 0;
393 } else {
394 CanQualType CanUsageType
395 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
396 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
397
398 // Determine whether we have already seen this type. If so, we save
399 // ourselves the work of formatting the type string by using the
400 // temporary, CanQualType-based hash table to find the associated value.
401 unsigned &TypeValue = CompletionTypes[CanUsageType];
402 if (TypeValue == 0) {
403 TypeValue = CompletionTypes.size();
404 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
405 = TypeValue;
406 }
407
408 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000409 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000410
Douglas Gregor8071e422010-08-15 06:18:01 +0000411 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000412
413 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000414 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
416 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000417 uint64_t NNSContexts
418 = (1LL << CodeCompletionContext::CCC_TopLevel)
419 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
420 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
421 | (1LL << CodeCompletionContext::CCC_Statement)
422 | (1LL << CodeCompletionContext::CCC_Expression)
423 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
424 | (1LL << CodeCompletionContext::CCC_EnumTag)
425 | (1LL << CodeCompletionContext::CCC_UnionTag)
426 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
427 | (1LL << CodeCompletionContext::CCC_Type)
428 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
429 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000430
431 if (isa<NamespaceDecl>(Results[I].Declaration) ||
432 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000433 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000434
435 if (unsigned RemainingContexts
436 = NNSContexts & ~CachedResult.ShowInContexts) {
437 // If there any contexts where this completion can be a
438 // nested-name-specifier but isn't already an option, create a
439 // nested-name-specifier completion.
440 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000441 CachedResult.Completion
442 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000443 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000444 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000445 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000446 CachedResult.ShowInContexts = RemainingContexts;
447 CachedResult.Priority = CCP_NestedNameSpecifier;
448 CachedResult.TypeClass = STC_Void;
449 CachedResult.Type = 0;
450 CachedCompletionResults.push_back(CachedResult);
451 }
452 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000453 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000454 }
455
Douglas Gregor87c08a52010-08-13 22:48:40 +0000456 case Result::RK_Keyword:
457 case Result::RK_Pattern:
458 // Ignore keywords and patterns; we don't care, since they are so
459 // easily regenerated.
460 break;
461
462 case Result::RK_Macro: {
463 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000464 CachedResult.Completion
465 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000466 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000467 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000468 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000469 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000470 = (1LL << CodeCompletionContext::CCC_TopLevel)
471 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
472 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
473 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
474 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
475 | (1LL << CodeCompletionContext::CCC_Statement)
476 | (1LL << CodeCompletionContext::CCC_Expression)
477 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
478 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
479 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
480 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
481 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000482
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedResult.Priority = Results[I].Priority;
484 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000485 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000486 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000487 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000488 CachedCompletionResults.push_back(CachedResult);
489 break;
490 }
491 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000493
494 // Save the current top-level hash value.
495 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000496}
497
498void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000499 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000500 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000501 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000502}
503
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504namespace {
505
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000506/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000508class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 LangOptions &LangOpt;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000512 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000513 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000516 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000517public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000518 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000519 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000520 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000521 unsigned &Counter)
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000522 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000523 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000524 Counter(Counter),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000525 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000527 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000528 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000529 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000530 return false;
531
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000532 LangOpt = LangOpts;
533 InitializedLanguage = true;
534
535 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000536 return false;
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000539 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000540 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000541 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000542 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000543 return false;
544
Douglas Gregor57016dd2012-10-16 23:40:58 +0000545 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000546 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
547 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000548
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000549 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000550 return false;
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000553 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 Counter = Value;
555 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000556
557private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000558 void updated() {
559 if (!Target || !InitializedLanguage)
560 return;
561
562 // Inform the target of the language options.
563 //
564 // FIXME: We shouldn't need to do this, the target should be immutable once
565 // created. This complexity should be lifted elsewhere.
566 Target->setForcedLangOptions(LangOpt);
567
568 // Initialize the preprocessor.
569 PP.Initialize(*Target);
570
571 // Initialize the ASTContext
572 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000573
574 // We didn't have access to the comment options when the ASTContext was
575 // constructed, so register them now.
576 Context.getCommentCommandTraits().registerCommentOptions(
577 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000578 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000579};
580
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000581 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000582class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000584 SourceManager *SourceMgr;
585
Douglas Gregora88084b2010-02-18 18:08:43 +0000586public:
David Blaikie26e7a902011-09-26 00:01:39 +0000587 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000588 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000589 : StoredDiags(StoredDiags), SourceMgr(0) { }
590
591 virtual void BeginSourceFile(const LangOptions &LangOpts,
592 const Preprocessor *PP = 0) {
593 if (PP)
594 SourceMgr = &PP->getSourceManager();
595 }
596
David Blaikied6471f72011-09-25 23:23:43 +0000597 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000598 const Diagnostic &Info);
Douglas Gregora88084b2010-02-18 18:08:43 +0000599};
600
601/// \brief RAII object that optionally captures diagnostics, if
602/// there is no diagnostic client to capture them already.
603class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000604 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000605 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000606 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000607
608public:
David Blaikied6471f72011-09-25 23:23:43 +0000609 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000610 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000611 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000612 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000613 if (RequestCapture || Diags.getClient() == 0) {
614 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000615 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000616 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000617 }
618
619 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000620 if (Diags.getClient() == &Client) {
621 Diags.takeClient();
622 Diags.setClient(PreviousClient);
623 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000624 }
625};
626
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000627} // anonymous namespace
628
David Blaikie26e7a902011-09-26 00:01:39 +0000629void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000630 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000631 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000632 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000633
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000634 // Only record the diagnostic if it's part of the source manager we know
635 // about. This effectively drops diagnostics from modules we're building.
636 // FIXME: In the long run, ee don't want to drop source managers from modules.
637 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
638 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000639}
640
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000641ASTDeserializationListener *ASTUnit::getDeserializationListener() {
642 if (WriterData)
643 return &WriterData->Writer;
644 return 0;
645}
646
Chris Lattner5f9e2722011-07-23 10:55:15 +0000647llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000648 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000649 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000650 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000651}
652
Douglas Gregore47be3e2010-11-11 00:39:14 +0000653/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000654void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000655 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000656 ASTUnit &AST, bool CaptureDiagnostics) {
657 if (!Diags.getPtr()) {
658 // No diagnostics engine was provided, so create our own diagnostics object
659 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000660 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000661 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000662 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000663 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000664 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000665 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000666 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000667 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000668 }
669}
670
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000671ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000672 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000673 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000674 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000675 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000676 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000677 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000678 bool AllowPCHWithCompilerErrors,
679 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000680 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000681
682 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000683 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
684 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000685 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
686 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000687 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000688
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000689 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000690
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000691 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000692 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000693 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000694 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000695 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000696 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000697 AST->getFileManager(),
698 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000699 AST->HSOpts = new HeaderSearchOptions();
700
701 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
702 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000703 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000704 AST->ASTFileLangOpts,
705 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000706
Douglas Gregor4db64a42010-01-23 00:14:00 +0000707 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000708 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
709 if (const llvm::MemoryBuffer *
710 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
711 // Create the file entry for the file that we're mapping from.
712 const FileEntry *FromFile
713 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
714 memBuf->getBufferSize(),
715 0);
716 if (!FromFile) {
717 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
718 << RemappedFiles[I].first;
719 delete memBuf;
720 continue;
721 }
722
723 // Override the contents of the "from" file with the contents of
724 // the "to" file.
725 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
726
727 } else {
728 const char *fname = fileOrBuf.get<const char *>();
729 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
730 if (!ToFile) {
731 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
732 << RemappedFiles[I].first << fname;
733 continue;
734 }
735
736 // Create the file entry for the file that we're mapping from.
737 const FileEntry *FromFile
738 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
739 ToFile->getSize(),
740 0);
741 if (!FromFile) {
742 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
743 << RemappedFiles[I].first;
744 delete memBuf;
745 continue;
746 }
747
748 // Override the contents of the "from" file with the contents of
749 // the "to" file.
750 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000751 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000752 }
753
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000754 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000756 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000757 unsigned Counter;
758
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000759 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000760
Douglas Gregor36a16492012-10-24 17:46:57 +0000761 AST->PP = new Preprocessor(new PreprocessorOptions(),
762 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000763 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
764 *AST,
765 /*IILookup=*/0,
766 /*OwnsHeaderSearch=*/false,
767 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000768 Preprocessor &PP = *AST->PP;
769
770 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
771 AST->getSourceManager(),
772 /*Target=*/0,
773 PP.getIdentifierTable(),
774 PP.getSelectorTable(),
775 PP.getBuiltinInfo(),
776 /* size_reserve = */0,
777 /*DelayInitialization=*/true);
778 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000779
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000780 bool disableValid = false;
781 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
782 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000783 Reader.reset(new ASTReader(PP, Context,
784 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000785 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000786 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000787
788 // Recover resources if we crash before exiting this method.
789 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
790 ReaderCleanup(Reader.get());
791
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000792 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000793 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000794 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000795 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000796
Douglas Gregor38295be2012-10-22 23:51:00 +0000797 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000798 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000799 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000800 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000802 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000803 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000804 case ASTReader::OutOfDate:
805 case ASTReader::VersionMismatch:
806 case ASTReader::ConfigurationMismatch:
807 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000808 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000809 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000810 }
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000812 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
813
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000814 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000816 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000817 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000818 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000819 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000820 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000821
822 // Unregister the cleanup for ASTReader. It will get cleaned up
823 // by the ASTUnit cleanup.
824 ReaderCleanup.unregister();
825
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000826 Context.setExternalSource(Source);
827
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000828 // Create an AST consumer, even though it isn't used.
829 AST->Consumer.reset(new ASTConsumer);
830
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000831 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000832 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
833 AST->TheSema->Initialize();
834 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000835 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000836
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000837 // Tell the diagnostic client that we have started a source file.
838 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
839
Mike Stump1eb44332009-09-09 15:08:12 +0000840 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000841}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000842
843namespace {
844
Douglas Gregor9b7db622011-02-16 18:16:54 +0000845/// \brief Preprocessor callback class that updates a hash value with the names
846/// of all macros that have been defined by the translation unit.
847class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
848 unsigned &Hash;
849
850public:
851 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
852
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000853 virtual void MacroDefined(const Token &MacroNameTok,
854 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000855 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
856 }
857};
858
859/// \brief Add the given declaration to the hash of all top-level entities.
860void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
861 if (!D)
862 return;
863
864 DeclContext *DC = D->getDeclContext();
865 if (!DC)
866 return;
867
868 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
869 return;
870
871 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
872 if (ND->getIdentifier())
873 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
874 else if (DeclarationName Name = ND->getDeclName()) {
875 std::string NameStr = Name.getAsString();
876 Hash = llvm::HashString(NameStr, Hash);
877 }
878 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000879 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000880}
881
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000882class TopLevelDeclTrackerConsumer : public ASTConsumer {
883 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000884 unsigned &Hash;
885
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000886public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000887 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
888 : Unit(_Unit), Hash(Hash) {
889 Hash = 0;
890 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000891
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000892 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000893 if (!D)
894 return;
895
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000896 // FIXME: Currently ObjC method declarations are incorrectly being
897 // reported as top-level declarations, even though their DeclContext
898 // is the containing ObjC @interface/@implementation. This is a
899 // fundamental problem in the parser right now.
900 if (isa<ObjCMethodDecl>(D))
901 return;
902
903 AddTopLevelDeclarationToHash(D, Hash);
904 Unit.addTopLevelDecl(D);
905
906 handleFileLevelDecl(D);
907 }
908
909 void handleFileLevelDecl(Decl *D) {
910 Unit.addFileLevelDecl(D);
911 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
912 for (NamespaceDecl::decl_iterator
913 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
914 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000915 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000916 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000917
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000918 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000919 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
920 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000921 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000922 }
923
Sebastian Redl27372b42010-08-11 18:52:41 +0000924 // We're not interested in "interesting" decls.
925 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000926
927 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
928 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
929 handleTopLevelDecl(*it);
930 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000931
932 virtual ASTDeserializationListener *GetASTDeserializationListener() {
933 return Unit.getDeserializationListener();
934 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000935};
936
937class TopLevelDeclTrackerAction : public ASTFrontendAction {
938public:
939 ASTUnit &Unit;
940
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000941 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000942 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000943 CI.getPreprocessor().addPPCallbacks(
944 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
945 return new TopLevelDeclTrackerConsumer(Unit,
946 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000947 }
948
949public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000950 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
951
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000952 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000953 virtual TranslationUnitKind getTranslationUnitKind() {
954 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000955 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000956};
957
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000958class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000959 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000960 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000961 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000962
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000963public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000964 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000965 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000966 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000967 Hash(Unit.getCurrentTopLevelHashValue()) {
968 Hash = 0;
969 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000970
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000971 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000972 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
973 Decl *D = *it;
974 // FIXME: Currently ObjC method declarations are incorrectly being
975 // reported as top-level declarations, even though their DeclContext
976 // is the containing ObjC @interface/@implementation. This is a
977 // fundamental problem in the parser right now.
978 if (isa<ObjCMethodDecl>(D))
979 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000980 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000981 TopLevelDecls.push_back(D);
982 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000983 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000984 }
985
986 virtual void HandleTranslationUnit(ASTContext &Ctx) {
987 PCHGenerator::HandleTranslationUnit(Ctx);
988 if (!Unit.getDiagnostics().hasErrorOccurred()) {
989 // Translate the top-level declarations we captured during
990 // parsing into declaration IDs in the precompiled
991 // preamble. This will allow us to deserialize those top-level
992 // declarations when requested.
993 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
994 Unit.addTopLevelDeclFromPreamble(
995 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000996 }
997 }
998};
999
1000class PrecompilePreambleAction : public ASTFrontendAction {
1001 ASTUnit &Unit;
1002
1003public:
1004 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1005
1006 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001007 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001008 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001009 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001010 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001011 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1012 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001013 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001014 return 0;
1015
Douglas Gregor832d6202011-07-22 16:35:34 +00001016 if (!CI.getFrontendOpts().RelocatablePCH)
1017 Sysroot.clear();
1018
Douglas Gregor9b7db622011-02-16 18:16:54 +00001019 CI.getPreprocessor().addPPCallbacks(
1020 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001021 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1022 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001023 }
1024
1025 virtual bool hasCodeCompletionSupport() const { return false; }
1026 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001027 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001028};
1029
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001030}
1031
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001032static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1033 return StoredDiag.getLocation().isValid();
1034}
1035
1036static void
1037checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001038 // Get rid of stored diagnostics except the ones from the driver which do not
1039 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001040 StoredDiags.erase(
1041 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1042 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001043}
1044
1045static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1046 StoredDiagnostics,
1047 SourceManager &SM) {
1048 // The stored diagnostic has the old source manager in it; update
1049 // the locations to refer into the new source manager. Since we've
1050 // been careful to make sure that the source manager's state
1051 // before and after are identical, so that we can reuse the source
1052 // location itself.
1053 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1054 if (StoredDiagnostics[I].getLocation().isValid()) {
1055 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1056 StoredDiagnostics[I].setLocation(Loc);
1057 }
1058 }
1059}
1060
Douglas Gregorabc563f2010-07-19 21:46:24 +00001061/// Parse the source file into a translation unit using the given compiler
1062/// invocation, replacing the current translation unit.
1063///
1064/// \returns True if a failure occurred that causes the ASTUnit not to
1065/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001066bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001067 delete SavedMainFileBuffer;
1068 SavedMainFileBuffer = 0;
1069
Ted Kremenek4f327862011-03-21 18:40:17 +00001070 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001071 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001072 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001073 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001074
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001075 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001076 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001077
1078 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001079 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1080 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001081
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001082 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001083 CCInvocation(new CompilerInvocation(*Invocation));
1084
1085 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001086 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001087
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001088 // Set up diagnostics, capturing any diagnostics that would
1089 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001090 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001091
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001092 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001093 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001094 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001095 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001096 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001097 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001098 }
1099
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001100 // Inform the target of the language options.
1101 //
1102 // FIXME: We shouldn't need to do this, the target should be immutable once
1103 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001104 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001105
Ted Kremenek03201fb2011-03-21 18:40:07 +00001106 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001107 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001108 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001109 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001110 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001111 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001112
Douglas Gregorabc563f2010-07-19 21:46:24 +00001113 // Configure the various subsystems.
1114 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001115 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001116 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001117 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001118 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1119 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001120 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001121 Ctx = 0;
1122 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001123 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001124
1125 // Clear out old caches and data.
1126 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001127 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001128 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001129
Douglas Gregorf128fed2010-08-20 00:02:33 +00001130 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001131 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001132 TopLevelDeclsInPreamble.clear();
1133 }
1134
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001135 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001136 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001137
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001138 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001139 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001140
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001141 // If the main file has been overridden due to the use of a preamble,
1142 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001143 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001144 if (OverrideMainBuffer) {
1145 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1146 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1147 PreprocessorOpts.PrecompiledPreambleBytes.second
1148 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001149 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001150 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001151
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001152 // The stored diagnostic has the old source manager in it; update
1153 // the locations to refer into the new source manager. Since we've
1154 // been careful to make sure that the source manager's state
1155 // before and after are identical, so that we can reuse the source
1156 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001157 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001158
1159 // Keep track of the override buffer;
1160 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001161 }
1162
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001163 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001164 new TopLevelDeclTrackerAction(*this));
1165
1166 // Recover resources if we crash before exiting this method.
1167 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1168 ActCleanup(Act.get());
1169
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001170 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001171 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001172
1173 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001174 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001175 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1176 getSourceManager(), PreambleDiagnostics,
1177 StoredDiagnostics);
1178 }
1179
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001180 if (!Act->Execute())
1181 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001182
1183 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001184
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001185 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001186
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001187 FailedParseDiagnostics.clear();
1188
Douglas Gregorabc563f2010-07-19 21:46:24 +00001189 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001190
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001191error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001192 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001193 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001194 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001195 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001196 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001197
1198 // Keep the ownership of the data in the ASTUnit because the client may
1199 // want to see the diagnostics.
1200 transferASTDataFromCompilerInstance(*Clang);
1201 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001202 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001203 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001204 return true;
1205}
1206
Douglas Gregor44c181a2010-07-23 00:33:23 +00001207/// \brief Simple function to retrieve a path for a preamble precompiled header.
1208static std::string GetPreamblePCHPath() {
1209 // FIXME: This is lame; sys::Path should provide this function (in particular,
1210 // it should know how to find the temporary files dir).
1211 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001212 // FIXME: This is a hack so that we can override the preamble file during
1213 // crash-recovery testing, which is the only case where the preamble files
1214 // are not necessarily cleaned up.
1215 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1216 if (TmpFile)
1217 return TmpFile;
1218
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 std::string Error;
1220 const char *TmpDir = ::getenv("TMPDIR");
1221 if (!TmpDir)
1222 TmpDir = ::getenv("TEMP");
1223 if (!TmpDir)
1224 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001225#ifdef LLVM_ON_WIN32
1226 if (!TmpDir)
1227 TmpDir = ::getenv("USERPROFILE");
1228#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229 if (!TmpDir)
1230 TmpDir = "/tmp";
1231 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001232 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001234 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001235 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 return std::string();
1237
Douglas Gregor44c181a2010-07-23 00:33:23 +00001238 return P.str();
1239}
1240
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001241/// \brief Compute the preamble for the main file, providing the source buffer
1242/// that corresponds to the main file along with a pair (bytes, start-of-line)
1243/// that describes the preamble.
1244std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001245ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1246 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001247 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001248 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249 CreatedBuffer = false;
1250
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251 // Try to determine if the main file has been remapped, either from the
1252 // command line (to another file) or directly through the compiler invocation
1253 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001254 llvm::MemoryBuffer *Buffer = 0;
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001255 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1257 // Check whether there is a file-file remapping of the main file
1258 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001259 M = PreprocessorOpts.remapped_file_begin(),
1260 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261 M != E;
1262 ++M) {
1263 llvm::sys::PathWithStatus MPath(M->first);
1264 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1265 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1266 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001267 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001269 CreatedBuffer = false;
1270 }
1271
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001272 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001273 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001274 return std::make_pair((llvm::MemoryBuffer*)0,
1275 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001277 }
1278 }
1279 }
1280
1281 // Check whether there is a file-buffer remapping. It supercedes the
1282 // file-file remapping.
1283 for (PreprocessorOptions::remapped_file_buffer_iterator
1284 M = PreprocessorOpts.remapped_file_buffer_begin(),
1285 E = PreprocessorOpts.remapped_file_buffer_end();
1286 M != E;
1287 ++M) {
1288 llvm::sys::PathWithStatus MPath(M->first);
1289 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1290 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1291 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001293 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001294 CreatedBuffer = false;
1295 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001296
Douglas Gregor175c4a92010-07-23 23:58:40 +00001297 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001298 }
1299 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001300 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001301 }
1302
1303 // If the main source file was not remapped, load it now.
1304 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001305 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001306 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001307 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001308
1309 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001310 }
1311
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001312 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001313 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001314 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001315}
1316
Douglas Gregor754f3492010-07-24 00:38:13 +00001317static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001318 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001319 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001320 llvm::MemoryBuffer *Result
1321 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1322 memcpy(const_cast<char*>(Result->getBufferStart()),
1323 Old->getBufferStart(), Old->getBufferSize());
1324 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001325 ' ', NewSize - Old->getBufferSize() - 1);
1326 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001327
Douglas Gregor754f3492010-07-24 00:38:13 +00001328 return Result;
1329}
1330
Douglas Gregor175c4a92010-07-23 23:58:40 +00001331/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1332/// the source file.
1333///
1334/// This routine will compute the preamble of the main source file. If a
1335/// non-trivial preamble is found, it will precompile that preamble into a
1336/// precompiled header so that the precompiled preamble can be used to reduce
1337/// reparsing time. If a precompiled preamble has already been constructed,
1338/// this routine will determine if it is still valid and, if so, avoid
1339/// rebuilding the precompiled preamble.
1340///
Douglas Gregordf95a132010-08-09 20:45:32 +00001341/// \param AllowRebuild When true (the default), this routine is
1342/// allowed to rebuild the precompiled preamble if it is found to be
1343/// out-of-date.
1344///
1345/// \param MaxLines When non-zero, the maximum number of lines that
1346/// can occur within the preamble.
1347///
Douglas Gregor754f3492010-07-24 00:38:13 +00001348/// \returns If the precompiled preamble can be used, returns a newly-allocated
1349/// buffer that should be used in place of the main file when doing so.
1350/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001351llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001352 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001353 bool AllowRebuild,
1354 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001355
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001356 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001357 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1358 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001359 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001360 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001361
1362 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001363 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001364 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001365
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001366 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001367 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001368 if (CreatedPreambleBuffer)
1369 OwnedPreambleBuffer.reset(NewPreamble.first);
1370
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001371 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001372 // We couldn't find a preamble in the main source. Clear out the current
1373 // preamble, if we have one. It's obviously no good any more.
1374 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001375 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001376
1377 // The next time we actually see a preamble, precompile it.
1378 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001379 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001380 }
1381
1382 if (!Preamble.empty()) {
1383 // We've previously computed a preamble. Check whether we have the same
1384 // preamble now that we did before, and that there's enough space in
1385 // the main-file buffer within the precompiled preamble to fit the
1386 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001387 if (Preamble.size() == NewPreamble.second.first &&
1388 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001389 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001390 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001391 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001392 // The preamble has not changed. We may be able to re-use the precompiled
1393 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001394
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001395 // Check that none of the files used by the preamble have changed.
1396 bool AnyFileChanged = false;
1397
1398 // First, make a record of those files that have been overridden via
1399 // remapping or unsaved_files.
1400 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1401 for (PreprocessorOptions::remapped_file_iterator
1402 R = PreprocessorOpts.remapped_file_begin(),
1403 REnd = PreprocessorOpts.remapped_file_end();
1404 !AnyFileChanged && R != REnd;
1405 ++R) {
1406 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001407 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001408 // If we can't stat the file we're remapping to, assume that something
1409 // horrible happened.
1410 AnyFileChanged = true;
1411 break;
1412 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001413
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001414 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1415 StatBuf.st_mtime);
1416 }
1417 for (PreprocessorOptions::remapped_file_buffer_iterator
1418 R = PreprocessorOpts.remapped_file_buffer_begin(),
1419 REnd = PreprocessorOpts.remapped_file_buffer_end();
1420 !AnyFileChanged && R != REnd;
1421 ++R) {
1422 // FIXME: Should we actually compare the contents of file->buffer
1423 // remappings?
1424 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1425 0);
1426 }
1427
1428 // Check whether anything has changed.
1429 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1430 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1431 !AnyFileChanged && F != FEnd;
1432 ++F) {
1433 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1434 = OverriddenFiles.find(F->first());
1435 if (Overridden != OverriddenFiles.end()) {
1436 // This file was remapped; check whether the newly-mapped file
1437 // matches up with the previous mapping.
1438 if (Overridden->second != F->second)
1439 AnyFileChanged = true;
1440 continue;
1441 }
1442
1443 // The file was not remapped; check whether it has changed on disk.
1444 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001445 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001446 // If we can't stat the file, assume that something horrible happened.
1447 AnyFileChanged = true;
1448 } else if (StatBuf.st_size != F->second.first ||
1449 StatBuf.st_mtime != F->second.second)
1450 AnyFileChanged = true;
1451 }
1452
1453 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001454 // Okay! We can re-use the precompiled preamble.
1455
1456 // Set the state of the diagnostic object to mimic its state
1457 // after parsing the preamble.
1458 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001459 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001460 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001461 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001462
1463 // Create a version of the main file buffer that is padded to
1464 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001465 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001466 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001467 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001468 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001469 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001470
1471 // If we aren't allowed to rebuild the precompiled preamble, just
1472 // return now.
1473 if (!AllowRebuild)
1474 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001475
Douglas Gregor175c4a92010-07-23 23:58:40 +00001476 // We can't reuse the previously-computed preamble. Build a new one.
1477 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001478 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001479 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001480 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001481 } else if (!AllowRebuild) {
1482 // We aren't allowed to rebuild the precompiled preamble; just
1483 // return now.
1484 return 0;
1485 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001486
1487 // If the preamble rebuild counter > 1, it's because we previously
1488 // failed to build a preamble and we're not yet ready to try
1489 // again. Decrement the counter and return a failure.
1490 if (PreambleRebuildCounter > 1) {
1491 --PreambleRebuildCounter;
1492 return 0;
1493 }
1494
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001495 // Create a temporary file for the precompiled preamble. In rare
1496 // circumstances, this can fail.
1497 std::string PreamblePCHPath = GetPreamblePCHPath();
1498 if (PreamblePCHPath.empty()) {
1499 // Try again next time.
1500 PreambleRebuildCounter = 1;
1501 return 0;
1502 }
1503
Douglas Gregor175c4a92010-07-23 23:58:40 +00001504 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001505 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001506 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001507
1508 // Create a new buffer that stores the preamble. The buffer also contains
1509 // extra space for the original contents of the file (which will be present
1510 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001511 // grows.
1512 PreambleReservedSize = NewPreamble.first->getBufferSize();
1513 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001514 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001515 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001516 PreambleReservedSize *= 2;
1517
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001518 // Save the preamble text for later; we'll need to compare against it for
1519 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001520 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001521 Preamble.assign(FileMgr->getFile(MainFilename),
1522 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001523 NewPreamble.first->getBufferStart()
1524 + NewPreamble.second.first);
1525 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1526
Douglas Gregor671947b2010-08-19 01:33:06 +00001527 delete PreambleBuffer;
1528 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001529 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001530 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001532 NewPreamble.first->getBufferStart(), Preamble.size());
1533 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001534 ' ', PreambleReservedSize - Preamble.size() - 1);
1535 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001536
1537 // Remap the main source file to the preamble buffer.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001538 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001539 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1540
1541 // Tell the compiler invocation to generate a temporary precompiled header.
1542 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001543 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001544 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001545 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1546 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001547
1548 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001549 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001550
1551 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001552 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1553 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001554
Douglas Gregor01b6e312011-07-01 18:22:13 +00001555 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001556 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001557
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001558 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001559 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001560
1561 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001562 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001563 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001564 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001565 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1566 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001567 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001568 PreprocessorOpts.eraseRemappedFile(
1569 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001570 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001571 }
1572
1573 // Inform the target of the language options.
1574 //
1575 // FIXME: We shouldn't need to do this, the target should be immutable once
1576 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001577 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001578
Ted Kremenek03201fb2011-03-21 18:40:07 +00001579 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001580 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001581 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001582 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001583 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001584 "IR inputs not support here!");
1585
1586 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001587 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001588 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001589 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001590 TopLevelDecls.clear();
1591 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001592
1593 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001594 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001595
1596 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001597 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001598 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001599
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001600 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001601 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001602 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001603 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1604 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001605 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001606 PreprocessorOpts.eraseRemappedFile(
1607 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001608 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001609 }
1610
1611 Act->Execute();
1612 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001613
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001614 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001615 // There were errors parsing the preamble, so no precompiled header was
1616 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001617 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001618 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1619 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001620 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001621 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001622 PreprocessorOpts.eraseRemappedFile(
1623 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001624 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001625 }
1626
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001627 // Transfer any diagnostics generated when parsing the preamble into the set
1628 // of preamble diagnostics.
1629 PreambleDiagnostics.clear();
1630 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001631 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001632 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001633
Douglas Gregor175c4a92010-07-23 23:58:40 +00001634 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001635 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001636 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001637
1638 // Keep track of all of the files that the source manager knows about,
1639 // so we can verify whether they have changed or not.
1640 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001641 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001642 const llvm::MemoryBuffer *MainFileBuffer
1643 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1644 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1645 FEnd = SourceMgr.fileinfo_end();
1646 F != FEnd;
1647 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001648 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001649 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1650 continue;
1651
1652 FilesInPreamble[File->getName()]
1653 = std::make_pair(F->second->getSize(), File->getModificationTime());
1654 }
1655
Douglas Gregoreababfb2010-08-04 05:53:38 +00001656 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001657 PreprocessorOpts.eraseRemappedFile(
1658 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001659
1660 // If the hash of top-level entities differs from the hash of the top-level
1661 // entities the last time we rebuilt the preamble, clear out the completion
1662 // cache.
1663 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1664 CompletionCacheTopLevelHashValue = 0;
1665 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1666 }
1667
Douglas Gregor754f3492010-07-24 00:38:13 +00001668 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001669 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001670 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001671}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001672
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001673void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1674 std::vector<Decl *> Resolved;
1675 Resolved.reserve(TopLevelDeclsInPreamble.size());
1676 ExternalASTSource &Source = *getASTContext().getExternalSource();
1677 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1678 // Resolve the declaration ID to an actual declaration, possibly
1679 // deserializing the declaration in the process.
1680 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1681 if (D)
1682 Resolved.push_back(D);
1683 }
1684 TopLevelDeclsInPreamble.clear();
1685 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1686}
1687
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001688void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1689 // Steal the created target, context, and preprocessor.
1690 TheSema.reset(CI.takeSema());
1691 Consumer.reset(CI.takeASTConsumer());
1692 Ctx = &CI.getASTContext();
1693 PP = &CI.getPreprocessor();
1694 CI.setSourceManager(0);
1695 CI.setFileManager(0);
1696 Target = &CI.getTarget();
1697 Reader = CI.getModuleManager();
1698}
1699
Chris Lattner5f9e2722011-07-23 10:55:15 +00001700StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001701 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1702 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1703 if (Input.isFile())
1704 return Input.getFile();
1705 else
1706 return Input.getBuffer()->getBufferIdentifier();
1707 }
1708
1709 if (SourceMgr) {
1710 if (const FileEntry *
1711 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1712 return FE->getName();
1713 }
1714
1715 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001716}
1717
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001718StringRef ASTUnit::getASTFileName() const {
1719 if (!isMainFileAST())
1720 return StringRef();
1721
1722 serialization::ModuleFile &
1723 Mod = Reader->getModuleManager().getPrimaryModule();
1724 return Mod.FileName;
1725}
1726
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001727ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001728 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001729 bool CaptureDiagnostics,
1730 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001731 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001732 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001733 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001734 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001735 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001736 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001737 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001738 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1739 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1740 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001741
1742 return AST.take();
1743}
1744
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001745ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001746 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001747 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001748 ASTUnit *Unit,
1749 bool Persistent,
1750 StringRef ResourceFilesPath,
1751 bool OnlyLocalDecls,
1752 bool CaptureDiagnostics,
1753 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001754 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001755 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001756 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001757 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758 assert(CI && "A CompilerInvocation is required");
1759
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001760 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001761 ASTUnit *AST = Unit;
1762 if (!AST) {
1763 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001764 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001765 AST = OwnAST.get();
1766 }
1767
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001768 if (!ResourceFilesPath.empty()) {
1769 // Override the resources path.
1770 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1771 }
1772 AST->OnlyLocalDecls = OnlyLocalDecls;
1773 AST->CaptureDiagnostics = CaptureDiagnostics;
1774 if (PrecompilePreamble)
1775 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001776 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001777 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001778 AST->IncludeBriefCommentsInCodeCompletion
1779 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001780
1781 // Recover resources if we crash before exiting this method.
1782 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001783 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001784 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1785 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001786 DiagCleanup(Diags.getPtr());
1787
1788 // We'll manage file buffers ourselves.
1789 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1790 CI->getFrontendOpts().DisableFree = false;
1791 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1792
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001793 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001794 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001795
1796 // Recover resources if we crash before exiting this method.
1797 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1798 CICleanup(Clang.get());
1799
1800 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001801 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001802
1803 // Set up diagnostics, capturing any diagnostics that would
1804 // otherwise be dropped.
1805 Clang->setDiagnostics(&AST->getDiagnostics());
1806
1807 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001808 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001809 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001810 if (!Clang->hasTarget())
1811 return 0;
1812
1813 // Inform the target of the language options.
1814 //
1815 // FIXME: We shouldn't need to do this, the target should be immutable once
1816 // created. This complexity should be lifted elsewhere.
1817 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1818
1819 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1820 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001821 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001822 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001823 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001824 "IR inputs not supported here!");
1825
1826 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001827 AST->TheSema.reset();
1828 AST->Ctx = 0;
1829 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001830 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001831
1832 // Create a file manager object to provide access to and cache the filesystem.
1833 Clang->setFileManager(&AST->getFileManager());
1834
1835 // Create the source manager.
1836 Clang->setSourceManager(&AST->getSourceManager());
1837
1838 ASTFrontendAction *Act = Action;
1839
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001840 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001841 if (!Act) {
1842 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1843 Act = TrackerAct.get();
1844 }
1845
1846 // Recover resources if we crash before exiting this method.
1847 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1848 ActCleanup(TrackerAct.get());
1849
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001850 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1851 AST->transferASTDataFromCompilerInstance(*Clang);
1852 if (OwnAST && ErrAST)
1853 ErrAST->swap(OwnAST);
1854
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001855 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001856 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001857
1858 if (Persistent && !TrackerAct) {
1859 Clang->getPreprocessor().addPPCallbacks(
1860 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1861 std::vector<ASTConsumer*> Consumers;
1862 if (Clang->hasASTConsumer())
1863 Consumers.push_back(Clang->takeASTConsumer());
1864 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1865 AST->getCurrentTopLevelHashValue()));
1866 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1867 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001868 if (!Act->Execute()) {
1869 AST->transferASTDataFromCompilerInstance(*Clang);
1870 if (OwnAST && ErrAST)
1871 ErrAST->swap(OwnAST);
1872
1873 return 0;
1874 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001875
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001876 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001877 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001878
1879 Act->EndSourceFile();
1880
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001881 if (OwnAST)
1882 return OwnAST.take();
1883 else
1884 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001885}
1886
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001887bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1888 if (!Invocation)
1889 return true;
1890
1891 // We'll manage file buffers ourselves.
1892 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1893 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001894 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001895
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001896 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001897 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001898 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001899 OverrideMainBuffer
1900 = getMainBufferWithPrecompiledPreamble(*Invocation);
1901 }
1902
Douglas Gregor213f18b2010-10-28 15:44:59 +00001903 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001904 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001905
Ted Kremenek25a11e12011-03-22 01:15:24 +00001906 // Recover resources if we crash before exiting this method.
1907 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1908 MemBufferCleanup(OverrideMainBuffer);
1909
Douglas Gregor213f18b2010-10-28 15:44:59 +00001910 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001911}
1912
Douglas Gregorabc563f2010-07-19 21:46:24 +00001913ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001914 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001915 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001916 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001917 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001918 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001919 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001920 bool IncludeBriefCommentsInCodeCompletion,
1921 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001922 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001923 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001924 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001925 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001926 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001927 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001928 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001929 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001930 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001931 AST->IncludeBriefCommentsInCodeCompletion
1932 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001933 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001934 AST->FileSystemOpts = CI->getFileSystemOpts();
1935 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001936 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001937
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001938 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001939 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1940 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001941 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1942 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001943 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001944
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001945 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001946}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001947
1948ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1949 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001950 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001951 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001952 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001953 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001954 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001955 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001956 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001957 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001958 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001959 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001960 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001961 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001962 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001963 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001964 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001965 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001966 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001967 // No diagnostics engine was provided, so create our own diagnostics object
1968 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001969 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001970 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001971
Chris Lattner5f9e2722011-07-23 10:55:15 +00001972 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001973
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001974 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001975
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001976 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001977
Douglas Gregore47be3e2010-11-11 00:39:14 +00001978 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001979 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001980
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001981 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001982 llvm::makeArrayRef(ArgBegin, ArgEnd),
1983 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001984 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001985 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001986 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001987
Douglas Gregor4db64a42010-01-23 00:14:00 +00001988 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001989 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1990 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1991 if (const llvm::MemoryBuffer *
1992 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1993 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1994 } else {
1995 const char *fname = fileOrBuf.get<const char *>();
1996 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1997 }
1998 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001999 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2000 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2001 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002002
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002003 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002004 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002005
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002006 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2007
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002008 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002009 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002010 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002011 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002012 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002013 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002014 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002015 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002016 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002017 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002018 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002019 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002020 AST->IncludeBriefCommentsInCodeCompletion
2021 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002022 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002023 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002024 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002025 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002026 if (ForSerialization)
2027 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002028 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002029
2030 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002031 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2032 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002033
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002034 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2035 // Some error occurred, if caller wants to examine diagnostics, pass it the
2036 // ASTUnit.
2037 if (ErrAST) {
2038 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2039 ErrAST->swap(AST);
2040 }
2041 return 0;
2042 }
2043
2044 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002045}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002046
2047bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002048 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002049 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002050
2051 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002052
Douglas Gregor213f18b2010-10-28 15:44:59 +00002053 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002054 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002055
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002056 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002057 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2058 for (PreprocessorOptions::remapped_file_buffer_iterator
2059 R = PPOpts.remapped_file_buffer_begin(),
2060 REnd = PPOpts.remapped_file_buffer_end();
2061 R != REnd;
2062 ++R) {
2063 delete R->second;
2064 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002065 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002066 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2067 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2068 if (const llvm::MemoryBuffer *
2069 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2070 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2071 memBuf);
2072 } else {
2073 const char *fname = fileOrBuf.get<const char *>();
2074 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2075 fname);
2076 }
2077 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002078
Douglas Gregoreababfb2010-08-04 05:53:38 +00002079 // If we have a preamble file lying around, or if we might try to
2080 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002081 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002082 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002083 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002084
Douglas Gregorabc563f2010-07-19 21:46:24 +00002085 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002086 getDiagnostics().Reset();
2087 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002088 if (OverrideMainBuffer)
2089 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002090
Douglas Gregor175c4a92010-07-23 23:58:40 +00002091 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002092 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002093
2094 // If we're caching global code-completion results, and the top-level
2095 // declarations have changed, clear out the code-completion cache.
2096 if (!Result && ShouldCacheCodeCompletionResults &&
2097 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2098 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002099
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002100 // We now need to clear out the completion info related to this translation
2101 // unit; it'll be recreated if necessary.
2102 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002103
Douglas Gregor175c4a92010-07-23 23:58:40 +00002104 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002105}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002106
Douglas Gregor87c08a52010-08-13 22:48:40 +00002107//----------------------------------------------------------------------------//
2108// Code completion
2109//----------------------------------------------------------------------------//
2110
2111namespace {
2112 /// \brief Code completion consumer that combines the cached code-completion
2113 /// results from an ASTUnit with the code-completion results provided to it,
2114 /// then passes the result on to
2115 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002116 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002117 ASTUnit &AST;
2118 CodeCompleteConsumer &Next;
2119
2120 public:
2121 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002122 const CodeCompleteOptions &CodeCompleteOpts)
2123 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2124 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002125 {
2126 // Compute the set of contexts in which we will look when we don't have
2127 // any information about the specific context.
2128 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002129 = (1LL << CodeCompletionContext::CCC_TopLevel)
2130 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2131 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2132 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2133 | (1LL << CodeCompletionContext::CCC_Statement)
2134 | (1LL << CodeCompletionContext::CCC_Expression)
2135 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2136 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2137 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2138 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2139 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2140 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2141 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002142
David Blaikie4e4d0842012-03-11 07:00:24 +00002143 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002144 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2145 | (1LL << CodeCompletionContext::CCC_UnionTag)
2146 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002147 }
2148
2149 virtual void ProcessCodeCompleteResults(Sema &S,
2150 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002151 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002152 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002153
2154 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2155 OverloadCandidate *Candidates,
2156 unsigned NumCandidates) {
2157 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2158 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002159
Douglas Gregordae68752011-02-01 22:57:45 +00002160 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002161 return Next.getAllocator();
2162 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002163
2164 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2165 return Next.getCodeCompletionTUInfo();
2166 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002167 };
2168}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002169
Douglas Gregor5f808c22010-08-16 21:18:39 +00002170/// \brief Helper function that computes which global names are hidden by the
2171/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002172static void CalculateHiddenNames(const CodeCompletionContext &Context,
2173 CodeCompletionResult *Results,
2174 unsigned NumResults,
2175 ASTContext &Ctx,
2176 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002177 bool OnlyTagNames = false;
2178 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002179 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002180 case CodeCompletionContext::CCC_TopLevel:
2181 case CodeCompletionContext::CCC_ObjCInterface:
2182 case CodeCompletionContext::CCC_ObjCImplementation:
2183 case CodeCompletionContext::CCC_ObjCIvarList:
2184 case CodeCompletionContext::CCC_ClassStructUnion:
2185 case CodeCompletionContext::CCC_Statement:
2186 case CodeCompletionContext::CCC_Expression:
2187 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002188 case CodeCompletionContext::CCC_DotMemberAccess:
2189 case CodeCompletionContext::CCC_ArrowMemberAccess:
2190 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002191 case CodeCompletionContext::CCC_Namespace:
2192 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002193 case CodeCompletionContext::CCC_Name:
2194 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002195 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002196 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002197 break;
2198
2199 case CodeCompletionContext::CCC_EnumTag:
2200 case CodeCompletionContext::CCC_UnionTag:
2201 case CodeCompletionContext::CCC_ClassOrStructTag:
2202 OnlyTagNames = true;
2203 break;
2204
2205 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002206 case CodeCompletionContext::CCC_MacroName:
2207 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002208 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002209 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002210 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002211 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002212 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002213 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002214 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002215 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2216 case CodeCompletionContext::CCC_ObjCClassMessage:
2217 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002218 // We're looking for nothing, or we're looking for names that cannot
2219 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002220 return;
2221 }
2222
John McCall0a2c5e22010-08-25 06:19:51 +00002223 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002224 for (unsigned I = 0; I != NumResults; ++I) {
2225 if (Results[I].Kind != Result::RK_Declaration)
2226 continue;
2227
2228 unsigned IDNS
2229 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2230
2231 bool Hiding = false;
2232 if (OnlyTagNames)
2233 Hiding = (IDNS & Decl::IDNS_Tag);
2234 else {
2235 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002236 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2237 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002238 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002239 HiddenIDNS |= Decl::IDNS_Tag;
2240 Hiding = (IDNS & HiddenIDNS);
2241 }
2242
2243 if (!Hiding)
2244 continue;
2245
2246 DeclarationName Name = Results[I].Declaration->getDeclName();
2247 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2248 HiddenNames.insert(Identifier->getName());
2249 else
2250 HiddenNames.insert(Name.getAsString());
2251 }
2252}
2253
2254
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002255void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2256 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002257 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002258 unsigned NumResults) {
2259 // Merge the results we were given with the results we cached.
2260 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002261 uint64_t InContexts =
2262 Context.getKind() == CodeCompletionContext::CCC_Recovery
2263 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002264 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002265 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002266 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002267 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002268 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002269 C = AST.cached_completion_begin(),
2270 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002271 C != CEnd; ++C) {
2272 // If the context we are in matches any of the contexts we are
2273 // interested in, we'll add this result.
2274 if ((C->ShowInContexts & InContexts) == 0)
2275 continue;
2276
2277 // If we haven't added any results previously, do so now.
2278 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002279 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2280 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002281 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2282 AddedResult = true;
2283 }
2284
Douglas Gregor5f808c22010-08-16 21:18:39 +00002285 // Determine whether this global completion result is hidden by a local
2286 // completion result. If so, skip it.
2287 if (C->Kind != CXCursor_MacroDefinition &&
2288 HiddenNames.count(C->Completion->getTypedText()))
2289 continue;
2290
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002291 // Adjust priority based on similar type classes.
2292 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002293 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002294 if (!Context.getPreferredType().isNull()) {
2295 if (C->Kind == CXCursor_MacroDefinition) {
2296 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002297 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002298 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002299 } else if (C->Type) {
2300 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002301 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002302 Context.getPreferredType().getUnqualifiedType());
2303 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2304 if (ExpectedSTC == C->TypeClass) {
2305 // We know this type is similar; check for an exact match.
2306 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002307 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002308 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002309 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002310 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2311 Priority /= CCF_ExactTypeMatch;
2312 else
2313 Priority /= CCF_SimilarTypeMatch;
2314 }
2315 }
2316 }
2317
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002318 // Adjust the completion string, if required.
2319 if (C->Kind == CXCursor_MacroDefinition &&
2320 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2321 // Create a new code-completion string that just contains the
2322 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002323 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2324 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002325 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002326 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002327 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002328 }
2329
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002330 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002331 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002332 }
2333
2334 // If we did not add any cached completion results, just forward the
2335 // results we were given to the next consumer.
2336 if (!AddedResult) {
2337 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2338 return;
2339 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002340
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002341 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2342 AllResults.size());
2343}
2344
2345
2346
Chris Lattner5f9e2722011-07-23 10:55:15 +00002347void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348 RemappedFile *RemappedFiles,
2349 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002350 bool IncludeMacros,
2351 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002352 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002353 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002354 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002356 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2357 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002358 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002359 return;
2360
Douglas Gregor213f18b2010-10-28 15:44:59 +00002361 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002362 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002363 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002364
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002365 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002366 CCInvocation(new CompilerInvocation(*Invocation));
2367
2368 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002369 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002370 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002371
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002372 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2373 CachedCompletionResults.empty();
2374 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2375 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2376 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2377
2378 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2379
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002380 FrontendOpts.CodeCompletionAt.FileName = File;
2381 FrontendOpts.CodeCompletionAt.Line = Line;
2382 FrontendOpts.CodeCompletionAt.Column = Column;
2383
2384 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002385 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002386
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002387 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002388
2389 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002390 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2391 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002392
Ted Kremenek4f327862011-03-21 18:40:17 +00002393 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002394 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002395
2396 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002397 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002398 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002399 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002400 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002401 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002402
2403 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002404 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002405 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002406 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002407 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002408 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002409 }
2410
2411 // Inform the target of the language options.
2412 //
2413 // FIXME: We shouldn't need to do this, the target should be immutable once
2414 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002415 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416
Ted Kremenek03201fb2011-03-21 18:40:07 +00002417 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002419 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002420 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002421 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002422 "IR inputs not support here!");
2423
2424
2425 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002426 Clang->setFileManager(&FileMgr);
2427 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002428
2429 // Remap files.
2430 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002431 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002432 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002433 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2434 if (const llvm::MemoryBuffer *
2435 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2436 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2437 OwnedBuffers.push_back(memBuf);
2438 } else {
2439 const char *fname = fileOrBuf.get<const char *>();
2440 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2441 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002442 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002443
Douglas Gregor87c08a52010-08-13 22:48:40 +00002444 // Use the code completion consumer we were given, but adding any cached
2445 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002446 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002447 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002448 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002449
Douglas Gregordf95a132010-08-09 20:45:32 +00002450 // If we have a precompiled preamble, try to use it. We only allow
2451 // the use of the precompiled preamble if we're if the completion
2452 // point is within the main file, after the end of the precompiled
2453 // preamble.
2454 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002455 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002456 using llvm::sys::FileStatus;
2457 llvm::sys::PathWithStatus CompleteFilePath(File);
2458 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2459 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2460 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002461 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2462 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002463 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002464 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002465 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002466 }
2467
2468 // If the main file has been overridden due to the use of a preamble,
2469 // make that override happen and introduce the preamble.
2470 if (OverrideMainBuffer) {
2471 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2472 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2473 PreprocessorOpts.PrecompiledPreambleBytes.second
2474 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002475 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002476 PreprocessorOpts.DisablePCHValidation = true;
2477
Douglas Gregor2283d792010-08-20 00:59:43 +00002478 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002479 } else {
2480 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2481 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002482 }
2483
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002484 // Disable the preprocessing record if modules are not enabled.
2485 if (!Clang->getLangOpts().Modules)
2486 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002487
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002488 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002489 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002490 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002491 Act->Execute();
2492 Act->EndSourceFile();
2493 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002494}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002495
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002496bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002497 // Write to a temporary file and later rename it to the actual file, to avoid
2498 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002499 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002500 TempPath = File;
2501 TempPath += "-%%%%%%%%";
2502 int fd;
2503 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2504 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002505 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002506
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002507 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2508 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002509 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002510
2511 serialize(Out);
2512 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002513 if (Out.has_error()) {
2514 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002515 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002516 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002517
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002518 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002519 bool exists;
2520 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002521 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002522 }
2523
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002524 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002525}
2526
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002527static bool serializeUnit(ASTWriter &Writer,
2528 SmallVectorImpl<char> &Buffer,
2529 Sema &S,
2530 bool hasErrors,
2531 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002532 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002533
2534 // Write the generated bitstream to "Out".
2535 if (!Buffer.empty())
2536 OS.write(Buffer.data(), Buffer.size());
2537
2538 return false;
2539}
2540
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002542 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002543
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002544 if (WriterData)
2545 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2546 getSema(), hasErrors, OS);
2547
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002548 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002549 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002550 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002551 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002552}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002553
2554typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2555
2556static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2557 unsigned Raw = L.getRawEncoding();
2558 const unsigned MacroBit = 1U << 31;
2559 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2560 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2561}
2562
2563void ASTUnit::TranslateStoredDiagnostics(
2564 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002566 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002567 const SmallVectorImpl<StoredDiagnostic> &Diags,
2568 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002569 // The stored diagnostic has the old source manager in it; update
2570 // the locations to refer into the new source manager. We also need to remap
2571 // all the locations to the new view. This includes the diag location, any
2572 // associated source ranges, and the source ranges of associated fix-its.
2573 // FIXME: There should be a cleaner way to do this.
2574
Chris Lattner5f9e2722011-07-23 10:55:15 +00002575 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002576 Result.reserve(Diags.size());
2577 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002578 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002579 assert(Mod && "Don't have preamble module");
2580 SLocRemap &Remap = Mod->SLocRemap;
2581 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2582 // Rebuild the StoredDiagnostic.
2583 const StoredDiagnostic &SD = Diags[I];
2584 SourceLocation L = SD.getLocation();
2585 TranslateSLoc(L, Remap);
2586 FullSourceLoc Loc(L, SrcMgr);
2587
Chris Lattner5f9e2722011-07-23 10:55:15 +00002588 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002589 Ranges.reserve(SD.range_size());
2590 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2591 E = SD.range_end();
2592 I != E; ++I) {
2593 SourceLocation BL = I->getBegin();
2594 TranslateSLoc(BL, Remap);
2595 SourceLocation EL = I->getEnd();
2596 TranslateSLoc(EL, Remap);
2597 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2598 }
2599
Chris Lattner5f9e2722011-07-23 10:55:15 +00002600 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002601 FixIts.reserve(SD.fixit_size());
2602 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2603 E = SD.fixit_end();
2604 I != E; ++I) {
2605 FixIts.push_back(FixItHint());
2606 FixItHint &FH = FixIts.back();
2607 FH.CodeToInsert = I->CodeToInsert;
2608 SourceLocation BL = I->RemoveRange.getBegin();
2609 TranslateSLoc(BL, Remap);
2610 SourceLocation EL = I->RemoveRange.getEnd();
2611 TranslateSLoc(EL, Remap);
2612 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2613 I->RemoveRange.isTokenRange());
2614 }
2615
2616 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2617 SD.getMessage(), Loc, Ranges, FixIts));
2618 }
2619 Result.swap(Out);
2620}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002621
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002622static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2623 std::pair<unsigned, Decl *> R) {
2624 return L.first < R.first;
2625}
2626
2627void ASTUnit::addFileLevelDecl(Decl *D) {
2628 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002629
2630 // We only care about local declarations.
2631 if (D->isFromASTFile())
2632 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002633
2634 SourceManager &SM = *SourceMgr;
2635 SourceLocation Loc = D->getLocation();
2636 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2637 return;
2638
2639 // We only keep track of the file-level declarations of each file.
2640 if (!D->getLexicalDeclContext()->isFileContext())
2641 return;
2642
2643 SourceLocation FileLoc = SM.getFileLoc(Loc);
2644 assert(SM.isLocalSourceLocation(FileLoc));
2645 FileID FID;
2646 unsigned Offset;
2647 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2648 if (FID.isInvalid())
2649 return;
2650
2651 LocDeclsTy *&Decls = FileDecls[FID];
2652 if (!Decls)
2653 Decls = new LocDeclsTy();
2654
2655 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2656
2657 if (Decls->empty() || Decls->back().first <= Offset) {
2658 Decls->push_back(LocDecl);
2659 return;
2660 }
2661
2662 LocDeclsTy::iterator
2663 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2664
2665 Decls->insert(I, LocDecl);
2666}
2667
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002668void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2669 SmallVectorImpl<Decl *> &Decls) {
2670 if (File.isInvalid())
2671 return;
2672
2673 if (SourceMgr->isLoadedFileID(File)) {
2674 assert(Ctx->getExternalSource() && "No external source!");
2675 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2676 Decls);
2677 }
2678
2679 FileDeclsTy::iterator I = FileDecls.find(File);
2680 if (I == FileDecls.end())
2681 return;
2682
2683 LocDeclsTy &LocDecls = *I->second;
2684 if (LocDecls.empty())
2685 return;
2686
2687 LocDeclsTy::iterator
2688 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2689 std::make_pair(Offset, (Decl*)0), compLocDecl);
2690 if (BeginIt != LocDecls.begin())
2691 --BeginIt;
2692
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002693 // If we are pointing at a top-level decl inside an objc container, we need
2694 // to backtrack until we find it otherwise we will fail to report that the
2695 // region overlaps with an objc container.
2696 while (BeginIt != LocDecls.begin() &&
2697 BeginIt->second->isTopLevelDeclInObjCContainer())
2698 --BeginIt;
2699
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002700 LocDeclsTy::iterator
2701 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2702 std::make_pair(Offset+Length, (Decl*)0),
2703 compLocDecl);
2704 if (EndIt != LocDecls.end())
2705 ++EndIt;
2706
2707 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2708 Decls.push_back(DIt->second);
2709}
2710
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002711SourceLocation ASTUnit::getLocation(const FileEntry *File,
2712 unsigned Line, unsigned Col) const {
2713 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002714 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002715 return SM.getMacroArgExpandedLocation(Loc);
2716}
2717
2718SourceLocation ASTUnit::getLocation(const FileEntry *File,
2719 unsigned Offset) const {
2720 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002721 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002722 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2723}
2724
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002725/// \brief If \arg Loc is a loaded location from the preamble, returns
2726/// the corresponding local location of the main file, otherwise it returns
2727/// \arg Loc.
2728SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2729 FileID PreambleID;
2730 if (SourceMgr)
2731 PreambleID = SourceMgr->getPreambleFileID();
2732
2733 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2734 return Loc;
2735
2736 unsigned Offs;
2737 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2738 SourceLocation FileLoc
2739 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2740 return FileLoc.getLocWithOffset(Offs);
2741 }
2742
2743 return Loc;
2744}
2745
2746/// \brief If \arg Loc is a local location of the main file but inside the
2747/// preamble chunk, returns the corresponding loaded location from the
2748/// preamble, otherwise it returns \arg Loc.
2749SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2750 FileID PreambleID;
2751 if (SourceMgr)
2752 PreambleID = SourceMgr->getPreambleFileID();
2753
2754 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2755 return Loc;
2756
2757 unsigned Offs;
2758 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2759 Offs < Preamble.size()) {
2760 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2761 return FileLoc.getLocWithOffset(Offs);
2762 }
2763
2764 return Loc;
2765}
2766
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002767bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2768 FileID FID;
2769 if (SourceMgr)
2770 FID = SourceMgr->getPreambleFileID();
2771
2772 if (Loc.isInvalid() || FID.isInvalid())
2773 return false;
2774
2775 return SourceMgr->isInFileID(Loc, FID);
2776}
2777
2778bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2779 FileID FID;
2780 if (SourceMgr)
2781 FID = SourceMgr->getMainFileID();
2782
2783 if (Loc.isInvalid() || FID.isInvalid())
2784 return false;
2785
2786 return SourceMgr->isInFileID(Loc, FID);
2787}
2788
2789SourceLocation ASTUnit::getEndOfPreambleFileID() {
2790 FileID FID;
2791 if (SourceMgr)
2792 FID = SourceMgr->getPreambleFileID();
2793
2794 if (FID.isInvalid())
2795 return SourceLocation();
2796
2797 return SourceMgr->getLocForEndOfFile(FID);
2798}
2799
2800SourceLocation ASTUnit::getStartOfMainFileID() {
2801 FileID FID;
2802 if (SourceMgr)
2803 FID = SourceMgr->getMainFileID();
2804
2805 if (FID.isInvalid())
2806 return SourceLocation();
2807
2808 return SourceMgr->getLocForStartOfFile(FID);
2809}
2810
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002811std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2812ASTUnit::getLocalPreprocessingEntities() const {
2813 if (isMainFileAST()) {
2814 serialization::ModuleFile &
2815 Mod = Reader->getModuleManager().getPrimaryModule();
2816 return Reader->getModulePreprocessedEntities(Mod);
2817 }
2818
2819 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2820 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2821
2822 return std::make_pair(PreprocessingRecord::iterator(),
2823 PreprocessingRecord::iterator());
2824}
2825
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002826bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002827 if (isMainFileAST()) {
2828 serialization::ModuleFile &
2829 Mod = Reader->getModuleManager().getPrimaryModule();
2830 ASTReader::ModuleDeclIterator MDI, MDE;
2831 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2832 for (; MDI != MDE; ++MDI) {
2833 if (!Fn(context, *MDI))
2834 return false;
2835 }
2836
2837 return true;
2838 }
2839
2840 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2841 TLEnd = top_level_end();
2842 TL != TLEnd; ++TL) {
2843 if (!Fn(context, *TL))
2844 return false;
2845 }
2846
2847 return true;
2848}
2849
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002850namespace {
2851struct PCHLocatorInfo {
2852 serialization::ModuleFile *Mod;
2853 PCHLocatorInfo() : Mod(0) {}
2854};
2855}
2856
2857static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2858 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2859 switch (M.Kind) {
2860 case serialization::MK_Module:
2861 return true; // skip dependencies.
2862 case serialization::MK_PCH:
2863 Info.Mod = &M;
2864 return true; // found it.
2865 case serialization::MK_Preamble:
2866 return false; // look in dependencies.
2867 case serialization::MK_MainFile:
2868 return false; // look in dependencies.
2869 }
2870
2871 return true;
2872}
2873
2874const FileEntry *ASTUnit::getPCHFile() {
2875 if (!Reader)
2876 return 0;
2877
2878 PCHLocatorInfo Info;
2879 Reader->getModuleManager().visit(PCHLocator, &Info);
2880 if (Info.Mod)
2881 return Info.Mod->File;
2882
2883 return 0;
2884}
2885
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002886bool ASTUnit::isModuleFile() {
2887 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2888}
2889
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002890void ASTUnit::PreambleData::countLines() const {
2891 NumLines = 0;
2892 if (empty())
2893 return;
2894
2895 for (std::vector<char>::const_iterator
2896 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2897 if (*I == '\n')
2898 ++NumLines;
2899 }
2900 if (Buffer.back() != '\n')
2901 ++NumLines;
2902}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002903
2904#ifndef NDEBUG
2905ASTUnit::ConcurrencyState::ConcurrencyState() {
2906 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2907}
2908
2909ASTUnit::ConcurrencyState::~ConcurrencyState() {
2910 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2911}
2912
2913void ASTUnit::ConcurrencyState::start() {
2914 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2915 assert(acquired && "Concurrent access to ASTUnit!");
2916}
2917
2918void ASTUnit::ConcurrencyState::finish() {
2919 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2920}
2921
2922#else // NDEBUG
2923
2924ASTUnit::ConcurrencyState::ConcurrencyState() {}
2925ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2926void ASTUnit::ConcurrencyState::start() {}
2927void ASTUnit::ConcurrencyState::finish() {}
2928
2929#endif