blob: 6a4f0eb6d73842647d27351643a796e5cbd0c8a0 [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"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000033#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000036#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000042#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000045#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000046#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000048#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000049using namespace clang;
50
Douglas Gregor213f18b2010-10-28 15:44:59 +000051using llvm::TimeRecord;
52
53namespace {
54 class SimpleTimer {
55 bool WantTiming;
56 TimeRecord Start;
57 std::string Output;
58
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000059 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000060 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 }
64
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000067 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 }
69
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 ~SimpleTimer() {
71 if (WantTiming) {
72 TimeRecord Elapsed = TimeRecord::getCurrentTime();
73 Elapsed -= Start;
74 llvm::errs() << Output << ':';
75 Elapsed.print(Elapsed, llvm::errs());
76 llvm::errs() << '\n';
77 }
78 }
79 };
Ted Kremenek1872b312011-10-27 17:55:18 +000080
81 struct OnDiskData {
82 /// \brief The file in which the precompiled preamble is stored.
83 std::string PreambleFile;
84
85 /// \brief Temporary files that should be removed when the ASTUnit is
86 /// destroyed.
87 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
88
89 /// \brief Erase temporary files.
90 void CleanTemporaryFiles();
91
92 /// \brief Erase the preamble file.
93 void CleanPreambleFile();
94
95 /// \brief Erase temporary files and the preamble file.
96 void Cleanup();
97 };
98}
99
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000100static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
101 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
102 return M;
103}
104
Ted Kremenek1872b312011-10-27 17:55:18 +0000105static void cleanupOnDiskMapAtExit(void);
106
107typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
108static OnDiskDataMap &getOnDiskDataMap() {
109 static OnDiskDataMap M;
110 static bool hasRegisteredAtExit = false;
111 if (!hasRegisteredAtExit) {
112 hasRegisteredAtExit = true;
113 atexit(cleanupOnDiskMapAtExit);
114 }
115 return M;
116}
117
118static void cleanupOnDiskMapAtExit(void) {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000119 // Use the mutex because there can be an alive thread destroying an ASTUnit.
120 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000121 OnDiskDataMap &M = getOnDiskDataMap();
122 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
123 // We don't worry about freeing the memory associated with OnDiskDataMap.
124 // All we care about is erasing stale files.
125 I->second->Cleanup();
126 }
127}
128
129static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000130 // We require the mutex since we are modifying the structure of the
131 // DenseMap.
132 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000133 OnDiskDataMap &M = getOnDiskDataMap();
134 OnDiskData *&D = M[AU];
135 if (!D)
136 D = new OnDiskData();
137 return *D;
138}
139
140static void erasePreambleFile(const ASTUnit *AU) {
141 getOnDiskData(AU).CleanPreambleFile();
142}
143
144static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000145 // We require the mutex since we are modifying the structure of the
146 // DenseMap.
147 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000148 OnDiskDataMap &M = getOnDiskDataMap();
149 OnDiskDataMap::iterator I = M.find(AU);
150 if (I != M.end()) {
151 I->second->Cleanup();
152 delete I->second;
153 M.erase(AU);
154 }
155}
156
157static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
158 getOnDiskData(AU).PreambleFile = preambleFile;
159}
160
161static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
163}
164
165void OnDiskData::CleanTemporaryFiles() {
166 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
167 TemporaryFiles[I].eraseFromDisk();
168 TemporaryFiles.clear();
169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
173 llvm::sys::Path(PreambleFile).eraseFromDisk();
174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000183void ASTUnit::clearFileLevelDecls() {
184 for (FileDeclsTy::iterator
185 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
186 delete I->second;
187 FileDecls.clear();
188}
189
Ted Kremenek1872b312011-10-27 17:55:18 +0000190void ASTUnit::CleanTemporaryFiles() {
191 getOnDiskData(this).CleanTemporaryFiles();
192}
193
194void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
195 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000196}
197
Douglas Gregoreababfb2010-08-04 05:53:38 +0000198/// \brief After failing to build a precompiled preamble (due to
199/// errors in the source that occurs in the preamble), the number of
200/// reparses during which we'll skip even trying to precompile the
201/// preamble.
202const unsigned DefaultPreambleRebuildInterval = 5;
203
Douglas Gregore3c60a72010-11-17 00:13:31 +0000204/// \brief Tracks the number of ASTUnit objects that are currently active.
205///
206/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000207static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000208
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000209ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000210 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000211 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000212 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000213 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000214 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000215 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000216 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000217 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000218 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000219 CompletionCacheTopLevelHashValue(0),
220 PreambleTopLevelHashValue(0),
221 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000222 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000223 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000224 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000225 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
226 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000227}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000228
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000229ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000230 clearFileLevelDecls();
231
Ted Kremenek1872b312011-10-27 17:55:18 +0000232 // Clean up the temporary files and the preamble file.
233 removeOnDiskEntry(this);
234
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000235 // Free the buffers associated with remapped files. We are required to
236 // perform this operation here because we explicitly request that the
237 // compiler instance *not* free these buffers for each invocation of the
238 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000239 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000240 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
241 for (PreprocessorOptions::remapped_file_buffer_iterator
242 FB = PPOpts.remapped_file_buffer_begin(),
243 FBEnd = PPOpts.remapped_file_buffer_end();
244 FB != FBEnd;
245 ++FB)
246 delete FB->second;
247 }
Douglas Gregor28233422010-07-27 14:52:07 +0000248
249 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000250 delete PreambleBuffer;
251
Douglas Gregor213f18b2010-10-28 15:44:59 +0000252 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000253
254 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000255 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000256 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
257 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000258}
259
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000260void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
261
Douglas Gregor8071e422010-08-15 06:18:01 +0000262/// \brief Determine the set of code-completion contexts in which this
263/// declaration should be shown.
264static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
268
Douglas Gregor8071e422010-08-15 06:18:01 +0000269 if (isa<UsingShadowDecl>(ND))
270 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
271 if (!ND)
272 return 0;
273
Richard Smith026b3582012-08-14 03:13:00 +0000274 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
277 // Types can appear in these contexts.
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000279 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
280 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
281 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
282 | (1LL << CodeCompletionContext::CCC_Statement)
283 | (1LL << CodeCompletionContext::CCC_Type)
284 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000285
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000289
290 // In Objective-C, message sends can send interfaces. In Objective-C++,
291 // all types are available due to functional casts.
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000294
295 // In Objective-C, you can only be a subclass of another Objective-C class
296 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000298
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000302
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000303 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000304 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000306 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
307 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 else
Richard Smith026b3582012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000311
Douglas Gregor8071e422010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000314 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000315 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
317 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000318 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
319 | (1LL << CodeCompletionContext::CCC_Expression)
320 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
321 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000322 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000324 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000328
329 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 }
332
333 return Contexts;
334}
335
Douglas Gregor87c08a52010-08-13 22:48:40 +0000336void ASTUnit::CacheCodeCompletionResults() {
337 if (!TheSema)
338 return;
339
Douglas Gregor213f18b2010-10-28 15:44:59 +0000340 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000341 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000342
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
345
346 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000347 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000348 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000350 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
351 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352
353 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000354 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
355
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
357 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000358 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000359 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000360 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000361 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000362 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000363 getCodeCompletionTUInfo(),
364 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000365 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000366 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000367 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedResult.Priority = Results[I].Priority;
369 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000370 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000371
Douglas Gregorf5586f62010-08-16 18:08:11 +0000372 // Keep track of the type of this completion in an ASTContext-agnostic
373 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000374 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000375 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000376 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000377 CachedResult.Type = 0;
378 } else {
379 CanQualType CanUsageType
380 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
381 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
382
383 // Determine whether we have already seen this type. If so, we save
384 // ourselves the work of formatting the type string by using the
385 // temporary, CanQualType-based hash table to find the associated value.
386 unsigned &TypeValue = CompletionTypes[CanUsageType];
387 if (TypeValue == 0) {
388 TypeValue = CompletionTypes.size();
389 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
390 = TypeValue;
391 }
392
393 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000394 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000395
Douglas Gregor8071e422010-08-15 06:18:01 +0000396 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000397
398 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000399 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000400 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
401 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000402 uint64_t NNSContexts
403 = (1LL << CodeCompletionContext::CCC_TopLevel)
404 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
405 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
406 | (1LL << CodeCompletionContext::CCC_Statement)
407 | (1LL << CodeCompletionContext::CCC_Expression)
408 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
409 | (1LL << CodeCompletionContext::CCC_EnumTag)
410 | (1LL << CodeCompletionContext::CCC_UnionTag)
411 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
412 | (1LL << CodeCompletionContext::CCC_Type)
413 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
414 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415
416 if (isa<NamespaceDecl>(Results[I].Declaration) ||
417 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000418 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000419
420 if (unsigned RemainingContexts
421 = NNSContexts & ~CachedResult.ShowInContexts) {
422 // If there any contexts where this completion can be a
423 // nested-name-specifier but isn't already an option, create a
424 // nested-name-specifier completion.
425 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000426 CachedResult.Completion
427 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000428 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000429 getCodeCompletionTUInfo(),
430 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000431 CachedResult.ShowInContexts = RemainingContexts;
432 CachedResult.Priority = CCP_NestedNameSpecifier;
433 CachedResult.TypeClass = STC_Void;
434 CachedResult.Type = 0;
435 CachedCompletionResults.push_back(CachedResult);
436 }
437 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000438 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000439 }
440
Douglas Gregor87c08a52010-08-13 22:48:40 +0000441 case Result::RK_Keyword:
442 case Result::RK_Pattern:
443 // Ignore keywords and patterns; we don't care, since they are so
444 // easily regenerated.
445 break;
446
447 case Result::RK_Macro: {
448 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000449 CachedResult.Completion
450 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000451 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000452 getCodeCompletionTUInfo(),
453 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000454 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000455 = (1LL << CodeCompletionContext::CCC_TopLevel)
456 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
457 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
458 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
459 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
460 | (1LL << CodeCompletionContext::CCC_Statement)
461 | (1LL << CodeCompletionContext::CCC_Expression)
462 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
463 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
464 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
465 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
466 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000467
Douglas Gregor87c08a52010-08-13 22:48:40 +0000468 CachedResult.Priority = Results[I].Priority;
469 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000470 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000471 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000472 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000473 CachedCompletionResults.push_back(CachedResult);
474 break;
475 }
476 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000477 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000478
479 // Save the current top-level hash value.
480 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481}
482
483void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000484 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000485 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000486 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000487}
488
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000489namespace {
490
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000491/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000492/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000493class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000494 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000495 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000496 LangOptions &LangOpt;
497 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000498 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499 std::string &Predefines;
500 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000504 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000505public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000506 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
507 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000512 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000515 virtual bool ReadLanguageOptions(const serialization::ModuleFile &M,
516 const LangOptions &LangOpts) {
517 if (InitializedLanguage || M.Kind != serialization::MK_MainFile)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000518 return false;
519
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000521
522 // Initialize the preprocessor.
523 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000524
525 // Initialize the ASTContext
526 Context.InitBuiltinTypes(*Target);
527
528 InitializedLanguage = true;
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000529
530 applyLangOptsToTarget();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000531 return false;
532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000534 virtual bool ReadTargetTriple(const serialization::ModuleFile &M,
535 StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000536 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000537 if (Target || M.Kind != serialization::MK_MainFile)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000538 return false;
539
540 // FIXME: This is broken, we should store the TargetOptions in the AST file.
541 TargetOptions TargetOpts;
542 TargetOpts.ABI = "";
543 TargetOpts.CXXABI = "";
544 TargetOpts.CPU = "";
545 TargetOpts.Features.clear();
546 TargetOpts.Triple = Triple;
547 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000548
549 applyLangOptsToTarget();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000550 return false;
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000553 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000554 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000555 std::string &SuggestedPredefines,
556 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000557 Predefines = Buffers[0].Data;
558 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
559 Predefines += Buffers[I].Data;
560 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000561 return false;
562 }
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000564 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000565 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000568 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000569 Counter = Value;
570 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000571
572private:
573 void applyLangOptsToTarget() {
574 if (Target && InitializedLanguage) {
575 // Inform the target of the language options.
576 //
577 // FIXME: We shouldn't need to do this, the target should be immutable once
578 // created. This complexity should be lifted elsewhere.
579 Target->setForcedLangOptions(LangOpt);
580 }
581 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000582};
583
David Blaikie26e7a902011-09-26 00:01:39 +0000584class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000586
587public:
David Blaikie26e7a902011-09-26 00:01:39 +0000588 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000590 : StoredDiags(StoredDiags) { }
591
David Blaikied6471f72011-09-25 23:23:43 +0000592 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000593 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000594
595 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
596 // Just drop any diagnostics that come from cloned consumers; they'll
597 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000598 // FIXME: We'd like to be able to capture these somehow, even if it's just
599 // file/line/column, because they could occur when parsing module maps or
600 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000601 return new IgnoringDiagConsumer();
602 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000603};
604
605/// \brief RAII object that optionally captures diagnostics, if
606/// there is no diagnostic client to capture them already.
607class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000608 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000609 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000610 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000611
612public:
David Blaikied6471f72011-09-25 23:23:43 +0000613 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000614 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000615 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000616 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000617 if (RequestCapture || Diags.getClient() == 0) {
618 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000619 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000620 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000621 }
622
623 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000624 if (Diags.getClient() == &Client) {
625 Diags.takeClient();
626 Diags.setClient(PreviousClient);
627 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000628 }
629};
630
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000631} // anonymous namespace
632
David Blaikie26e7a902011-09-26 00:01:39 +0000633void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000634 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000635 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000636 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000637
Douglas Gregora88084b2010-02-18 18:08:43 +0000638 StoredDiags.push_back(StoredDiagnostic(Level, Info));
639}
640
Steve Naroff77accc12009-09-03 18:19:54 +0000641const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000642 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000643}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000644
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.
658 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000659 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000660 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000661 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000662 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
663 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 Gregor8e238062011-11-11 00:35:06 +0000699 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000700 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000701 AST->ASTFileLangOpts,
702 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000703
Douglas Gregor4db64a42010-01-23 00:14:00 +0000704 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000705 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
706 if (const llvm::MemoryBuffer *
707 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
708 // Create the file entry for the file that we're mapping from.
709 const FileEntry *FromFile
710 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
711 memBuf->getBufferSize(),
712 0);
713 if (!FromFile) {
714 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
715 << RemappedFiles[I].first;
716 delete memBuf;
717 continue;
718 }
719
720 // Override the contents of the "from" file with the contents of
721 // the "to" file.
722 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
723
724 } else {
725 const char *fname = fileOrBuf.get<const char *>();
726 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
727 if (!ToFile) {
728 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
729 << RemappedFiles[I].first << fname;
730 continue;
731 }
732
733 // Create the file entry for the file that we're mapping from.
734 const FileEntry *FromFile
735 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
736 ToFile->getSize(),
737 0);
738 if (!FromFile) {
739 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
740 << RemappedFiles[I].first;
741 delete memBuf;
742 continue;
743 }
744
745 // Override the contents of the "from" file with the contents of
746 // the "to" file.
747 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000748 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000749 }
750
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000751 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000753 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000754 std::string Predefines;
755 unsigned Counter;
756
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000757 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000758
Douglas Gregor998b3d32011-09-01 23:39:15 +0000759 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
760 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
761 *AST,
762 /*IILookup=*/0,
763 /*OwnsHeaderSearch=*/false,
764 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000765 Preprocessor &PP = *AST->PP;
766
767 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
768 AST->getSourceManager(),
769 /*Target=*/0,
770 PP.getIdentifierTable(),
771 PP.getSelectorTable(),
772 PP.getBuiltinInfo(),
773 /* size_reserve = */0,
774 /*DelayInitialization=*/true);
775 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000776
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000777 bool disableValid = false;
778 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
779 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000780 Reader.reset(new ASTReader(PP, Context,
781 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000782 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000783 /*DisableStatCache=*/false,
784 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000785
786 // Recover resources if we crash before exiting this method.
787 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
788 ReaderCleanup(Reader.get());
789
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000790 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000791 AST->ASTFileLangOpts, HeaderInfo,
792 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000793
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000794 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000795 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000796 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000798 case ASTReader::Failure:
799 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000800 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000801 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000802 }
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000804 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
805
Daniel Dunbard5b61262009-09-21 03:03:47 +0000806 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000807 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000809 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000810 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000811 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000812 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000813 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000814
815 // Unregister the cleanup for ASTReader. It will get cleaned up
816 // by the ASTUnit cleanup.
817 ReaderCleanup.unregister();
818
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000819 Context.setExternalSource(Source);
820
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000821 // Create an AST consumer, even though it isn't used.
822 AST->Consumer.reset(new ASTConsumer);
823
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000824 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000825 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
826 AST->TheSema->Initialize();
827 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000828 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000829
Mike Stump1eb44332009-09-09 15:08:12 +0000830 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000831}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000832
833namespace {
834
Douglas Gregor9b7db622011-02-16 18:16:54 +0000835/// \brief Preprocessor callback class that updates a hash value with the names
836/// of all macros that have been defined by the translation unit.
837class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
838 unsigned &Hash;
839
840public:
841 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
842
843 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
844 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
845 }
846};
847
848/// \brief Add the given declaration to the hash of all top-level entities.
849void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
850 if (!D)
851 return;
852
853 DeclContext *DC = D->getDeclContext();
854 if (!DC)
855 return;
856
857 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
858 return;
859
860 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
861 if (ND->getIdentifier())
862 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
863 else if (DeclarationName Name = ND->getDeclName()) {
864 std::string NameStr = Name.getAsString();
865 Hash = llvm::HashString(NameStr, Hash);
866 }
867 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000868 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000869}
870
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000871class TopLevelDeclTrackerConsumer : public ASTConsumer {
872 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000873 unsigned &Hash;
874
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000875public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000876 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
877 : Unit(_Unit), Hash(Hash) {
878 Hash = 0;
879 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000880
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000881 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000882 if (!D)
883 return;
884
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000885 // FIXME: Currently ObjC method declarations are incorrectly being
886 // reported as top-level declarations, even though their DeclContext
887 // is the containing ObjC @interface/@implementation. This is a
888 // fundamental problem in the parser right now.
889 if (isa<ObjCMethodDecl>(D))
890 return;
891
892 AddTopLevelDeclarationToHash(D, Hash);
893 Unit.addTopLevelDecl(D);
894
895 handleFileLevelDecl(D);
896 }
897
898 void handleFileLevelDecl(Decl *D) {
899 Unit.addFileLevelDecl(D);
900 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
901 for (NamespaceDecl::decl_iterator
902 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
903 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000904 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000905 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000906
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000907 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000908 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
909 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000910 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000911 }
912
Sebastian Redl27372b42010-08-11 18:52:41 +0000913 // We're not interested in "interesting" decls.
914 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000915
916 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
917 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
918 handleTopLevelDecl(*it);
919 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000920};
921
922class TopLevelDeclTrackerAction : public ASTFrontendAction {
923public:
924 ASTUnit &Unit;
925
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000926 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000927 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000928 CI.getPreprocessor().addPPCallbacks(
929 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
930 return new TopLevelDeclTrackerConsumer(Unit,
931 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000932 }
933
934public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000935 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
936
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000937 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000938 virtual TranslationUnitKind getTranslationUnitKind() {
939 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000940 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000941};
942
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000943class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000944 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000945 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000946 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000947
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000948public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000949 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000950 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000951 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000952 Hash(Unit.getCurrentTopLevelHashValue()) {
953 Hash = 0;
954 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000955
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000956 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000957 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
958 Decl *D = *it;
959 // FIXME: Currently ObjC method declarations are incorrectly being
960 // reported as top-level declarations, even though their DeclContext
961 // is the containing ObjC @interface/@implementation. This is a
962 // fundamental problem in the parser right now.
963 if (isa<ObjCMethodDecl>(D))
964 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000965 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000966 TopLevelDecls.push_back(D);
967 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000968 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000969 }
970
971 virtual void HandleTranslationUnit(ASTContext &Ctx) {
972 PCHGenerator::HandleTranslationUnit(Ctx);
973 if (!Unit.getDiagnostics().hasErrorOccurred()) {
974 // Translate the top-level declarations we captured during
975 // parsing into declaration IDs in the precompiled
976 // preamble. This will allow us to deserialize those top-level
977 // declarations when requested.
978 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
979 Unit.addTopLevelDeclFromPreamble(
980 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000981 }
982 }
983};
984
985class PrecompilePreambleAction : public ASTFrontendAction {
986 ASTUnit &Unit;
987
988public:
989 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
990
991 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000992 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000993 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000994 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000995 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000996 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
997 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000998 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000999 return 0;
1000
Douglas Gregor832d6202011-07-22 16:35:34 +00001001 if (!CI.getFrontendOpts().RelocatablePCH)
1002 Sysroot.clear();
1003
Douglas Gregor9b7db622011-02-16 18:16:54 +00001004 CI.getPreprocessor().addPPCallbacks(
1005 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001006 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1007 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001008 }
1009
1010 virtual bool hasCodeCompletionSupport() const { return false; }
1011 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001012 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001013};
1014
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001015}
1016
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001017static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1018 StoredDiagnostics) {
1019 // Get rid of stored diagnostics except the ones from the driver which do not
1020 // have a source location.
1021 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1022 if (StoredDiagnostics[I].getLocation().isValid()) {
1023 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1024 --I;
1025 }
1026 }
1027}
1028
1029static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1030 StoredDiagnostics,
1031 SourceManager &SM) {
1032 // The stored diagnostic has the old source manager in it; update
1033 // the locations to refer into the new source manager. Since we've
1034 // been careful to make sure that the source manager's state
1035 // before and after are identical, so that we can reuse the source
1036 // location itself.
1037 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1038 if (StoredDiagnostics[I].getLocation().isValid()) {
1039 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1040 StoredDiagnostics[I].setLocation(Loc);
1041 }
1042 }
1043}
1044
Douglas Gregorabc563f2010-07-19 21:46:24 +00001045/// Parse the source file into a translation unit using the given compiler
1046/// invocation, replacing the current translation unit.
1047///
1048/// \returns True if a failure occurred that causes the ASTUnit not to
1049/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001050bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001051 delete SavedMainFileBuffer;
1052 SavedMainFileBuffer = 0;
1053
Ted Kremenek4f327862011-03-21 18:40:17 +00001054 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001055 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001056 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001057 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001058
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001059 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001060 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001061
1062 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001063 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1064 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001065
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001066 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001067 CCInvocation(new CompilerInvocation(*Invocation));
1068
1069 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001070 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001071
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001072 // Set up diagnostics, capturing any diagnostics that would
1073 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001074 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001075
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001076 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001077 Clang->getTargetOpts().Features = TargetFeatures;
1078 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001079 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001080 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001081 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001083 }
1084
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001085 // Inform the target of the language options.
1086 //
1087 // FIXME: We shouldn't need to do this, the target should be immutable once
1088 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001089 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001090
Ted Kremenek03201fb2011-03-21 18:40:07 +00001091 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001092 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001093 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001094 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001095 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001096 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001097
Douglas Gregorabc563f2010-07-19 21:46:24 +00001098 // Configure the various subsystems.
1099 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001100 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001101 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001102 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001103 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1104 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001105 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001106 Ctx = 0;
1107 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001108 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001109
1110 // Clear out old caches and data.
1111 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001112 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001113 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001114
Douglas Gregorf128fed2010-08-20 00:02:33 +00001115 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001116 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001117 TopLevelDeclsInPreamble.clear();
1118 }
1119
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001120 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001121 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001122
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001123 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001124 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001125
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001126 // If the main file has been overridden due to the use of a preamble,
1127 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001128 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001129 if (OverrideMainBuffer) {
1130 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1131 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1132 PreprocessorOpts.PrecompiledPreambleBytes.second
1133 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001134 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001135 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001136
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001137 // The stored diagnostic has the old source manager in it; update
1138 // the locations to refer into the new source manager. Since we've
1139 // been careful to make sure that the source manager's state
1140 // before and after are identical, so that we can reuse the source
1141 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001142 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001143
1144 // Keep track of the override buffer;
1145 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001146 }
1147
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001148 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001149 new TopLevelDeclTrackerAction(*this));
1150
1151 // Recover resources if we crash before exiting this method.
1152 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1153 ActCleanup(Act.get());
1154
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001155 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001156 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001157
1158 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001159 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001160 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1161 getSourceManager(), PreambleDiagnostics,
1162 StoredDiagnostics);
1163 }
1164
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001165 if (!Act->Execute())
1166 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001167
1168 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001169
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001170 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001171
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001172 FailedParseDiagnostics.clear();
1173
Douglas Gregorabc563f2010-07-19 21:46:24 +00001174 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001175
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001176error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001177 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001178 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001179 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001180 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001181 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001182
1183 // Keep the ownership of the data in the ASTUnit because the client may
1184 // want to see the diagnostics.
1185 transferASTDataFromCompilerInstance(*Clang);
1186 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001187 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001188 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001189 return true;
1190}
1191
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192/// \brief Simple function to retrieve a path for a preamble precompiled header.
1193static std::string GetPreamblePCHPath() {
1194 // FIXME: This is lame; sys::Path should provide this function (in particular,
1195 // it should know how to find the temporary files dir).
1196 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001197 // FIXME: This is a hack so that we can override the preamble file during
1198 // crash-recovery testing, which is the only case where the preamble files
1199 // are not necessarily cleaned up.
1200 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1201 if (TmpFile)
1202 return TmpFile;
1203
Douglas Gregor44c181a2010-07-23 00:33:23 +00001204 std::string Error;
1205 const char *TmpDir = ::getenv("TMPDIR");
1206 if (!TmpDir)
1207 TmpDir = ::getenv("TEMP");
1208 if (!TmpDir)
1209 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001210#ifdef LLVM_ON_WIN32
1211 if (!TmpDir)
1212 TmpDir = ::getenv("USERPROFILE");
1213#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214 if (!TmpDir)
1215 TmpDir = "/tmp";
1216 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001217 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001218 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001219 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001220 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001221 return std::string();
1222
Douglas Gregor44c181a2010-07-23 00:33:23 +00001223 return P.str();
1224}
1225
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001226/// \brief Compute the preamble for the main file, providing the source buffer
1227/// that corresponds to the main file along with a pair (bytes, start-of-line)
1228/// that describes the preamble.
1229std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001230ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1231 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001232 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001233 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001234 CreatedBuffer = false;
1235
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 // Try to determine if the main file has been remapped, either from the
1237 // command line (to another file) or directly through the compiler invocation
1238 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001239 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001240 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1242 // Check whether there is a file-file remapping of the main file
1243 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001244 M = PreprocessorOpts.remapped_file_begin(),
1245 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 M != E;
1247 ++M) {
1248 llvm::sys::PathWithStatus MPath(M->first);
1249 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1250 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1251 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001254 CreatedBuffer = false;
1255 }
1256
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001257 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001259 return std::make_pair((llvm::MemoryBuffer*)0,
1260 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001261 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001262 }
1263 }
1264 }
1265
1266 // Check whether there is a file-buffer remapping. It supercedes the
1267 // file-file remapping.
1268 for (PreprocessorOptions::remapped_file_buffer_iterator
1269 M = PreprocessorOpts.remapped_file_buffer_begin(),
1270 E = PreprocessorOpts.remapped_file_buffer_end();
1271 M != E;
1272 ++M) {
1273 llvm::sys::PathWithStatus MPath(M->first);
1274 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1275 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1276 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001278 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001279 CreatedBuffer = false;
1280 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281
Douglas Gregor175c4a92010-07-23 23:58:40 +00001282 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 }
1284 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001285 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286 }
1287
1288 // If the main source file was not remapped, load it now.
1289 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001290 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001291 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001292 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001293
1294 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001295 }
1296
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001297 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001298 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001299 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001300}
1301
Douglas Gregor754f3492010-07-24 00:38:13 +00001302static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001303 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001304 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001305 llvm::MemoryBuffer *Result
1306 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1307 memcpy(const_cast<char*>(Result->getBufferStart()),
1308 Old->getBufferStart(), Old->getBufferSize());
1309 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001310 ' ', NewSize - Old->getBufferSize() - 1);
1311 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001312
Douglas Gregor754f3492010-07-24 00:38:13 +00001313 return Result;
1314}
1315
Douglas Gregor175c4a92010-07-23 23:58:40 +00001316/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1317/// the source file.
1318///
1319/// This routine will compute the preamble of the main source file. If a
1320/// non-trivial preamble is found, it will precompile that preamble into a
1321/// precompiled header so that the precompiled preamble can be used to reduce
1322/// reparsing time. If a precompiled preamble has already been constructed,
1323/// this routine will determine if it is still valid and, if so, avoid
1324/// rebuilding the precompiled preamble.
1325///
Douglas Gregordf95a132010-08-09 20:45:32 +00001326/// \param AllowRebuild When true (the default), this routine is
1327/// allowed to rebuild the precompiled preamble if it is found to be
1328/// out-of-date.
1329///
1330/// \param MaxLines When non-zero, the maximum number of lines that
1331/// can occur within the preamble.
1332///
Douglas Gregor754f3492010-07-24 00:38:13 +00001333/// \returns If the precompiled preamble can be used, returns a newly-allocated
1334/// buffer that should be used in place of the main file when doing so.
1335/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001336llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001337 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001338 bool AllowRebuild,
1339 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001340
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001341 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001342 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1343 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001344 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001345 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001346
1347 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001348 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001349 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001350
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001351 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001352 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001353 if (CreatedPreambleBuffer)
1354 OwnedPreambleBuffer.reset(NewPreamble.first);
1355
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001356 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001357 // We couldn't find a preamble in the main source. Clear out the current
1358 // preamble, if we have one. It's obviously no good any more.
1359 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001360 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001361
1362 // The next time we actually see a preamble, precompile it.
1363 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001364 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001365 }
1366
1367 if (!Preamble.empty()) {
1368 // We've previously computed a preamble. Check whether we have the same
1369 // preamble now that we did before, and that there's enough space in
1370 // the main-file buffer within the precompiled preamble to fit the
1371 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001372 if (Preamble.size() == NewPreamble.second.first &&
1373 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001374 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001375 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001376 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001377 // The preamble has not changed. We may be able to re-use the precompiled
1378 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001379
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001380 // Check that none of the files used by the preamble have changed.
1381 bool AnyFileChanged = false;
1382
1383 // First, make a record of those files that have been overridden via
1384 // remapping or unsaved_files.
1385 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1386 for (PreprocessorOptions::remapped_file_iterator
1387 R = PreprocessorOpts.remapped_file_begin(),
1388 REnd = PreprocessorOpts.remapped_file_end();
1389 !AnyFileChanged && R != REnd;
1390 ++R) {
1391 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001392 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001393 // If we can't stat the file we're remapping to, assume that something
1394 // horrible happened.
1395 AnyFileChanged = true;
1396 break;
1397 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001398
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001399 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1400 StatBuf.st_mtime);
1401 }
1402 for (PreprocessorOptions::remapped_file_buffer_iterator
1403 R = PreprocessorOpts.remapped_file_buffer_begin(),
1404 REnd = PreprocessorOpts.remapped_file_buffer_end();
1405 !AnyFileChanged && R != REnd;
1406 ++R) {
1407 // FIXME: Should we actually compare the contents of file->buffer
1408 // remappings?
1409 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1410 0);
1411 }
1412
1413 // Check whether anything has changed.
1414 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1415 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1416 !AnyFileChanged && F != FEnd;
1417 ++F) {
1418 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1419 = OverriddenFiles.find(F->first());
1420 if (Overridden != OverriddenFiles.end()) {
1421 // This file was remapped; check whether the newly-mapped file
1422 // matches up with the previous mapping.
1423 if (Overridden->second != F->second)
1424 AnyFileChanged = true;
1425 continue;
1426 }
1427
1428 // The file was not remapped; check whether it has changed on disk.
1429 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001430 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001431 // If we can't stat the file, assume that something horrible happened.
1432 AnyFileChanged = true;
1433 } else if (StatBuf.st_size != F->second.first ||
1434 StatBuf.st_mtime != F->second.second)
1435 AnyFileChanged = true;
1436 }
1437
1438 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001439 // Okay! We can re-use the precompiled preamble.
1440
1441 // Set the state of the diagnostic object to mimic its state
1442 // after parsing the preamble.
1443 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001444 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001445 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001446 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001447
1448 // Create a version of the main file buffer that is padded to
1449 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001450 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001451 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001452 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001453 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001454 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001455
1456 // If we aren't allowed to rebuild the precompiled preamble, just
1457 // return now.
1458 if (!AllowRebuild)
1459 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001460
Douglas Gregor175c4a92010-07-23 23:58:40 +00001461 // We can't reuse the previously-computed preamble. Build a new one.
1462 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001463 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001464 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001465 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001466 } else if (!AllowRebuild) {
1467 // We aren't allowed to rebuild the precompiled preamble; just
1468 // return now.
1469 return 0;
1470 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001471
1472 // If the preamble rebuild counter > 1, it's because we previously
1473 // failed to build a preamble and we're not yet ready to try
1474 // again. Decrement the counter and return a failure.
1475 if (PreambleRebuildCounter > 1) {
1476 --PreambleRebuildCounter;
1477 return 0;
1478 }
1479
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001480 // Create a temporary file for the precompiled preamble. In rare
1481 // circumstances, this can fail.
1482 std::string PreamblePCHPath = GetPreamblePCHPath();
1483 if (PreamblePCHPath.empty()) {
1484 // Try again next time.
1485 PreambleRebuildCounter = 1;
1486 return 0;
1487 }
1488
Douglas Gregor175c4a92010-07-23 23:58:40 +00001489 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001490 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001491 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001492
1493 // Create a new buffer that stores the preamble. The buffer also contains
1494 // extra space for the original contents of the file (which will be present
1495 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001496 // grows.
1497 PreambleReservedSize = NewPreamble.first->getBufferSize();
1498 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001499 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001500 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001501 PreambleReservedSize *= 2;
1502
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001503 // Save the preamble text for later; we'll need to compare against it for
1504 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001505 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001506 Preamble.assign(FileMgr->getFile(MainFilename),
1507 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001508 NewPreamble.first->getBufferStart()
1509 + NewPreamble.second.first);
1510 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1511
Douglas Gregor671947b2010-08-19 01:33:06 +00001512 delete PreambleBuffer;
1513 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001514 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001515 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001517 NewPreamble.first->getBufferStart(), Preamble.size());
1518 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001519 ' ', PreambleReservedSize - Preamble.size() - 1);
1520 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001521
1522 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001523 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001524 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1525
1526 // Tell the compiler invocation to generate a temporary precompiled header.
1527 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001528 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001529 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001530 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1531 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001532
1533 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001534 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001535
1536 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001537 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1538 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001539
Douglas Gregor01b6e312011-07-01 18:22:13 +00001540 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001541 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001542
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001543 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001544 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001545
1546 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001547 Clang->getTargetOpts().Features = TargetFeatures;
1548 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1549 Clang->getTargetOpts()));
1550 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001551 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1552 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001553 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001554 PreprocessorOpts.eraseRemappedFile(
1555 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001556 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001557 }
1558
1559 // Inform the target of the language options.
1560 //
1561 // FIXME: We shouldn't need to do this, the target should be immutable once
1562 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001563 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001564
Ted Kremenek03201fb2011-03-21 18:40:07 +00001565 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001566 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001567 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001568 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001569 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001570 "IR inputs not support here!");
1571
1572 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001573 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001574 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001575 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001576 TopLevelDecls.clear();
1577 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001578
1579 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001580 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001581
1582 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001583 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001584 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001585
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001586 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001587 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001588 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001589 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1590 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001591 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001592 PreprocessorOpts.eraseRemappedFile(
1593 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001594 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001595 }
1596
1597 Act->Execute();
1598 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001599
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001600 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001601 // There were errors parsing the preamble, so no precompiled header was
1602 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001603 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001604 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1605 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001606 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001607 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001608 PreprocessorOpts.eraseRemappedFile(
1609 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001610 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001611 }
1612
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001613 // Transfer any diagnostics generated when parsing the preamble into the set
1614 // of preamble diagnostics.
1615 PreambleDiagnostics.clear();
1616 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001617 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001618 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001619
Douglas Gregor175c4a92010-07-23 23:58:40 +00001620 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001621 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001622 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001623
1624 // Keep track of all of the files that the source manager knows about,
1625 // so we can verify whether they have changed or not.
1626 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001627 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001628 const llvm::MemoryBuffer *MainFileBuffer
1629 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1630 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1631 FEnd = SourceMgr.fileinfo_end();
1632 F != FEnd;
1633 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001634 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001635 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1636 continue;
1637
1638 FilesInPreamble[File->getName()]
1639 = std::make_pair(F->second->getSize(), File->getModificationTime());
1640 }
1641
Douglas Gregoreababfb2010-08-04 05:53:38 +00001642 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001643 PreprocessorOpts.eraseRemappedFile(
1644 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001645
1646 // If the hash of top-level entities differs from the hash of the top-level
1647 // entities the last time we rebuilt the preamble, clear out the completion
1648 // cache.
1649 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1650 CompletionCacheTopLevelHashValue = 0;
1651 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1652 }
1653
Douglas Gregor754f3492010-07-24 00:38:13 +00001654 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001655 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001656 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001657}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001658
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001659void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1660 std::vector<Decl *> Resolved;
1661 Resolved.reserve(TopLevelDeclsInPreamble.size());
1662 ExternalASTSource &Source = *getASTContext().getExternalSource();
1663 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1664 // Resolve the declaration ID to an actual declaration, possibly
1665 // deserializing the declaration in the process.
1666 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1667 if (D)
1668 Resolved.push_back(D);
1669 }
1670 TopLevelDeclsInPreamble.clear();
1671 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1672}
1673
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001674void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1675 // Steal the created target, context, and preprocessor.
1676 TheSema.reset(CI.takeSema());
1677 Consumer.reset(CI.takeASTConsumer());
1678 Ctx = &CI.getASTContext();
1679 PP = &CI.getPreprocessor();
1680 CI.setSourceManager(0);
1681 CI.setFileManager(0);
1682 Target = &CI.getTarget();
1683 Reader = CI.getModuleManager();
1684}
1685
Chris Lattner5f9e2722011-07-23 10:55:15 +00001686StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001687 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001688}
1689
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001690ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001691 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001692 bool CaptureDiagnostics,
1693 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001694 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001695 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001696 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001697 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001698 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001699 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001700 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001701 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1702 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1703 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001704
1705 return AST.take();
1706}
1707
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001708ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001709 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001710 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001711 ASTUnit *Unit,
1712 bool Persistent,
1713 StringRef ResourceFilesPath,
1714 bool OnlyLocalDecls,
1715 bool CaptureDiagnostics,
1716 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001717 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001718 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001719 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001720 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001721 assert(CI && "A CompilerInvocation is required");
1722
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001723 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001724 ASTUnit *AST = Unit;
1725 if (!AST) {
1726 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001727 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001728 AST = OwnAST.get();
1729 }
1730
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001731 if (!ResourceFilesPath.empty()) {
1732 // Override the resources path.
1733 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1734 }
1735 AST->OnlyLocalDecls = OnlyLocalDecls;
1736 AST->CaptureDiagnostics = CaptureDiagnostics;
1737 if (PrecompilePreamble)
1738 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001739 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001740 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001741 AST->IncludeBriefCommentsInCodeCompletion
1742 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001743
1744 // Recover resources if we crash before exiting this method.
1745 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001746 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001747 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1748 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001749 DiagCleanup(Diags.getPtr());
1750
1751 // We'll manage file buffers ourselves.
1752 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1753 CI->getFrontendOpts().DisableFree = false;
1754 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1755
1756 // Save the target features.
1757 AST->TargetFeatures = CI->getTargetOpts().Features;
1758
1759 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001760 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001761
1762 // Recover resources if we crash before exiting this method.
1763 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1764 CICleanup(Clang.get());
1765
1766 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001767 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001768
1769 // Set up diagnostics, capturing any diagnostics that would
1770 // otherwise be dropped.
1771 Clang->setDiagnostics(&AST->getDiagnostics());
1772
1773 // Create the target instance.
1774 Clang->getTargetOpts().Features = AST->TargetFeatures;
1775 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1776 Clang->getTargetOpts()));
1777 if (!Clang->hasTarget())
1778 return 0;
1779
1780 // Inform the target of the language options.
1781 //
1782 // FIXME: We shouldn't need to do this, the target should be immutable once
1783 // created. This complexity should be lifted elsewhere.
1784 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1785
1786 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1787 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001788 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001789 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001790 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001791 "IR inputs not supported here!");
1792
1793 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001794 AST->TheSema.reset();
1795 AST->Ctx = 0;
1796 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001797 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001798
1799 // Create a file manager object to provide access to and cache the filesystem.
1800 Clang->setFileManager(&AST->getFileManager());
1801
1802 // Create the source manager.
1803 Clang->setSourceManager(&AST->getSourceManager());
1804
1805 ASTFrontendAction *Act = Action;
1806
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001807 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001808 if (!Act) {
1809 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1810 Act = TrackerAct.get();
1811 }
1812
1813 // Recover resources if we crash before exiting this method.
1814 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1815 ActCleanup(TrackerAct.get());
1816
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001817 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1818 AST->transferASTDataFromCompilerInstance(*Clang);
1819 if (OwnAST && ErrAST)
1820 ErrAST->swap(OwnAST);
1821
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001822 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001823 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001824
1825 if (Persistent && !TrackerAct) {
1826 Clang->getPreprocessor().addPPCallbacks(
1827 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1828 std::vector<ASTConsumer*> Consumers;
1829 if (Clang->hasASTConsumer())
1830 Consumers.push_back(Clang->takeASTConsumer());
1831 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1832 AST->getCurrentTopLevelHashValue()));
1833 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1834 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001835 if (!Act->Execute()) {
1836 AST->transferASTDataFromCompilerInstance(*Clang);
1837 if (OwnAST && ErrAST)
1838 ErrAST->swap(OwnAST);
1839
1840 return 0;
1841 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001842
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001843 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001844 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001845
1846 Act->EndSourceFile();
1847
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001848 if (OwnAST)
1849 return OwnAST.take();
1850 else
1851 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001852}
1853
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001854bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1855 if (!Invocation)
1856 return true;
1857
1858 // We'll manage file buffers ourselves.
1859 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1860 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001861 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001862
Douglas Gregor1aa27302011-01-27 18:02:58 +00001863 // Save the target features.
1864 TargetFeatures = Invocation->getTargetOpts().Features;
1865
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001866 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001867 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001868 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001869 OverrideMainBuffer
1870 = getMainBufferWithPrecompiledPreamble(*Invocation);
1871 }
1872
Douglas Gregor213f18b2010-10-28 15:44:59 +00001873 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001874 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001875
Ted Kremenek25a11e12011-03-22 01:15:24 +00001876 // Recover resources if we crash before exiting this method.
1877 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1878 MemBufferCleanup(OverrideMainBuffer);
1879
Douglas Gregor213f18b2010-10-28 15:44:59 +00001880 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001881}
1882
Douglas Gregorabc563f2010-07-19 21:46:24 +00001883ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001884 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001885 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001886 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001887 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001888 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001889 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001890 bool IncludeBriefCommentsInCodeCompletion,
1891 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001892 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001893 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001894 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001895 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001896 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001897 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001898 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001899 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001900 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001901 AST->IncludeBriefCommentsInCodeCompletion
1902 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001903 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001904 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001905
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001906 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001907 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1908 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001909 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1910 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001911 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001912
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001913 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001914}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001915
1916ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1917 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001918 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001919 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001920 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001921 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001922 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001923 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001924 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001925 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001926 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001927 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001928 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001929 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001930 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001931 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001932 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001933 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001934 // No diagnostics engine was provided, so create our own diagnostics object
1935 // with the default options.
1936 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001937 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1938 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001939 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001940
Chris Lattner5f9e2722011-07-23 10:55:15 +00001941 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001942
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001943 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001944
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001945 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001946
Douglas Gregore47be3e2010-11-11 00:39:14 +00001947 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001948 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001949
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001950 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001951 llvm::makeArrayRef(ArgBegin, ArgEnd),
1952 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001953 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001954 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001955 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001956
Douglas Gregor4db64a42010-01-23 00:14:00 +00001957 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001958 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1959 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1960 if (const llvm::MemoryBuffer *
1961 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1962 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1963 } else {
1964 const char *fname = fileOrBuf.get<const char *>();
1965 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1966 }
1967 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001968 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1969 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1970 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001971
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001972 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001973 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001974
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001975 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1976
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001977 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001978 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001979 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001980 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001981 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001982 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001983 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001984 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001985 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001986 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001987 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001988 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001989 AST->IncludeBriefCommentsInCodeCompletion
1990 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001991 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001992 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001993 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001994 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001995 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001996
1997 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001998 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1999 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002000
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002001 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2002 // Some error occurred, if caller wants to examine diagnostics, pass it the
2003 // ASTUnit.
2004 if (ErrAST) {
2005 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2006 ErrAST->swap(AST);
2007 }
2008 return 0;
2009 }
2010
2011 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002012}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002013
2014bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002015 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002016 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002017
2018 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002019
Douglas Gregor213f18b2010-10-28 15:44:59 +00002020 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002021 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002022
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002023 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002024 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002025 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002026 for (PreprocessorOptions::remapped_file_buffer_iterator
2027 R = PPOpts.remapped_file_buffer_begin(),
2028 REnd = PPOpts.remapped_file_buffer_end();
2029 R != REnd;
2030 ++R) {
2031 delete R->second;
2032 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002033 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002034 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2035 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2036 if (const llvm::MemoryBuffer *
2037 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2038 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2039 memBuf);
2040 } else {
2041 const char *fname = fileOrBuf.get<const char *>();
2042 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2043 fname);
2044 }
2045 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002046
Douglas Gregoreababfb2010-08-04 05:53:38 +00002047 // If we have a preamble file lying around, or if we might try to
2048 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002049 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002050 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002051 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002052
Douglas Gregorabc563f2010-07-19 21:46:24 +00002053 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002054 getDiagnostics().Reset();
2055 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002056 if (OverrideMainBuffer)
2057 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002058
Douglas Gregor175c4a92010-07-23 23:58:40 +00002059 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002060 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002061
2062 // If we're caching global code-completion results, and the top-level
2063 // declarations have changed, clear out the code-completion cache.
2064 if (!Result && ShouldCacheCodeCompletionResults &&
2065 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2066 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002067
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002068 // We now need to clear out the completion info related to this translation
2069 // unit; it'll be recreated if necessary.
2070 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002071
Douglas Gregor175c4a92010-07-23 23:58:40 +00002072 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002073}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002074
Douglas Gregor87c08a52010-08-13 22:48:40 +00002075//----------------------------------------------------------------------------//
2076// Code completion
2077//----------------------------------------------------------------------------//
2078
2079namespace {
2080 /// \brief Code completion consumer that combines the cached code-completion
2081 /// results from an ASTUnit with the code-completion results provided to it,
2082 /// then passes the result on to
2083 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002084 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002085 ASTUnit &AST;
2086 CodeCompleteConsumer &Next;
2087
2088 public:
2089 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002090 const CodeCompleteOptions &CodeCompleteOpts)
2091 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2092 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002093 {
2094 // Compute the set of contexts in which we will look when we don't have
2095 // any information about the specific context.
2096 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002097 = (1LL << CodeCompletionContext::CCC_TopLevel)
2098 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2099 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2100 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2101 | (1LL << CodeCompletionContext::CCC_Statement)
2102 | (1LL << CodeCompletionContext::CCC_Expression)
2103 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2104 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2105 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2106 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2107 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2108 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2109 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002110
David Blaikie4e4d0842012-03-11 07:00:24 +00002111 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002112 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2113 | (1LL << CodeCompletionContext::CCC_UnionTag)
2114 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002115 }
2116
2117 virtual void ProcessCodeCompleteResults(Sema &S,
2118 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002119 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002120 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002121
2122 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2123 OverloadCandidate *Candidates,
2124 unsigned NumCandidates) {
2125 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2126 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002127
Douglas Gregordae68752011-02-01 22:57:45 +00002128 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002129 return Next.getAllocator();
2130 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002131
2132 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2133 return Next.getCodeCompletionTUInfo();
2134 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002135 };
2136}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002137
Douglas Gregor5f808c22010-08-16 21:18:39 +00002138/// \brief Helper function that computes which global names are hidden by the
2139/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002140static void CalculateHiddenNames(const CodeCompletionContext &Context,
2141 CodeCompletionResult *Results,
2142 unsigned NumResults,
2143 ASTContext &Ctx,
2144 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002145 bool OnlyTagNames = false;
2146 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002147 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002148 case CodeCompletionContext::CCC_TopLevel:
2149 case CodeCompletionContext::CCC_ObjCInterface:
2150 case CodeCompletionContext::CCC_ObjCImplementation:
2151 case CodeCompletionContext::CCC_ObjCIvarList:
2152 case CodeCompletionContext::CCC_ClassStructUnion:
2153 case CodeCompletionContext::CCC_Statement:
2154 case CodeCompletionContext::CCC_Expression:
2155 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002156 case CodeCompletionContext::CCC_DotMemberAccess:
2157 case CodeCompletionContext::CCC_ArrowMemberAccess:
2158 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002159 case CodeCompletionContext::CCC_Namespace:
2160 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002161 case CodeCompletionContext::CCC_Name:
2162 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002163 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002164 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002165 break;
2166
2167 case CodeCompletionContext::CCC_EnumTag:
2168 case CodeCompletionContext::CCC_UnionTag:
2169 case CodeCompletionContext::CCC_ClassOrStructTag:
2170 OnlyTagNames = true;
2171 break;
2172
2173 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002174 case CodeCompletionContext::CCC_MacroName:
2175 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002176 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002177 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002178 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002179 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002180 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002181 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002182 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002183 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2184 case CodeCompletionContext::CCC_ObjCClassMessage:
2185 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002186 // We're looking for nothing, or we're looking for names that cannot
2187 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002188 return;
2189 }
2190
John McCall0a2c5e22010-08-25 06:19:51 +00002191 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002192 for (unsigned I = 0; I != NumResults; ++I) {
2193 if (Results[I].Kind != Result::RK_Declaration)
2194 continue;
2195
2196 unsigned IDNS
2197 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2198
2199 bool Hiding = false;
2200 if (OnlyTagNames)
2201 Hiding = (IDNS & Decl::IDNS_Tag);
2202 else {
2203 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002204 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2205 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002206 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002207 HiddenIDNS |= Decl::IDNS_Tag;
2208 Hiding = (IDNS & HiddenIDNS);
2209 }
2210
2211 if (!Hiding)
2212 continue;
2213
2214 DeclarationName Name = Results[I].Declaration->getDeclName();
2215 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2216 HiddenNames.insert(Identifier->getName());
2217 else
2218 HiddenNames.insert(Name.getAsString());
2219 }
2220}
2221
2222
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002223void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2224 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002225 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002226 unsigned NumResults) {
2227 // Merge the results we were given with the results we cached.
2228 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002229 uint64_t InContexts =
2230 Context.getKind() == CodeCompletionContext::CCC_Recovery
2231 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002232 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002233 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002234 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002235 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002236 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002237 C = AST.cached_completion_begin(),
2238 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002239 C != CEnd; ++C) {
2240 // If the context we are in matches any of the contexts we are
2241 // interested in, we'll add this result.
2242 if ((C->ShowInContexts & InContexts) == 0)
2243 continue;
2244
2245 // If we haven't added any results previously, do so now.
2246 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002247 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2248 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002249 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2250 AddedResult = true;
2251 }
2252
Douglas Gregor5f808c22010-08-16 21:18:39 +00002253 // Determine whether this global completion result is hidden by a local
2254 // completion result. If so, skip it.
2255 if (C->Kind != CXCursor_MacroDefinition &&
2256 HiddenNames.count(C->Completion->getTypedText()))
2257 continue;
2258
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002259 // Adjust priority based on similar type classes.
2260 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002261 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002262 if (!Context.getPreferredType().isNull()) {
2263 if (C->Kind == CXCursor_MacroDefinition) {
2264 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002265 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002266 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002267 } else if (C->Type) {
2268 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002269 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002270 Context.getPreferredType().getUnqualifiedType());
2271 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2272 if (ExpectedSTC == C->TypeClass) {
2273 // We know this type is similar; check for an exact match.
2274 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002275 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002276 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002277 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002278 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2279 Priority /= CCF_ExactTypeMatch;
2280 else
2281 Priority /= CCF_SimilarTypeMatch;
2282 }
2283 }
2284 }
2285
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002286 // Adjust the completion string, if required.
2287 if (C->Kind == CXCursor_MacroDefinition &&
2288 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2289 // Create a new code-completion string that just contains the
2290 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002291 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2292 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002293 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002294 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002295 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002296 }
2297
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002298 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002299 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002300 }
2301
2302 // If we did not add any cached completion results, just forward the
2303 // results we were given to the next consumer.
2304 if (!AddedResult) {
2305 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2306 return;
2307 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002308
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002309 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2310 AllResults.size());
2311}
2312
2313
2314
Chris Lattner5f9e2722011-07-23 10:55:15 +00002315void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002316 RemappedFile *RemappedFiles,
2317 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002318 bool IncludeMacros,
2319 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002320 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002321 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002322 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002323 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002324 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2325 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002326 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002327 return;
2328
Douglas Gregor213f18b2010-10-28 15:44:59 +00002329 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002330 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002331 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002332
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002333 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002334 CCInvocation(new CompilerInvocation(*Invocation));
2335
2336 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002337 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002338 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002339
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002340 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2341 CachedCompletionResults.empty();
2342 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2343 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2344 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2345
2346 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2347
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348 FrontendOpts.CodeCompletionAt.FileName = File;
2349 FrontendOpts.CodeCompletionAt.Line = Line;
2350 FrontendOpts.CodeCompletionAt.Column = Column;
2351
2352 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002353 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002355 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002356
2357 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002358 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2359 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002360
Ted Kremenek4f327862011-03-21 18:40:17 +00002361 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002362 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002363
2364 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002365 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002366 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002367 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002368 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002369 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002370
2371 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002372 Clang->getTargetOpts().Features = TargetFeatures;
2373 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2374 Clang->getTargetOpts()));
2375 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002376 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002377 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002378 }
2379
2380 // Inform the target of the language options.
2381 //
2382 // FIXME: We shouldn't need to do this, the target should be immutable once
2383 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002384 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002385
Ted Kremenek03201fb2011-03-21 18:40:07 +00002386 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002387 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002388 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002389 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002390 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002391 "IR inputs not support here!");
2392
2393
2394 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002395 Clang->setFileManager(&FileMgr);
2396 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002397
2398 // Remap files.
2399 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002400 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002401 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002402 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2403 if (const llvm::MemoryBuffer *
2404 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2405 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2406 OwnedBuffers.push_back(memBuf);
2407 } else {
2408 const char *fname = fileOrBuf.get<const char *>();
2409 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2410 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002411 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002412
Douglas Gregor87c08a52010-08-13 22:48:40 +00002413 // Use the code completion consumer we were given, but adding any cached
2414 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002415 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002416 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002417 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002418
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002419 Clang->getFrontendOpts().SkipFunctionBodies = true;
2420
Douglas Gregordf95a132010-08-09 20:45:32 +00002421 // If we have a precompiled preamble, try to use it. We only allow
2422 // the use of the precompiled preamble if we're if the completion
2423 // point is within the main file, after the end of the precompiled
2424 // preamble.
2425 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002426 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002427 using llvm::sys::FileStatus;
2428 llvm::sys::PathWithStatus CompleteFilePath(File);
2429 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2430 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2431 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002432 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2433 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002434 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002435 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002436 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002437 }
2438
2439 // If the main file has been overridden due to the use of a preamble,
2440 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002441 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002442 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002443 stored_diag_begin(),
2444 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002445 if (OverrideMainBuffer) {
2446 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2447 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2448 PreprocessorOpts.PrecompiledPreambleBytes.second
2449 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002450 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002451 PreprocessorOpts.DisablePCHValidation = true;
2452
Douglas Gregor2283d792010-08-20 00:59:43 +00002453 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002454 } else {
2455 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2456 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002457 }
2458
Douglas Gregordca8ee82011-05-06 16:33:08 +00002459 // Disable the preprocessing record
2460 PreprocessorOpts.DetailedRecord = false;
2461
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002462 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002463 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002464 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002465 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002466 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002467 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2468 getSourceManager(), PreambleDiagnostics,
2469 StoredDiagnostics);
2470 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002471 Act->Execute();
2472 Act->EndSourceFile();
2473 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002474
2475 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002476}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002477
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002478bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002479 // Write to a temporary file and later rename it to the actual file, to avoid
2480 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002481 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002482 TempPath = File;
2483 TempPath += "-%%%%%%%%";
2484 int fd;
2485 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2486 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002487 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002488
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002489 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2490 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002491 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002492
2493 serialize(Out);
2494 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002495 if (Out.has_error()) {
2496 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002497 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002498 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002499
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002500 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002501 bool exists;
2502 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002503 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002504 }
2505
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002506 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002507}
2508
Chris Lattner5f9e2722011-07-23 10:55:15 +00002509bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002510 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002511
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002512 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002513 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002514 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002515 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002516 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002517
2518 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002519 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002520 OS.write((char *)&Buffer.front(), Buffer.size());
2521
2522 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002523}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002524
2525typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2526
2527static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2528 unsigned Raw = L.getRawEncoding();
2529 const unsigned MacroBit = 1U << 31;
2530 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2531 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2532}
2533
2534void ASTUnit::TranslateStoredDiagnostics(
2535 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002537 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002538 const SmallVectorImpl<StoredDiagnostic> &Diags,
2539 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002540 // The stored diagnostic has the old source manager in it; update
2541 // the locations to refer into the new source manager. We also need to remap
2542 // all the locations to the new view. This includes the diag location, any
2543 // associated source ranges, and the source ranges of associated fix-its.
2544 // FIXME: There should be a cleaner way to do this.
2545
Chris Lattner5f9e2722011-07-23 10:55:15 +00002546 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002547 Result.reserve(Diags.size());
2548 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002549 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002550 assert(Mod && "Don't have preamble module");
2551 SLocRemap &Remap = Mod->SLocRemap;
2552 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2553 // Rebuild the StoredDiagnostic.
2554 const StoredDiagnostic &SD = Diags[I];
2555 SourceLocation L = SD.getLocation();
2556 TranslateSLoc(L, Remap);
2557 FullSourceLoc Loc(L, SrcMgr);
2558
Chris Lattner5f9e2722011-07-23 10:55:15 +00002559 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002560 Ranges.reserve(SD.range_size());
2561 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2562 E = SD.range_end();
2563 I != E; ++I) {
2564 SourceLocation BL = I->getBegin();
2565 TranslateSLoc(BL, Remap);
2566 SourceLocation EL = I->getEnd();
2567 TranslateSLoc(EL, Remap);
2568 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2569 }
2570
Chris Lattner5f9e2722011-07-23 10:55:15 +00002571 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002572 FixIts.reserve(SD.fixit_size());
2573 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2574 E = SD.fixit_end();
2575 I != E; ++I) {
2576 FixIts.push_back(FixItHint());
2577 FixItHint &FH = FixIts.back();
2578 FH.CodeToInsert = I->CodeToInsert;
2579 SourceLocation BL = I->RemoveRange.getBegin();
2580 TranslateSLoc(BL, Remap);
2581 SourceLocation EL = I->RemoveRange.getEnd();
2582 TranslateSLoc(EL, Remap);
2583 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2584 I->RemoveRange.isTokenRange());
2585 }
2586
2587 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2588 SD.getMessage(), Loc, Ranges, FixIts));
2589 }
2590 Result.swap(Out);
2591}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002592
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002593static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2594 std::pair<unsigned, Decl *> R) {
2595 return L.first < R.first;
2596}
2597
2598void ASTUnit::addFileLevelDecl(Decl *D) {
2599 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002600
2601 // We only care about local declarations.
2602 if (D->isFromASTFile())
2603 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002604
2605 SourceManager &SM = *SourceMgr;
2606 SourceLocation Loc = D->getLocation();
2607 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2608 return;
2609
2610 // We only keep track of the file-level declarations of each file.
2611 if (!D->getLexicalDeclContext()->isFileContext())
2612 return;
2613
2614 SourceLocation FileLoc = SM.getFileLoc(Loc);
2615 assert(SM.isLocalSourceLocation(FileLoc));
2616 FileID FID;
2617 unsigned Offset;
2618 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2619 if (FID.isInvalid())
2620 return;
2621
2622 LocDeclsTy *&Decls = FileDecls[FID];
2623 if (!Decls)
2624 Decls = new LocDeclsTy();
2625
2626 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2627
2628 if (Decls->empty() || Decls->back().first <= Offset) {
2629 Decls->push_back(LocDecl);
2630 return;
2631 }
2632
2633 LocDeclsTy::iterator
2634 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2635
2636 Decls->insert(I, LocDecl);
2637}
2638
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002639void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2640 SmallVectorImpl<Decl *> &Decls) {
2641 if (File.isInvalid())
2642 return;
2643
2644 if (SourceMgr->isLoadedFileID(File)) {
2645 assert(Ctx->getExternalSource() && "No external source!");
2646 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2647 Decls);
2648 }
2649
2650 FileDeclsTy::iterator I = FileDecls.find(File);
2651 if (I == FileDecls.end())
2652 return;
2653
2654 LocDeclsTy &LocDecls = *I->second;
2655 if (LocDecls.empty())
2656 return;
2657
2658 LocDeclsTy::iterator
2659 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2660 std::make_pair(Offset, (Decl*)0), compLocDecl);
2661 if (BeginIt != LocDecls.begin())
2662 --BeginIt;
2663
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002664 // If we are pointing at a top-level decl inside an objc container, we need
2665 // to backtrack until we find it otherwise we will fail to report that the
2666 // region overlaps with an objc container.
2667 while (BeginIt != LocDecls.begin() &&
2668 BeginIt->second->isTopLevelDeclInObjCContainer())
2669 --BeginIt;
2670
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002671 LocDeclsTy::iterator
2672 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2673 std::make_pair(Offset+Length, (Decl*)0),
2674 compLocDecl);
2675 if (EndIt != LocDecls.end())
2676 ++EndIt;
2677
2678 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2679 Decls.push_back(DIt->second);
2680}
2681
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002682SourceLocation ASTUnit::getLocation(const FileEntry *File,
2683 unsigned Line, unsigned Col) const {
2684 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002685 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002686 return SM.getMacroArgExpandedLocation(Loc);
2687}
2688
2689SourceLocation ASTUnit::getLocation(const FileEntry *File,
2690 unsigned Offset) const {
2691 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002692 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002693 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2694}
2695
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002696/// \brief If \arg Loc is a loaded location from the preamble, returns
2697/// the corresponding local location of the main file, otherwise it returns
2698/// \arg Loc.
2699SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2700 FileID PreambleID;
2701 if (SourceMgr)
2702 PreambleID = SourceMgr->getPreambleFileID();
2703
2704 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2705 return Loc;
2706
2707 unsigned Offs;
2708 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2709 SourceLocation FileLoc
2710 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2711 return FileLoc.getLocWithOffset(Offs);
2712 }
2713
2714 return Loc;
2715}
2716
2717/// \brief If \arg Loc is a local location of the main file but inside the
2718/// preamble chunk, returns the corresponding loaded location from the
2719/// preamble, otherwise it returns \arg Loc.
2720SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2721 FileID PreambleID;
2722 if (SourceMgr)
2723 PreambleID = SourceMgr->getPreambleFileID();
2724
2725 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2726 return Loc;
2727
2728 unsigned Offs;
2729 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2730 Offs < Preamble.size()) {
2731 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2732 return FileLoc.getLocWithOffset(Offs);
2733 }
2734
2735 return Loc;
2736}
2737
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002738bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2739 FileID FID;
2740 if (SourceMgr)
2741 FID = SourceMgr->getPreambleFileID();
2742
2743 if (Loc.isInvalid() || FID.isInvalid())
2744 return false;
2745
2746 return SourceMgr->isInFileID(Loc, FID);
2747}
2748
2749bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2750 FileID FID;
2751 if (SourceMgr)
2752 FID = SourceMgr->getMainFileID();
2753
2754 if (Loc.isInvalid() || FID.isInvalid())
2755 return false;
2756
2757 return SourceMgr->isInFileID(Loc, FID);
2758}
2759
2760SourceLocation ASTUnit::getEndOfPreambleFileID() {
2761 FileID FID;
2762 if (SourceMgr)
2763 FID = SourceMgr->getPreambleFileID();
2764
2765 if (FID.isInvalid())
2766 return SourceLocation();
2767
2768 return SourceMgr->getLocForEndOfFile(FID);
2769}
2770
2771SourceLocation ASTUnit::getStartOfMainFileID() {
2772 FileID FID;
2773 if (SourceMgr)
2774 FID = SourceMgr->getMainFileID();
2775
2776 if (FID.isInvalid())
2777 return SourceLocation();
2778
2779 return SourceMgr->getLocForStartOfFile(FID);
2780}
2781
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002782std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2783ASTUnit::getLocalPreprocessingEntities() const {
2784 if (isMainFileAST()) {
2785 serialization::ModuleFile &
2786 Mod = Reader->getModuleManager().getPrimaryModule();
2787 return Reader->getModulePreprocessedEntities(Mod);
2788 }
2789
2790 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2791 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2792
2793 return std::make_pair(PreprocessingRecord::iterator(),
2794 PreprocessingRecord::iterator());
2795}
2796
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002797bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002798 if (isMainFileAST()) {
2799 serialization::ModuleFile &
2800 Mod = Reader->getModuleManager().getPrimaryModule();
2801 ASTReader::ModuleDeclIterator MDI, MDE;
2802 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2803 for (; MDI != MDE; ++MDI) {
2804 if (!Fn(context, *MDI))
2805 return false;
2806 }
2807
2808 return true;
2809 }
2810
2811 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2812 TLEnd = top_level_end();
2813 TL != TLEnd; ++TL) {
2814 if (!Fn(context, *TL))
2815 return false;
2816 }
2817
2818 return true;
2819}
2820
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002821namespace {
2822struct PCHLocatorInfo {
2823 serialization::ModuleFile *Mod;
2824 PCHLocatorInfo() : Mod(0) {}
2825};
2826}
2827
2828static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2829 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2830 switch (M.Kind) {
2831 case serialization::MK_Module:
2832 return true; // skip dependencies.
2833 case serialization::MK_PCH:
2834 Info.Mod = &M;
2835 return true; // found it.
2836 case serialization::MK_Preamble:
2837 return false; // look in dependencies.
2838 case serialization::MK_MainFile:
2839 return false; // look in dependencies.
2840 }
2841
2842 return true;
2843}
2844
2845const FileEntry *ASTUnit::getPCHFile() {
2846 if (!Reader)
2847 return 0;
2848
2849 PCHLocatorInfo Info;
2850 Reader->getModuleManager().visit(PCHLocator, &Info);
2851 if (Info.Mod)
2852 return Info.Mod->File;
2853
2854 return 0;
2855}
2856
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002857bool ASTUnit::isModuleFile() {
2858 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2859}
2860
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002861void ASTUnit::PreambleData::countLines() const {
2862 NumLines = 0;
2863 if (empty())
2864 return;
2865
2866 for (std::vector<char>::const_iterator
2867 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2868 if (*I == '\n')
2869 ++NumLines;
2870 }
2871 if (Buffer.back() != '\n')
2872 ++NumLines;
2873}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002874
2875#ifndef NDEBUG
2876ASTUnit::ConcurrencyState::ConcurrencyState() {
2877 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2878}
2879
2880ASTUnit::ConcurrencyState::~ConcurrencyState() {
2881 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2882}
2883
2884void ASTUnit::ConcurrencyState::start() {
2885 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2886 assert(acquired && "Concurrent access to ASTUnit!");
2887}
2888
2889void ASTUnit::ConcurrencyState::finish() {
2890 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2891}
2892
2893#else // NDEBUG
2894
2895ASTUnit::ConcurrencyState::ConcurrencyState() {}
2896ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2897void ASTUnit::ConcurrencyState::start() {}
2898void ASTUnit::ConcurrencyState::finish() {}
2899
2900#endif