blob: 8738035c4922814bf54ca4effad195e13ce7f408 [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"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000030#include "clang/Lex/PreprocessorOptions.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.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"
Douglas Gregor4db64a42010-01-23 00:14:00 +000038#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000039#include "llvm/Support/Host.h"
40#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000041#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000042#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000043#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000044#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000045#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000046#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000047#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000048#include <cstdio>
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
Ted Kremenek1872b312011-10-27 17:55:18 +0000106static void cleanupOnDiskMapAtExit(void);
107
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
119static void cleanupOnDiskMapAtExit(void) {
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
158static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
159 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() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000239 clearFileLevelDecls();
240
Ted Kremenek1872b312011-10-27 17:55:18 +0000241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
243
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
247 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000248 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
250 for (PreprocessorOptions::remapped_file_buffer_iterator
251 FB = PPOpts.remapped_file_buffer_begin(),
252 FBEnd = PPOpts.remapped_file_buffer_end();
253 FB != FBEnd;
254 ++FB)
255 delete FB->second;
256 }
Douglas Gregor28233422010-07-27 14:52:07 +0000257
258 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000259 delete PreambleBuffer;
260
Douglas Gregor213f18b2010-10-28 15:44:59 +0000261 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000262
263 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000264 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000265 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
266 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000267}
268
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000269void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
270
Douglas Gregor8071e422010-08-15 06:18:01 +0000271/// \brief Determine the set of code-completion contexts in which this
272/// declaration should be shown.
273static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000274 const LangOptions &LangOpts,
275 bool &IsNestedNameSpecifier) {
276 IsNestedNameSpecifier = false;
277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278 if (isa<UsingShadowDecl>(ND))
279 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
280 if (!ND)
281 return 0;
282
Richard Smith026b3582012-08-14 03:13:00 +0000283 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000284 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
285 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
286 // Types can appear in these contexts.
287 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
289 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
290 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
291 | (1LL << CodeCompletionContext::CCC_Statement)
292 | (1LL << CodeCompletionContext::CCC_Type)
293 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000294
295 // In C++, types can appear in expressions contexts (for functional casts).
296 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // In Objective-C, message sends can send interfaces. In Objective-C++,
300 // all types are available due to functional casts.
301 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000303
304 // In Objective-C, you can only be a subclass of another Objective-C class
305 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000307
308 // Deal with tag names.
309 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000311
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000312 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000315 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
316 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000318 else
Richard Smith026b3582012-08-14 03:13:00 +0000319 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000320
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000322 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000323 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000324 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
326 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
328 | (1LL << CodeCompletionContext::CCC_Expression)
329 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
330 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000333 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000337
338 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000339 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 }
341
342 return Contexts;
343}
344
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345void ASTUnit::CacheCodeCompletionResults() {
346 if (!TheSema)
347 return;
348
Douglas Gregor213f18b2010-10-28 15:44:59 +0000349 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000350 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000351
352 // Clear out the previous results.
353 ClearCachedCompletionResults();
354
355 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000356 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000357 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000358 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000359 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
360 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000361
362 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000363 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
364
Douglas Gregor87c08a52010-08-13 22:48:40 +0000365 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
366 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000368 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000369 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000370 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000371 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000372 getCodeCompletionTUInfo(),
373 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000374 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000375 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000376 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000377 CachedResult.Priority = Results[I].Priority;
378 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000379 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000380
Douglas Gregorf5586f62010-08-16 18:08:11 +0000381 // Keep track of the type of this completion in an ASTContext-agnostic
382 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000383 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000384 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000385 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000386 CachedResult.Type = 0;
387 } else {
388 CanQualType CanUsageType
389 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
390 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
391
392 // Determine whether we have already seen this type. If so, we save
393 // ourselves the work of formatting the type string by using the
394 // temporary, CanQualType-based hash table to find the associated value.
395 unsigned &TypeValue = CompletionTypes[CanUsageType];
396 if (TypeValue == 0) {
397 TypeValue = CompletionTypes.size();
398 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
399 = TypeValue;
400 }
401
402 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000403 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000404
Douglas Gregor8071e422010-08-15 06:18:01 +0000405 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000406
407 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000409 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
410 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000411 uint64_t NNSContexts
412 = (1LL << CodeCompletionContext::CCC_TopLevel)
413 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
414 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
415 | (1LL << CodeCompletionContext::CCC_Statement)
416 | (1LL << CodeCompletionContext::CCC_Expression)
417 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
418 | (1LL << CodeCompletionContext::CCC_EnumTag)
419 | (1LL << CodeCompletionContext::CCC_UnionTag)
420 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
421 | (1LL << CodeCompletionContext::CCC_Type)
422 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
423 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000424
425 if (isa<NamespaceDecl>(Results[I].Declaration) ||
426 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000427 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000428
429 if (unsigned RemainingContexts
430 = NNSContexts & ~CachedResult.ShowInContexts) {
431 // If there any contexts where this completion can be a
432 // nested-name-specifier but isn't already an option, create a
433 // nested-name-specifier completion.
434 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000435 CachedResult.Completion
436 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000437 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000438 getCodeCompletionTUInfo(),
439 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000440 CachedResult.ShowInContexts = RemainingContexts;
441 CachedResult.Priority = CCP_NestedNameSpecifier;
442 CachedResult.TypeClass = STC_Void;
443 CachedResult.Type = 0;
444 CachedCompletionResults.push_back(CachedResult);
445 }
446 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000447 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000448 }
449
Douglas Gregor87c08a52010-08-13 22:48:40 +0000450 case Result::RK_Keyword:
451 case Result::RK_Pattern:
452 // Ignore keywords and patterns; we don't care, since they are so
453 // easily regenerated.
454 break;
455
456 case Result::RK_Macro: {
457 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000458 CachedResult.Completion
459 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000460 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000461 getCodeCompletionTUInfo(),
462 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000463 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000464 = (1LL << CodeCompletionContext::CCC_TopLevel)
465 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
466 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
467 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
468 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
469 | (1LL << CodeCompletionContext::CCC_Statement)
470 | (1LL << CodeCompletionContext::CCC_Expression)
471 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
472 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
473 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
474 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
475 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000476
Douglas Gregor87c08a52010-08-13 22:48:40 +0000477 CachedResult.Priority = Results[I].Priority;
478 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000479 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000480 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000481 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482 CachedCompletionResults.push_back(CachedResult);
483 break;
484 }
485 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000486 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000487
488 // Save the current top-level hash value.
489 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000490}
491
492void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000493 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000494 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000495 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000496}
497
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498namespace {
499
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000500/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000502class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000503 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000504 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505 LangOptions &LangOpt;
506 HeaderSearch &HSI;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000507 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000515 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000516 HeaderSearch &HSI,
517 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000518 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000520 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
521 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor43998902012-10-25 00:09:28 +0000522 Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000523 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000525 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000526 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000527 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000528 return false;
529
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000530 LangOpt = LangOpts;
531 InitializedLanguage = true;
532
533 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000534 return false;
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000537 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000538 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000539 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000540 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000541 return false;
542
Douglas Gregor57016dd2012-10-16 23:40:58 +0000543 this->TargetOpts = new TargetOptions(TargetOpts);
544 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
545 *this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000546
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000547 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000548 return false;
549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000551 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000552 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000555 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 Counter = Value;
557 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000558
559private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000560 void updated() {
561 if (!Target || !InitializedLanguage)
562 return;
563
564 // Inform the target of the language options.
565 //
566 // FIXME: We shouldn't need to do this, the target should be immutable once
567 // created. This complexity should be lifted elsewhere.
568 Target->setForcedLangOptions(LangOpt);
569
570 // Initialize the preprocessor.
571 PP.Initialize(*Target);
572
573 // Initialize the ASTContext
574 Context.InitBuiltinTypes(*Target);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000575 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000576};
577
David Blaikie26e7a902011-09-26 00:01:39 +0000578class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000580
581public:
David Blaikie26e7a902011-09-26 00:01:39 +0000582 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000584 : StoredDiags(StoredDiags) { }
585
David Blaikied6471f72011-09-25 23:23:43 +0000586 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000587 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000588
589 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
590 // Just drop any diagnostics that come from cloned consumers; they'll
591 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000592 // FIXME: We'd like to be able to capture these somehow, even if it's just
593 // file/line/column, because they could occur when parsing module maps or
594 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000595 return new IgnoringDiagConsumer();
596 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000597};
598
599/// \brief RAII object that optionally captures diagnostics, if
600/// there is no diagnostic client to capture them already.
601class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000602 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000603 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000604 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000605
606public:
David Blaikied6471f72011-09-25 23:23:43 +0000607 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000608 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000609 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000610 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000611 if (RequestCapture || Diags.getClient() == 0) {
612 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000613 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000614 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000615 }
616
617 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000618 if (Diags.getClient() == &Client) {
619 Diags.takeClient();
620 Diags.setClient(PreviousClient);
621 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000622 }
623};
624
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000625} // anonymous namespace
626
David Blaikie26e7a902011-09-26 00:01:39 +0000627void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000628 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000629 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000630 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000631
Douglas Gregora88084b2010-02-18 18:08:43 +0000632 StoredDiags.push_back(StoredDiagnostic(Level, Info));
633}
634
Steve Naroff77accc12009-09-03 18:19:54 +0000635const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000636 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000637}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000638
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000639ASTDeserializationListener *ASTUnit::getDeserializationListener() {
640 if (WriterData)
641 return &WriterData->Writer;
642 return 0;
643}
644
Chris Lattner5f9e2722011-07-23 10:55:15 +0000645llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000646 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000647 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000648 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000649}
650
Douglas Gregore47be3e2010-11-11 00:39:14 +0000651/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000652void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000653 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000654 ASTUnit &AST, bool CaptureDiagnostics) {
655 if (!Diags.getPtr()) {
656 // No diagnostics engine was provided, so create our own diagnostics object
657 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000658 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000659 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000660 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000661 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
662 ArgEnd-ArgBegin,
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000663 ArgBegin, Client,
664 /*ShouldOwnClient=*/true,
665 /*ShouldCloneClient=*/false);
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 /*DisableStatCache=*/false,
787 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000788
789 // Recover resources if we crash before exiting this method.
790 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
791 ReaderCleanup(Reader.get());
792
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000793 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000794 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000795 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000796 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000797
Douglas Gregor38295be2012-10-22 23:51:00 +0000798 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
799 ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000800 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000801 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000803 case ASTReader::Failure:
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
Mike Stump1eb44332009-09-09 15:08:12 +0000837 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000838}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000839
840namespace {
841
Douglas Gregor9b7db622011-02-16 18:16:54 +0000842/// \brief Preprocessor callback class that updates a hash value with the names
843/// of all macros that have been defined by the translation unit.
844class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
845 unsigned &Hash;
846
847public:
848 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
849
850 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
851 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
852 }
853};
854
855/// \brief Add the given declaration to the hash of all top-level entities.
856void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
857 if (!D)
858 return;
859
860 DeclContext *DC = D->getDeclContext();
861 if (!DC)
862 return;
863
864 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
865 return;
866
867 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
868 if (ND->getIdentifier())
869 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
870 else if (DeclarationName Name = ND->getDeclName()) {
871 std::string NameStr = Name.getAsString();
872 Hash = llvm::HashString(NameStr, Hash);
873 }
874 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000875 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000876}
877
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000878class TopLevelDeclTrackerConsumer : public ASTConsumer {
879 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000880 unsigned &Hash;
881
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000882public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000883 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
884 : Unit(_Unit), Hash(Hash) {
885 Hash = 0;
886 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000887
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000888 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000889 if (!D)
890 return;
891
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000892 // FIXME: Currently ObjC method declarations are incorrectly being
893 // reported as top-level declarations, even though their DeclContext
894 // is the containing ObjC @interface/@implementation. This is a
895 // fundamental problem in the parser right now.
896 if (isa<ObjCMethodDecl>(D))
897 return;
898
899 AddTopLevelDeclarationToHash(D, Hash);
900 Unit.addTopLevelDecl(D);
901
902 handleFileLevelDecl(D);
903 }
904
905 void handleFileLevelDecl(Decl *D) {
906 Unit.addFileLevelDecl(D);
907 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
908 for (NamespaceDecl::decl_iterator
909 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
910 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000911 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000912 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000913
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000914 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000915 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
916 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000917 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000918 }
919
Sebastian Redl27372b42010-08-11 18:52:41 +0000920 // We're not interested in "interesting" decls.
921 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000922
923 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
924 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
925 handleTopLevelDecl(*it);
926 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000927
928 virtual ASTDeserializationListener *GetASTDeserializationListener() {
929 return Unit.getDeserializationListener();
930 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000931};
932
933class TopLevelDeclTrackerAction : public ASTFrontendAction {
934public:
935 ASTUnit &Unit;
936
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000937 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000938 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000939 CI.getPreprocessor().addPPCallbacks(
940 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
941 return new TopLevelDeclTrackerConsumer(Unit,
942 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000943 }
944
945public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000946 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
947
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000948 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000949 virtual TranslationUnitKind getTranslationUnitKind() {
950 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000951 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000952};
953
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000954class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000955 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000956 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000957 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000958
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000959public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000960 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000961 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000962 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000963 Hash(Unit.getCurrentTopLevelHashValue()) {
964 Hash = 0;
965 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000966
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000967 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000968 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
969 Decl *D = *it;
970 // FIXME: Currently ObjC method declarations are incorrectly being
971 // reported as top-level declarations, even though their DeclContext
972 // is the containing ObjC @interface/@implementation. This is a
973 // fundamental problem in the parser right now.
974 if (isa<ObjCMethodDecl>(D))
975 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000976 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000977 TopLevelDecls.push_back(D);
978 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000979 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000980 }
981
982 virtual void HandleTranslationUnit(ASTContext &Ctx) {
983 PCHGenerator::HandleTranslationUnit(Ctx);
984 if (!Unit.getDiagnostics().hasErrorOccurred()) {
985 // Translate the top-level declarations we captured during
986 // parsing into declaration IDs in the precompiled
987 // preamble. This will allow us to deserialize those top-level
988 // declarations when requested.
989 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
990 Unit.addTopLevelDeclFromPreamble(
991 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000992 }
993 }
994};
995
996class PrecompilePreambleAction : public ASTFrontendAction {
997 ASTUnit &Unit;
998
999public:
1000 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1001
1002 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001003 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001004 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001005 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001006 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001007 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1008 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001009 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001010 return 0;
1011
Douglas Gregor832d6202011-07-22 16:35:34 +00001012 if (!CI.getFrontendOpts().RelocatablePCH)
1013 Sysroot.clear();
1014
Douglas Gregor9b7db622011-02-16 18:16:54 +00001015 CI.getPreprocessor().addPPCallbacks(
1016 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001017 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1018 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001019 }
1020
1021 virtual bool hasCodeCompletionSupport() const { return false; }
1022 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001023 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001024};
1025
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001026}
1027
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001028static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1029 StoredDiagnostics) {
1030 // Get rid of stored diagnostics except the ones from the driver which do not
1031 // have a source location.
1032 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1033 if (StoredDiagnostics[I].getLocation().isValid()) {
1034 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1035 --I;
1036 }
1037 }
1038}
1039
1040static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1041 StoredDiagnostics,
1042 SourceManager &SM) {
1043 // The stored diagnostic has the old source manager in it; update
1044 // the locations to refer into the new source manager. Since we've
1045 // been careful to make sure that the source manager's state
1046 // before and after are identical, so that we can reuse the source
1047 // location itself.
1048 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1049 if (StoredDiagnostics[I].getLocation().isValid()) {
1050 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1051 StoredDiagnostics[I].setLocation(Loc);
1052 }
1053 }
1054}
1055
Douglas Gregorabc563f2010-07-19 21:46:24 +00001056/// Parse the source file into a translation unit using the given compiler
1057/// invocation, replacing the current translation unit.
1058///
1059/// \returns True if a failure occurred that causes the ASTUnit not to
1060/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001061bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001062 delete SavedMainFileBuffer;
1063 SavedMainFileBuffer = 0;
1064
Ted Kremenek4f327862011-03-21 18:40:17 +00001065 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001066 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001067 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001068 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001069
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001070 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001071 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001072
1073 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001074 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1075 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001076
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001077 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001078 CCInvocation(new CompilerInvocation(*Invocation));
1079
1080 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001081 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001083 // Set up diagnostics, capturing any diagnostics that would
1084 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001085 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001086
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001087 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001088 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001089 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001090 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001091 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001092 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001093 }
1094
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001095 // Inform the target of the language options.
1096 //
1097 // FIXME: We shouldn't need to do this, the target should be immutable once
1098 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001099 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001100
Ted Kremenek03201fb2011-03-21 18:40:07 +00001101 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001102 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001103 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001104 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001105 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001106 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001107
Douglas Gregorabc563f2010-07-19 21:46:24 +00001108 // Configure the various subsystems.
1109 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001110 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001111 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001112 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001113 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1114 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001115 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001116 Ctx = 0;
1117 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001118 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001119
1120 // Clear out old caches and data.
1121 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001122 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001123 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001124
Douglas Gregorf128fed2010-08-20 00:02:33 +00001125 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001126 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001127 TopLevelDeclsInPreamble.clear();
1128 }
1129
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001130 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001131 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001132
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001133 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001134 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001135
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001136 // If the main file has been overridden due to the use of a preamble,
1137 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001138 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001139 if (OverrideMainBuffer) {
1140 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1141 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1142 PreprocessorOpts.PrecompiledPreambleBytes.second
1143 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001144 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001145 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001146
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001147 // The stored diagnostic has the old source manager in it; update
1148 // the locations to refer into the new source manager. Since we've
1149 // been careful to make sure that the source manager's state
1150 // before and after are identical, so that we can reuse the source
1151 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001152 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001153
1154 // Keep track of the override buffer;
1155 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001156 }
1157
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001158 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001159 new TopLevelDeclTrackerAction(*this));
1160
1161 // Recover resources if we crash before exiting this method.
1162 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1163 ActCleanup(Act.get());
1164
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001165 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001166 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001167
1168 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001169 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001170 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1171 getSourceManager(), PreambleDiagnostics,
1172 StoredDiagnostics);
1173 }
1174
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001175 if (!Act->Execute())
1176 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001177
1178 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001179
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001180 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001181
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001182 FailedParseDiagnostics.clear();
1183
Douglas Gregorabc563f2010-07-19 21:46:24 +00001184 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001185
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001186error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001187 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001188 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001189 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001190 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001191 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001192
1193 // Keep the ownership of the data in the ASTUnit because the client may
1194 // want to see the diagnostics.
1195 transferASTDataFromCompilerInstance(*Clang);
1196 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001197 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001198 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001199 return true;
1200}
1201
Douglas Gregor44c181a2010-07-23 00:33:23 +00001202/// \brief Simple function to retrieve a path for a preamble precompiled header.
1203static std::string GetPreamblePCHPath() {
1204 // FIXME: This is lame; sys::Path should provide this function (in particular,
1205 // it should know how to find the temporary files dir).
1206 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001207 // FIXME: This is a hack so that we can override the preamble file during
1208 // crash-recovery testing, which is the only case where the preamble files
1209 // are not necessarily cleaned up.
1210 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1211 if (TmpFile)
1212 return TmpFile;
1213
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214 std::string Error;
1215 const char *TmpDir = ::getenv("TMPDIR");
1216 if (!TmpDir)
1217 TmpDir = ::getenv("TEMP");
1218 if (!TmpDir)
1219 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001220#ifdef LLVM_ON_WIN32
1221 if (!TmpDir)
1222 TmpDir = ::getenv("USERPROFILE");
1223#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224 if (!TmpDir)
1225 TmpDir = "/tmp";
1226 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001227 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001229 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001230 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231 return std::string();
1232
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233 return P.str();
1234}
1235
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001236/// \brief Compute the preamble for the main file, providing the source buffer
1237/// that corresponds to the main file along with a pair (bytes, start-of-line)
1238/// that describes the preamble.
1239std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001240ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1241 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001242 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001243 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001244 CreatedBuffer = false;
1245
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 // Try to determine if the main file has been remapped, either from the
1247 // command line (to another file) or directly through the compiler invocation
1248 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001250 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1252 // Check whether there is a file-file remapping of the main file
1253 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001254 M = PreprocessorOpts.remapped_file_begin(),
1255 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256 M != E;
1257 ++M) {
1258 llvm::sys::PathWithStatus MPath(M->first);
1259 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1260 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1261 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001262 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001264 CreatedBuffer = false;
1265 }
1266
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001267 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001269 return std::make_pair((llvm::MemoryBuffer*)0,
1270 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001271 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001272 }
1273 }
1274 }
1275
1276 // Check whether there is a file-buffer remapping. It supercedes the
1277 // file-file remapping.
1278 for (PreprocessorOptions::remapped_file_buffer_iterator
1279 M = PreprocessorOpts.remapped_file_buffer_begin(),
1280 E = PreprocessorOpts.remapped_file_buffer_end();
1281 M != E;
1282 ++M) {
1283 llvm::sys::PathWithStatus MPath(M->first);
1284 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1285 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1286 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001287 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001288 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001289 CreatedBuffer = false;
1290 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001291
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001293 }
1294 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001295 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001296 }
1297
1298 // If the main source file was not remapped, load it now.
1299 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001300 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001301 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001302 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001303
1304 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001305 }
1306
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001307 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001308 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001309 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001310}
1311
Douglas Gregor754f3492010-07-24 00:38:13 +00001312static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001313 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001314 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001315 llvm::MemoryBuffer *Result
1316 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1317 memcpy(const_cast<char*>(Result->getBufferStart()),
1318 Old->getBufferStart(), Old->getBufferSize());
1319 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001320 ' ', NewSize - Old->getBufferSize() - 1);
1321 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001322
Douglas Gregor754f3492010-07-24 00:38:13 +00001323 return Result;
1324}
1325
Douglas Gregor175c4a92010-07-23 23:58:40 +00001326/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1327/// the source file.
1328///
1329/// This routine will compute the preamble of the main source file. If a
1330/// non-trivial preamble is found, it will precompile that preamble into a
1331/// precompiled header so that the precompiled preamble can be used to reduce
1332/// reparsing time. If a precompiled preamble has already been constructed,
1333/// this routine will determine if it is still valid and, if so, avoid
1334/// rebuilding the precompiled preamble.
1335///
Douglas Gregordf95a132010-08-09 20:45:32 +00001336/// \param AllowRebuild When true (the default), this routine is
1337/// allowed to rebuild the precompiled preamble if it is found to be
1338/// out-of-date.
1339///
1340/// \param MaxLines When non-zero, the maximum number of lines that
1341/// can occur within the preamble.
1342///
Douglas Gregor754f3492010-07-24 00:38:13 +00001343/// \returns If the precompiled preamble can be used, returns a newly-allocated
1344/// buffer that should be used in place of the main file when doing so.
1345/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001346llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001347 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001348 bool AllowRebuild,
1349 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001350
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001351 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001352 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1353 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001354 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001355 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001356
1357 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001358 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001359 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001360
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001361 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001362 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001363 if (CreatedPreambleBuffer)
1364 OwnedPreambleBuffer.reset(NewPreamble.first);
1365
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001366 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001367 // We couldn't find a preamble in the main source. Clear out the current
1368 // preamble, if we have one. It's obviously no good any more.
1369 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001370 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001371
1372 // The next time we actually see a preamble, precompile it.
1373 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001374 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001375 }
1376
1377 if (!Preamble.empty()) {
1378 // We've previously computed a preamble. Check whether we have the same
1379 // preamble now that we did before, and that there's enough space in
1380 // the main-file buffer within the precompiled preamble to fit the
1381 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001382 if (Preamble.size() == NewPreamble.second.first &&
1383 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001384 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001385 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001386 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001387 // The preamble has not changed. We may be able to re-use the precompiled
1388 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001389
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001390 // Check that none of the files used by the preamble have changed.
1391 bool AnyFileChanged = false;
1392
1393 // First, make a record of those files that have been overridden via
1394 // remapping or unsaved_files.
1395 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1396 for (PreprocessorOptions::remapped_file_iterator
1397 R = PreprocessorOpts.remapped_file_begin(),
1398 REnd = PreprocessorOpts.remapped_file_end();
1399 !AnyFileChanged && R != REnd;
1400 ++R) {
1401 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001402 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001403 // If we can't stat the file we're remapping to, assume that something
1404 // horrible happened.
1405 AnyFileChanged = true;
1406 break;
1407 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001408
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001409 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1410 StatBuf.st_mtime);
1411 }
1412 for (PreprocessorOptions::remapped_file_buffer_iterator
1413 R = PreprocessorOpts.remapped_file_buffer_begin(),
1414 REnd = PreprocessorOpts.remapped_file_buffer_end();
1415 !AnyFileChanged && R != REnd;
1416 ++R) {
1417 // FIXME: Should we actually compare the contents of file->buffer
1418 // remappings?
1419 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1420 0);
1421 }
1422
1423 // Check whether anything has changed.
1424 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1425 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1426 !AnyFileChanged && F != FEnd;
1427 ++F) {
1428 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1429 = OverriddenFiles.find(F->first());
1430 if (Overridden != OverriddenFiles.end()) {
1431 // This file was remapped; check whether the newly-mapped file
1432 // matches up with the previous mapping.
1433 if (Overridden->second != F->second)
1434 AnyFileChanged = true;
1435 continue;
1436 }
1437
1438 // The file was not remapped; check whether it has changed on disk.
1439 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001440 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001441 // If we can't stat the file, assume that something horrible happened.
1442 AnyFileChanged = true;
1443 } else if (StatBuf.st_size != F->second.first ||
1444 StatBuf.st_mtime != F->second.second)
1445 AnyFileChanged = true;
1446 }
1447
1448 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001449 // Okay! We can re-use the precompiled preamble.
1450
1451 // Set the state of the diagnostic object to mimic its state
1452 // after parsing the preamble.
1453 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001454 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001455 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001456 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001457
1458 // Create a version of the main file buffer that is padded to
1459 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001460 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001461 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001462 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001463 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001464 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001465
1466 // If we aren't allowed to rebuild the precompiled preamble, just
1467 // return now.
1468 if (!AllowRebuild)
1469 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001470
Douglas Gregor175c4a92010-07-23 23:58:40 +00001471 // We can't reuse the previously-computed preamble. Build a new one.
1472 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001473 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001474 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001475 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001476 } else if (!AllowRebuild) {
1477 // We aren't allowed to rebuild the precompiled preamble; just
1478 // return now.
1479 return 0;
1480 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001481
1482 // If the preamble rebuild counter > 1, it's because we previously
1483 // failed to build a preamble and we're not yet ready to try
1484 // again. Decrement the counter and return a failure.
1485 if (PreambleRebuildCounter > 1) {
1486 --PreambleRebuildCounter;
1487 return 0;
1488 }
1489
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001490 // Create a temporary file for the precompiled preamble. In rare
1491 // circumstances, this can fail.
1492 std::string PreamblePCHPath = GetPreamblePCHPath();
1493 if (PreamblePCHPath.empty()) {
1494 // Try again next time.
1495 PreambleRebuildCounter = 1;
1496 return 0;
1497 }
1498
Douglas Gregor175c4a92010-07-23 23:58:40 +00001499 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001500 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001501 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001502
1503 // Create a new buffer that stores the preamble. The buffer also contains
1504 // extra space for the original contents of the file (which will be present
1505 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001506 // grows.
1507 PreambleReservedSize = NewPreamble.first->getBufferSize();
1508 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001509 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001510 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001511 PreambleReservedSize *= 2;
1512
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001513 // Save the preamble text for later; we'll need to compare against it for
1514 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001515 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001516 Preamble.assign(FileMgr->getFile(MainFilename),
1517 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001518 NewPreamble.first->getBufferStart()
1519 + NewPreamble.second.first);
1520 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1521
Douglas Gregor671947b2010-08-19 01:33:06 +00001522 delete PreambleBuffer;
1523 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001524 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001525 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001526 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001527 NewPreamble.first->getBufferStart(), Preamble.size());
1528 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001529 ' ', PreambleReservedSize - Preamble.size() - 1);
1530 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531
1532 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001533 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001534 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1535
1536 // Tell the compiler invocation to generate a temporary precompiled header.
1537 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001538 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001539 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001540 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1541 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001542
1543 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001544 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001545
1546 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001547 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1548 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001549
Douglas Gregor01b6e312011-07-01 18:22:13 +00001550 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001551 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001553 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001554 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001555
1556 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001557 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor57016dd2012-10-16 23:40:58 +00001558 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001559 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001560 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1561 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001562 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001563 PreprocessorOpts.eraseRemappedFile(
1564 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001565 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001566 }
1567
1568 // Inform the target of the language options.
1569 //
1570 // FIXME: We shouldn't need to do this, the target should be immutable once
1571 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001572 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001573
Ted Kremenek03201fb2011-03-21 18:40:07 +00001574 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001575 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001576 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001577 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001578 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579 "IR inputs not support here!");
1580
1581 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001582 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001583 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001584 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001585 TopLevelDecls.clear();
1586 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001587
1588 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001589 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590
1591 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001592 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001593 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001594
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001595 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001596 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001597 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001598 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1599 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001600 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001601 PreprocessorOpts.eraseRemappedFile(
1602 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001603 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001604 }
1605
1606 Act->Execute();
1607 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001608
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001609 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001610 // There were errors parsing the preamble, so no precompiled header was
1611 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001612 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001613 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1614 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001615 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001616 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001617 PreprocessorOpts.eraseRemappedFile(
1618 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001619 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001620 }
1621
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001622 // Transfer any diagnostics generated when parsing the preamble into the set
1623 // of preamble diagnostics.
1624 PreambleDiagnostics.clear();
1625 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001626 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001627 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001628
Douglas Gregor175c4a92010-07-23 23:58:40 +00001629 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001630 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001631 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001632
1633 // Keep track of all of the files that the source manager knows about,
1634 // so we can verify whether they have changed or not.
1635 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001636 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001637 const llvm::MemoryBuffer *MainFileBuffer
1638 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1639 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1640 FEnd = SourceMgr.fileinfo_end();
1641 F != FEnd;
1642 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001643 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001644 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1645 continue;
1646
1647 FilesInPreamble[File->getName()]
1648 = std::make_pair(F->second->getSize(), File->getModificationTime());
1649 }
1650
Douglas Gregoreababfb2010-08-04 05:53:38 +00001651 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001652 PreprocessorOpts.eraseRemappedFile(
1653 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001654
1655 // If the hash of top-level entities differs from the hash of the top-level
1656 // entities the last time we rebuilt the preamble, clear out the completion
1657 // cache.
1658 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1659 CompletionCacheTopLevelHashValue = 0;
1660 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1661 }
1662
Douglas Gregor754f3492010-07-24 00:38:13 +00001663 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001664 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001665 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001666}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001667
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001668void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1669 std::vector<Decl *> Resolved;
1670 Resolved.reserve(TopLevelDeclsInPreamble.size());
1671 ExternalASTSource &Source = *getASTContext().getExternalSource();
1672 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1673 // Resolve the declaration ID to an actual declaration, possibly
1674 // deserializing the declaration in the process.
1675 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1676 if (D)
1677 Resolved.push_back(D);
1678 }
1679 TopLevelDeclsInPreamble.clear();
1680 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1681}
1682
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001683void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1684 // Steal the created target, context, and preprocessor.
1685 TheSema.reset(CI.takeSema());
1686 Consumer.reset(CI.takeASTConsumer());
1687 Ctx = &CI.getASTContext();
1688 PP = &CI.getPreprocessor();
1689 CI.setSourceManager(0);
1690 CI.setFileManager(0);
1691 Target = &CI.getTarget();
1692 Reader = CI.getModuleManager();
1693}
1694
Chris Lattner5f9e2722011-07-23 10:55:15 +00001695StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001696 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001697}
1698
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001699ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001700 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001701 bool CaptureDiagnostics,
1702 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001703 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001704 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001705 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001706 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001707 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001708 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001709 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001710 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1711 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1712 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001713
1714 return AST.take();
1715}
1716
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001717ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001718 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001719 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001720 ASTUnit *Unit,
1721 bool Persistent,
1722 StringRef ResourceFilesPath,
1723 bool OnlyLocalDecls,
1724 bool CaptureDiagnostics,
1725 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001726 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001727 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001728 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001729 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001730 assert(CI && "A CompilerInvocation is required");
1731
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001732 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001733 ASTUnit *AST = Unit;
1734 if (!AST) {
1735 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001736 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001737 AST = OwnAST.get();
1738 }
1739
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001740 if (!ResourceFilesPath.empty()) {
1741 // Override the resources path.
1742 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1743 }
1744 AST->OnlyLocalDecls = OnlyLocalDecls;
1745 AST->CaptureDiagnostics = CaptureDiagnostics;
1746 if (PrecompilePreamble)
1747 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001748 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001749 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001750 AST->IncludeBriefCommentsInCodeCompletion
1751 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001752
1753 // Recover resources if we crash before exiting this method.
1754 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001755 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001756 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1757 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758 DiagCleanup(Diags.getPtr());
1759
1760 // We'll manage file buffers ourselves.
1761 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1762 CI->getFrontendOpts().DisableFree = false;
1763 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1764
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001766 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001767
1768 // Recover resources if we crash before exiting this method.
1769 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1770 CICleanup(Clang.get());
1771
1772 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001773 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001774
1775 // Set up diagnostics, capturing any diagnostics that would
1776 // otherwise be dropped.
1777 Clang->setDiagnostics(&AST->getDiagnostics());
1778
1779 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001780 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1781 Clang->getTargetOpts()));
1782 if (!Clang->hasTarget())
1783 return 0;
1784
1785 // Inform the target of the language options.
1786 //
1787 // FIXME: We shouldn't need to do this, the target should be immutable once
1788 // created. This complexity should be lifted elsewhere.
1789 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1790
1791 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1792 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001793 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001794 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001795 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001796 "IR inputs not supported here!");
1797
1798 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001799 AST->TheSema.reset();
1800 AST->Ctx = 0;
1801 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001802 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001803
1804 // Create a file manager object to provide access to and cache the filesystem.
1805 Clang->setFileManager(&AST->getFileManager());
1806
1807 // Create the source manager.
1808 Clang->setSourceManager(&AST->getSourceManager());
1809
1810 ASTFrontendAction *Act = Action;
1811
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001812 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813 if (!Act) {
1814 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1815 Act = TrackerAct.get();
1816 }
1817
1818 // Recover resources if we crash before exiting this method.
1819 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1820 ActCleanup(TrackerAct.get());
1821
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001822 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1823 AST->transferASTDataFromCompilerInstance(*Clang);
1824 if (OwnAST && ErrAST)
1825 ErrAST->swap(OwnAST);
1826
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001827 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001828 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001829
1830 if (Persistent && !TrackerAct) {
1831 Clang->getPreprocessor().addPPCallbacks(
1832 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1833 std::vector<ASTConsumer*> Consumers;
1834 if (Clang->hasASTConsumer())
1835 Consumers.push_back(Clang->takeASTConsumer());
1836 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1837 AST->getCurrentTopLevelHashValue()));
1838 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1839 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001840 if (!Act->Execute()) {
1841 AST->transferASTDataFromCompilerInstance(*Clang);
1842 if (OwnAST && ErrAST)
1843 ErrAST->swap(OwnAST);
1844
1845 return 0;
1846 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001847
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001848 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001849 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001850
1851 Act->EndSourceFile();
1852
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001853 if (OwnAST)
1854 return OwnAST.take();
1855 else
1856 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001857}
1858
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001859bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1860 if (!Invocation)
1861 return true;
1862
1863 // We'll manage file buffers ourselves.
1864 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1865 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001866 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001867
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001868 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001869 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001870 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001871 OverrideMainBuffer
1872 = getMainBufferWithPrecompiledPreamble(*Invocation);
1873 }
1874
Douglas Gregor213f18b2010-10-28 15:44:59 +00001875 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001876 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001877
Ted Kremenek25a11e12011-03-22 01:15:24 +00001878 // Recover resources if we crash before exiting this method.
1879 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1880 MemBufferCleanup(OverrideMainBuffer);
1881
Douglas Gregor213f18b2010-10-28 15:44:59 +00001882 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001883}
1884
Douglas Gregorabc563f2010-07-19 21:46:24 +00001885ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001886 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001887 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001888 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001889 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001890 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001891 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001892 bool IncludeBriefCommentsInCodeCompletion,
1893 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001894 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001895 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001896 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001897 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001898 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001899 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001900 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001901 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001902 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001903 AST->IncludeBriefCommentsInCodeCompletion
1904 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001905 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001906 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001907
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001908 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001909 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1910 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001911 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1912 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001913 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001914
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001915 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001916}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001917
1918ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1919 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001920 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001921 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001922 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001923 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001924 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001925 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001926 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001927 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001928 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001929 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001930 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001931 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001932 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001933 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001934 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001935 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001936 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001937 // No diagnostics engine was provided, so create our own diagnostics object
1938 // with the default options.
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001939 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
1940 ArgEnd - ArgBegin,
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001941 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001942 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001943
Chris Lattner5f9e2722011-07-23 10:55:15 +00001944 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001945
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001946 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001947
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001948 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001949
Douglas Gregore47be3e2010-11-11 00:39:14 +00001950 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001951 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001952
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001953 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001954 llvm::makeArrayRef(ArgBegin, ArgEnd),
1955 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001956 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001957 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001958 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001959
Douglas Gregor4db64a42010-01-23 00:14:00 +00001960 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001961 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1962 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1963 if (const llvm::MemoryBuffer *
1964 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1965 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1966 } else {
1967 const char *fname = fileOrBuf.get<const char *>();
1968 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1969 }
1970 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001971 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1972 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1973 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001974
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001975 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001976 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001977
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001978 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1979
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001980 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001981 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001982 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001983 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001984 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001985 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001986 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001987 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001988 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001989 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001990 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001991 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001992 AST->IncludeBriefCommentsInCodeCompletion
1993 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001994 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001995 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001996 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001997 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001998 if (ForSerialization)
1999 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002000 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002001
2002 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002003 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2004 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002005
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002006 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2007 // Some error occurred, if caller wants to examine diagnostics, pass it the
2008 // ASTUnit.
2009 if (ErrAST) {
2010 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2011 ErrAST->swap(AST);
2012 }
2013 return 0;
2014 }
2015
2016 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002017}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002018
2019bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002020 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002021 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002022
2023 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002024
Douglas Gregor213f18b2010-10-28 15:44:59 +00002025 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002026 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002027
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002028 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002029 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002030 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002031 for (PreprocessorOptions::remapped_file_buffer_iterator
2032 R = PPOpts.remapped_file_buffer_begin(),
2033 REnd = PPOpts.remapped_file_buffer_end();
2034 R != REnd;
2035 ++R) {
2036 delete R->second;
2037 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002038 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002039 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2040 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2041 if (const llvm::MemoryBuffer *
2042 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2043 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2044 memBuf);
2045 } else {
2046 const char *fname = fileOrBuf.get<const char *>();
2047 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2048 fname);
2049 }
2050 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002051
Douglas Gregoreababfb2010-08-04 05:53:38 +00002052 // If we have a preamble file lying around, or if we might try to
2053 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002054 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002055 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002056 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002057
Douglas Gregorabc563f2010-07-19 21:46:24 +00002058 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002059 getDiagnostics().Reset();
2060 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002061 if (OverrideMainBuffer)
2062 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002063
Douglas Gregor175c4a92010-07-23 23:58:40 +00002064 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002065 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002066
2067 // If we're caching global code-completion results, and the top-level
2068 // declarations have changed, clear out the code-completion cache.
2069 if (!Result && ShouldCacheCodeCompletionResults &&
2070 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2071 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002072
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002073 // We now need to clear out the completion info related to this translation
2074 // unit; it'll be recreated if necessary.
2075 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002076
Douglas Gregor175c4a92010-07-23 23:58:40 +00002077 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002078}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002079
Douglas Gregor87c08a52010-08-13 22:48:40 +00002080//----------------------------------------------------------------------------//
2081// Code completion
2082//----------------------------------------------------------------------------//
2083
2084namespace {
2085 /// \brief Code completion consumer that combines the cached code-completion
2086 /// results from an ASTUnit with the code-completion results provided to it,
2087 /// then passes the result on to
2088 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002089 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002090 ASTUnit &AST;
2091 CodeCompleteConsumer &Next;
2092
2093 public:
2094 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002095 const CodeCompleteOptions &CodeCompleteOpts)
2096 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2097 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002098 {
2099 // Compute the set of contexts in which we will look when we don't have
2100 // any information about the specific context.
2101 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002102 = (1LL << CodeCompletionContext::CCC_TopLevel)
2103 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2104 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2105 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2106 | (1LL << CodeCompletionContext::CCC_Statement)
2107 | (1LL << CodeCompletionContext::CCC_Expression)
2108 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2109 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2110 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2111 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2112 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2113 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2114 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002115
David Blaikie4e4d0842012-03-11 07:00:24 +00002116 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002117 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2118 | (1LL << CodeCompletionContext::CCC_UnionTag)
2119 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002120 }
2121
2122 virtual void ProcessCodeCompleteResults(Sema &S,
2123 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002124 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002125 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002126
2127 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2128 OverloadCandidate *Candidates,
2129 unsigned NumCandidates) {
2130 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2131 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002132
Douglas Gregordae68752011-02-01 22:57:45 +00002133 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002134 return Next.getAllocator();
2135 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002136
2137 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2138 return Next.getCodeCompletionTUInfo();
2139 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002140 };
2141}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002142
Douglas Gregor5f808c22010-08-16 21:18:39 +00002143/// \brief Helper function that computes which global names are hidden by the
2144/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002145static void CalculateHiddenNames(const CodeCompletionContext &Context,
2146 CodeCompletionResult *Results,
2147 unsigned NumResults,
2148 ASTContext &Ctx,
2149 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002150 bool OnlyTagNames = false;
2151 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002152 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002153 case CodeCompletionContext::CCC_TopLevel:
2154 case CodeCompletionContext::CCC_ObjCInterface:
2155 case CodeCompletionContext::CCC_ObjCImplementation:
2156 case CodeCompletionContext::CCC_ObjCIvarList:
2157 case CodeCompletionContext::CCC_ClassStructUnion:
2158 case CodeCompletionContext::CCC_Statement:
2159 case CodeCompletionContext::CCC_Expression:
2160 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002161 case CodeCompletionContext::CCC_DotMemberAccess:
2162 case CodeCompletionContext::CCC_ArrowMemberAccess:
2163 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002164 case CodeCompletionContext::CCC_Namespace:
2165 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002166 case CodeCompletionContext::CCC_Name:
2167 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002168 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002169 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002170 break;
2171
2172 case CodeCompletionContext::CCC_EnumTag:
2173 case CodeCompletionContext::CCC_UnionTag:
2174 case CodeCompletionContext::CCC_ClassOrStructTag:
2175 OnlyTagNames = true;
2176 break;
2177
2178 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002179 case CodeCompletionContext::CCC_MacroName:
2180 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002181 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002182 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002183 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002184 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002185 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002186 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002187 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002188 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2189 case CodeCompletionContext::CCC_ObjCClassMessage:
2190 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002191 // We're looking for nothing, or we're looking for names that cannot
2192 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002193 return;
2194 }
2195
John McCall0a2c5e22010-08-25 06:19:51 +00002196 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002197 for (unsigned I = 0; I != NumResults; ++I) {
2198 if (Results[I].Kind != Result::RK_Declaration)
2199 continue;
2200
2201 unsigned IDNS
2202 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2203
2204 bool Hiding = false;
2205 if (OnlyTagNames)
2206 Hiding = (IDNS & Decl::IDNS_Tag);
2207 else {
2208 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002209 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2210 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002211 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002212 HiddenIDNS |= Decl::IDNS_Tag;
2213 Hiding = (IDNS & HiddenIDNS);
2214 }
2215
2216 if (!Hiding)
2217 continue;
2218
2219 DeclarationName Name = Results[I].Declaration->getDeclName();
2220 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2221 HiddenNames.insert(Identifier->getName());
2222 else
2223 HiddenNames.insert(Name.getAsString());
2224 }
2225}
2226
2227
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002228void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2229 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002230 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002231 unsigned NumResults) {
2232 // Merge the results we were given with the results we cached.
2233 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002234 uint64_t InContexts =
2235 Context.getKind() == CodeCompletionContext::CCC_Recovery
2236 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002237 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002238 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002239 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002240 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002241 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002242 C = AST.cached_completion_begin(),
2243 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002244 C != CEnd; ++C) {
2245 // If the context we are in matches any of the contexts we are
2246 // interested in, we'll add this result.
2247 if ((C->ShowInContexts & InContexts) == 0)
2248 continue;
2249
2250 // If we haven't added any results previously, do so now.
2251 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002252 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2253 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002254 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2255 AddedResult = true;
2256 }
2257
Douglas Gregor5f808c22010-08-16 21:18:39 +00002258 // Determine whether this global completion result is hidden by a local
2259 // completion result. If so, skip it.
2260 if (C->Kind != CXCursor_MacroDefinition &&
2261 HiddenNames.count(C->Completion->getTypedText()))
2262 continue;
2263
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002264 // Adjust priority based on similar type classes.
2265 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002266 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002267 if (!Context.getPreferredType().isNull()) {
2268 if (C->Kind == CXCursor_MacroDefinition) {
2269 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002270 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002271 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002272 } else if (C->Type) {
2273 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002274 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002275 Context.getPreferredType().getUnqualifiedType());
2276 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2277 if (ExpectedSTC == C->TypeClass) {
2278 // We know this type is similar; check for an exact match.
2279 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002280 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002281 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002282 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002283 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2284 Priority /= CCF_ExactTypeMatch;
2285 else
2286 Priority /= CCF_SimilarTypeMatch;
2287 }
2288 }
2289 }
2290
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002291 // Adjust the completion string, if required.
2292 if (C->Kind == CXCursor_MacroDefinition &&
2293 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2294 // Create a new code-completion string that just contains the
2295 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002296 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2297 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002298 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002299 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002300 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002301 }
2302
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002303 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002304 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002305 }
2306
2307 // If we did not add any cached completion results, just forward the
2308 // results we were given to the next consumer.
2309 if (!AddedResult) {
2310 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2311 return;
2312 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002313
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002314 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2315 AllResults.size());
2316}
2317
2318
2319
Chris Lattner5f9e2722011-07-23 10:55:15 +00002320void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002321 RemappedFile *RemappedFiles,
2322 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002323 bool IncludeMacros,
2324 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002325 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002326 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002327 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002328 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002329 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2330 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002331 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002332 return;
2333
Douglas Gregor213f18b2010-10-28 15:44:59 +00002334 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002335 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002336 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002337
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002338 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002339 CCInvocation(new CompilerInvocation(*Invocation));
2340
2341 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002342 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002343 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002344
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002345 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2346 CachedCompletionResults.empty();
2347 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2348 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2349 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2350
2351 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2352
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002353 FrontendOpts.CodeCompletionAt.FileName = File;
2354 FrontendOpts.CodeCompletionAt.Line = Line;
2355 FrontendOpts.CodeCompletionAt.Column = Column;
2356
2357 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002358 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002359
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002360 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002361
2362 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002363 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2364 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002365
Ted Kremenek4f327862011-03-21 18:40:17 +00002366 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002367 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368
2369 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002370 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002371 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002372 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002373 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002374 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375
2376 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002377 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2378 Clang->getTargetOpts()));
2379 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002380 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002381 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382 }
2383
2384 // Inform the target of the language options.
2385 //
2386 // FIXME: We shouldn't need to do this, the target should be immutable once
2387 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002388 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002389
Ted Kremenek03201fb2011-03-21 18:40:07 +00002390 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002391 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002392 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002393 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002394 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002395 "IR inputs not support here!");
2396
2397
2398 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002399 Clang->setFileManager(&FileMgr);
2400 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002401
2402 // Remap files.
2403 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002404 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002405 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002406 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2407 if (const llvm::MemoryBuffer *
2408 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2409 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2410 OwnedBuffers.push_back(memBuf);
2411 } else {
2412 const char *fname = fileOrBuf.get<const char *>();
2413 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2414 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002415 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416
Douglas Gregor87c08a52010-08-13 22:48:40 +00002417 // Use the code completion consumer we were given, but adding any cached
2418 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002419 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002420 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002421 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002422
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002423 Clang->getFrontendOpts().SkipFunctionBodies = true;
2424
Douglas Gregordf95a132010-08-09 20:45:32 +00002425 // If we have a precompiled preamble, try to use it. We only allow
2426 // the use of the precompiled preamble if we're if the completion
2427 // point is within the main file, after the end of the precompiled
2428 // preamble.
2429 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002430 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002431 using llvm::sys::FileStatus;
2432 llvm::sys::PathWithStatus CompleteFilePath(File);
2433 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2434 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2435 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002436 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2437 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002438 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002439 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002440 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002441 }
2442
2443 // If the main file has been overridden due to the use of a preamble,
2444 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002445 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002446 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002447 stored_diag_begin(),
2448 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002449 if (OverrideMainBuffer) {
2450 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2451 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2452 PreprocessorOpts.PrecompiledPreambleBytes.second
2453 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002454 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002455 PreprocessorOpts.DisablePCHValidation = true;
2456
Douglas Gregor2283d792010-08-20 00:59:43 +00002457 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002458 } else {
2459 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2460 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002461 }
2462
Douglas Gregordca8ee82011-05-06 16:33:08 +00002463 // Disable the preprocessing record
2464 PreprocessorOpts.DetailedRecord = false;
2465
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002466 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002467 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002468 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002469 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002470 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002471 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2472 getSourceManager(), PreambleDiagnostics,
2473 StoredDiagnostics);
2474 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002475 Act->Execute();
2476 Act->EndSourceFile();
2477 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002478
2479 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002480}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002481
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002482bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002483 // Write to a temporary file and later rename it to the actual file, to avoid
2484 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002485 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002486 TempPath = File;
2487 TempPath += "-%%%%%%%%";
2488 int fd;
2489 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2490 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002491 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002492
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002493 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2494 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002495 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002496
2497 serialize(Out);
2498 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002499 if (Out.has_error()) {
2500 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002501 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002502 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002503
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002504 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002505 bool exists;
2506 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002507 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002508 }
2509
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002510 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002511}
2512
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002513static bool serializeUnit(ASTWriter &Writer,
2514 SmallVectorImpl<char> &Buffer,
2515 Sema &S,
2516 bool hasErrors,
2517 raw_ostream &OS) {
2518 Writer.WriteAST(S, 0, std::string(), 0, "", hasErrors);
2519
2520 // Write the generated bitstream to "Out".
2521 if (!Buffer.empty())
2522 OS.write(Buffer.data(), Buffer.size());
2523
2524 return false;
2525}
2526
Chris Lattner5f9e2722011-07-23 10:55:15 +00002527bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002528 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002529
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002530 if (WriterData)
2531 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2532 getSema(), hasErrors, OS);
2533
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002534 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002535 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002536 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002537 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002538}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002539
2540typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2541
2542static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2543 unsigned Raw = L.getRawEncoding();
2544 const unsigned MacroBit = 1U << 31;
2545 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2546 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2547}
2548
2549void ASTUnit::TranslateStoredDiagnostics(
2550 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002551 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002552 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002553 const SmallVectorImpl<StoredDiagnostic> &Diags,
2554 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002555 // The stored diagnostic has the old source manager in it; update
2556 // the locations to refer into the new source manager. We also need to remap
2557 // all the locations to the new view. This includes the diag location, any
2558 // associated source ranges, and the source ranges of associated fix-its.
2559 // FIXME: There should be a cleaner way to do this.
2560
Chris Lattner5f9e2722011-07-23 10:55:15 +00002561 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002562 Result.reserve(Diags.size());
2563 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002564 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002565 assert(Mod && "Don't have preamble module");
2566 SLocRemap &Remap = Mod->SLocRemap;
2567 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2568 // Rebuild the StoredDiagnostic.
2569 const StoredDiagnostic &SD = Diags[I];
2570 SourceLocation L = SD.getLocation();
2571 TranslateSLoc(L, Remap);
2572 FullSourceLoc Loc(L, SrcMgr);
2573
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002575 Ranges.reserve(SD.range_size());
2576 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2577 E = SD.range_end();
2578 I != E; ++I) {
2579 SourceLocation BL = I->getBegin();
2580 TranslateSLoc(BL, Remap);
2581 SourceLocation EL = I->getEnd();
2582 TranslateSLoc(EL, Remap);
2583 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2584 }
2585
Chris Lattner5f9e2722011-07-23 10:55:15 +00002586 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002587 FixIts.reserve(SD.fixit_size());
2588 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2589 E = SD.fixit_end();
2590 I != E; ++I) {
2591 FixIts.push_back(FixItHint());
2592 FixItHint &FH = FixIts.back();
2593 FH.CodeToInsert = I->CodeToInsert;
2594 SourceLocation BL = I->RemoveRange.getBegin();
2595 TranslateSLoc(BL, Remap);
2596 SourceLocation EL = I->RemoveRange.getEnd();
2597 TranslateSLoc(EL, Remap);
2598 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2599 I->RemoveRange.isTokenRange());
2600 }
2601
2602 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2603 SD.getMessage(), Loc, Ranges, FixIts));
2604 }
2605 Result.swap(Out);
2606}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002607
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002608static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2609 std::pair<unsigned, Decl *> R) {
2610 return L.first < R.first;
2611}
2612
2613void ASTUnit::addFileLevelDecl(Decl *D) {
2614 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002615
2616 // We only care about local declarations.
2617 if (D->isFromASTFile())
2618 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002619
2620 SourceManager &SM = *SourceMgr;
2621 SourceLocation Loc = D->getLocation();
2622 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2623 return;
2624
2625 // We only keep track of the file-level declarations of each file.
2626 if (!D->getLexicalDeclContext()->isFileContext())
2627 return;
2628
2629 SourceLocation FileLoc = SM.getFileLoc(Loc);
2630 assert(SM.isLocalSourceLocation(FileLoc));
2631 FileID FID;
2632 unsigned Offset;
2633 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2634 if (FID.isInvalid())
2635 return;
2636
2637 LocDeclsTy *&Decls = FileDecls[FID];
2638 if (!Decls)
2639 Decls = new LocDeclsTy();
2640
2641 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2642
2643 if (Decls->empty() || Decls->back().first <= Offset) {
2644 Decls->push_back(LocDecl);
2645 return;
2646 }
2647
2648 LocDeclsTy::iterator
2649 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2650
2651 Decls->insert(I, LocDecl);
2652}
2653
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002654void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2655 SmallVectorImpl<Decl *> &Decls) {
2656 if (File.isInvalid())
2657 return;
2658
2659 if (SourceMgr->isLoadedFileID(File)) {
2660 assert(Ctx->getExternalSource() && "No external source!");
2661 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2662 Decls);
2663 }
2664
2665 FileDeclsTy::iterator I = FileDecls.find(File);
2666 if (I == FileDecls.end())
2667 return;
2668
2669 LocDeclsTy &LocDecls = *I->second;
2670 if (LocDecls.empty())
2671 return;
2672
2673 LocDeclsTy::iterator
2674 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2675 std::make_pair(Offset, (Decl*)0), compLocDecl);
2676 if (BeginIt != LocDecls.begin())
2677 --BeginIt;
2678
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002679 // If we are pointing at a top-level decl inside an objc container, we need
2680 // to backtrack until we find it otherwise we will fail to report that the
2681 // region overlaps with an objc container.
2682 while (BeginIt != LocDecls.begin() &&
2683 BeginIt->second->isTopLevelDeclInObjCContainer())
2684 --BeginIt;
2685
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002686 LocDeclsTy::iterator
2687 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2688 std::make_pair(Offset+Length, (Decl*)0),
2689 compLocDecl);
2690 if (EndIt != LocDecls.end())
2691 ++EndIt;
2692
2693 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2694 Decls.push_back(DIt->second);
2695}
2696
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002697SourceLocation ASTUnit::getLocation(const FileEntry *File,
2698 unsigned Line, unsigned Col) const {
2699 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002700 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002701 return SM.getMacroArgExpandedLocation(Loc);
2702}
2703
2704SourceLocation ASTUnit::getLocation(const FileEntry *File,
2705 unsigned Offset) const {
2706 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002707 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002708 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2709}
2710
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002711/// \brief If \arg Loc is a loaded location from the preamble, returns
2712/// the corresponding local location of the main file, otherwise it returns
2713/// \arg Loc.
2714SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2715 FileID PreambleID;
2716 if (SourceMgr)
2717 PreambleID = SourceMgr->getPreambleFileID();
2718
2719 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2720 return Loc;
2721
2722 unsigned Offs;
2723 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2724 SourceLocation FileLoc
2725 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2726 return FileLoc.getLocWithOffset(Offs);
2727 }
2728
2729 return Loc;
2730}
2731
2732/// \brief If \arg Loc is a local location of the main file but inside the
2733/// preamble chunk, returns the corresponding loaded location from the
2734/// preamble, otherwise it returns \arg Loc.
2735SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2736 FileID PreambleID;
2737 if (SourceMgr)
2738 PreambleID = SourceMgr->getPreambleFileID();
2739
2740 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2741 return Loc;
2742
2743 unsigned Offs;
2744 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2745 Offs < Preamble.size()) {
2746 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2747 return FileLoc.getLocWithOffset(Offs);
2748 }
2749
2750 return Loc;
2751}
2752
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002753bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2754 FileID FID;
2755 if (SourceMgr)
2756 FID = SourceMgr->getPreambleFileID();
2757
2758 if (Loc.isInvalid() || FID.isInvalid())
2759 return false;
2760
2761 return SourceMgr->isInFileID(Loc, FID);
2762}
2763
2764bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2765 FileID FID;
2766 if (SourceMgr)
2767 FID = SourceMgr->getMainFileID();
2768
2769 if (Loc.isInvalid() || FID.isInvalid())
2770 return false;
2771
2772 return SourceMgr->isInFileID(Loc, FID);
2773}
2774
2775SourceLocation ASTUnit::getEndOfPreambleFileID() {
2776 FileID FID;
2777 if (SourceMgr)
2778 FID = SourceMgr->getPreambleFileID();
2779
2780 if (FID.isInvalid())
2781 return SourceLocation();
2782
2783 return SourceMgr->getLocForEndOfFile(FID);
2784}
2785
2786SourceLocation ASTUnit::getStartOfMainFileID() {
2787 FileID FID;
2788 if (SourceMgr)
2789 FID = SourceMgr->getMainFileID();
2790
2791 if (FID.isInvalid())
2792 return SourceLocation();
2793
2794 return SourceMgr->getLocForStartOfFile(FID);
2795}
2796
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002797std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2798ASTUnit::getLocalPreprocessingEntities() const {
2799 if (isMainFileAST()) {
2800 serialization::ModuleFile &
2801 Mod = Reader->getModuleManager().getPrimaryModule();
2802 return Reader->getModulePreprocessedEntities(Mod);
2803 }
2804
2805 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2806 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2807
2808 return std::make_pair(PreprocessingRecord::iterator(),
2809 PreprocessingRecord::iterator());
2810}
2811
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002812bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002813 if (isMainFileAST()) {
2814 serialization::ModuleFile &
2815 Mod = Reader->getModuleManager().getPrimaryModule();
2816 ASTReader::ModuleDeclIterator MDI, MDE;
2817 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2818 for (; MDI != MDE; ++MDI) {
2819 if (!Fn(context, *MDI))
2820 return false;
2821 }
2822
2823 return true;
2824 }
2825
2826 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2827 TLEnd = top_level_end();
2828 TL != TLEnd; ++TL) {
2829 if (!Fn(context, *TL))
2830 return false;
2831 }
2832
2833 return true;
2834}
2835
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002836namespace {
2837struct PCHLocatorInfo {
2838 serialization::ModuleFile *Mod;
2839 PCHLocatorInfo() : Mod(0) {}
2840};
2841}
2842
2843static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2844 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2845 switch (M.Kind) {
2846 case serialization::MK_Module:
2847 return true; // skip dependencies.
2848 case serialization::MK_PCH:
2849 Info.Mod = &M;
2850 return true; // found it.
2851 case serialization::MK_Preamble:
2852 return false; // look in dependencies.
2853 case serialization::MK_MainFile:
2854 return false; // look in dependencies.
2855 }
2856
2857 return true;
2858}
2859
2860const FileEntry *ASTUnit::getPCHFile() {
2861 if (!Reader)
2862 return 0;
2863
2864 PCHLocatorInfo Info;
2865 Reader->getModuleManager().visit(PCHLocator, &Info);
2866 if (Info.Mod)
2867 return Info.Mod->File;
2868
2869 return 0;
2870}
2871
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002872bool ASTUnit::isModuleFile() {
2873 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2874}
2875
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002876void ASTUnit::PreambleData::countLines() const {
2877 NumLines = 0;
2878 if (empty())
2879 return;
2880
2881 for (std::vector<char>::const_iterator
2882 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2883 if (*I == '\n')
2884 ++NumLines;
2885 }
2886 if (Buffer.back() != '\n')
2887 ++NumLines;
2888}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002889
2890#ifndef NDEBUG
2891ASTUnit::ConcurrencyState::ConcurrencyState() {
2892 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2893}
2894
2895ASTUnit::ConcurrencyState::~ConcurrencyState() {
2896 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2897}
2898
2899void ASTUnit::ConcurrencyState::start() {
2900 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2901 assert(acquired && "Concurrent access to ASTUnit!");
2902}
2903
2904void ASTUnit::ConcurrencyState::finish() {
2905 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2906}
2907
2908#else // NDEBUG
2909
2910ASTUnit::ConcurrencyState::ConcurrencyState() {}
2911ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2912void ASTUnit::ConcurrencyState::start() {}
2913void ASTUnit::ConcurrencyState::finish() {}
2914
2915#endif