blob: 9954705d3958353cc821245c92926ec2f716426c [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 Kyrtzidis900ab952012-10-11 16:05:00 +0000183struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
186 ASTWriter Writer;
187
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
189};
190
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000191void ASTUnit::clearFileLevelDecls() {
192 for (FileDeclsTy::iterator
193 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
194 delete I->second;
195 FileDecls.clear();
196}
197
Ted Kremenek1872b312011-10-27 17:55:18 +0000198void ASTUnit::CleanTemporaryFiles() {
199 getOnDiskData(this).CleanTemporaryFiles();
200}
201
202void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
203 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000204}
205
Douglas Gregoreababfb2010-08-04 05:53:38 +0000206/// \brief After failing to build a precompiled preamble (due to
207/// errors in the source that occurs in the preamble), the number of
208/// reparses during which we'll skip even trying to precompile the
209/// preamble.
210const unsigned DefaultPreambleRebuildInterval = 5;
211
Douglas Gregore3c60a72010-11-17 00:13:31 +0000212/// \brief Tracks the number of ASTUnit objects that are currently active.
213///
214/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000215static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000216
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000217ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000218 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000224 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000232 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000233 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
234 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000235}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000236
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000237ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000238 clearFileLevelDecls();
239
Ted Kremenek1872b312011-10-27 17:55:18 +0000240 // Clean up the temporary files and the preamble file.
241 removeOnDiskEntry(this);
242
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000243 // Free the buffers associated with remapped files. We are required to
244 // perform this operation here because we explicitly request that the
245 // compiler instance *not* free these buffers for each invocation of the
246 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000247 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000248 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
249 for (PreprocessorOptions::remapped_file_buffer_iterator
250 FB = PPOpts.remapped_file_buffer_begin(),
251 FBEnd = PPOpts.remapped_file_buffer_end();
252 FB != FBEnd;
253 ++FB)
254 delete FB->second;
255 }
Douglas Gregor28233422010-07-27 14:52:07 +0000256
257 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000258 delete PreambleBuffer;
259
Douglas Gregor213f18b2010-10-28 15:44:59 +0000260 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000261
262 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000263 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000264 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
265 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000266}
267
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000268void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
269
Douglas Gregor8071e422010-08-15 06:18:01 +0000270/// \brief Determine the set of code-completion contexts in which this
271/// declaration should be shown.
272static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000273 const LangOptions &LangOpts,
274 bool &IsNestedNameSpecifier) {
275 IsNestedNameSpecifier = false;
276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 if (isa<UsingShadowDecl>(ND))
278 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
279 if (!ND)
280 return 0;
281
Richard Smith026b3582012-08-14 03:13:00 +0000282 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
284 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
285 // Types can appear in these contexts.
286 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000287 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
288 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
289 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
290 | (1LL << CodeCompletionContext::CCC_Statement)
291 | (1LL << CodeCompletionContext::CCC_Type)
292 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000293
294 // In C++, types can appear in expressions contexts (for functional casts).
295 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000296 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000297
298 // In Objective-C, message sends can send interfaces. In Objective-C++,
299 // all types are available due to functional casts.
300 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000302
303 // In Objective-C, you can only be a subclass of another Objective-C class
304 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000306
307 // Deal with tag names.
308 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000310
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000311 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000314 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
315 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000316 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000317 else
Richard Smith026b3582012-08-14 03:13:00 +0000318 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000319
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000321 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000322 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000323 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000324 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
325 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000326 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
327 | (1LL << CodeCompletionContext::CCC_Expression)
328 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
329 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000332 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000333 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000334 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000335 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336
337 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000338 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000339 }
340
341 return Contexts;
342}
343
Douglas Gregor87c08a52010-08-13 22:48:40 +0000344void ASTUnit::CacheCodeCompletionResults() {
345 if (!TheSema)
346 return;
347
Douglas Gregor213f18b2010-10-28 15:44:59 +0000348 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000349 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350
351 // Clear out the previous results.
352 ClearCachedCompletionResults();
353
354 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000355 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000356 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000357 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000358 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
359 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000360
361 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000362 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
363
Douglas Gregor87c08a52010-08-13 22:48:40 +0000364 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
365 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000367 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000369 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000370 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000371 getCodeCompletionTUInfo(),
372 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000374 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000375 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000376 CachedResult.Priority = Results[I].Priority;
377 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000378 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000379
Douglas Gregorf5586f62010-08-16 18:08:11 +0000380 // Keep track of the type of this completion in an ASTContext-agnostic
381 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000382 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000383 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000384 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000385 CachedResult.Type = 0;
386 } else {
387 CanQualType CanUsageType
388 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
389 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
390
391 // Determine whether we have already seen this type. If so, we save
392 // ourselves the work of formatting the type string by using the
393 // temporary, CanQualType-based hash table to find the associated value.
394 unsigned &TypeValue = CompletionTypes[CanUsageType];
395 if (TypeValue == 0) {
396 TypeValue = CompletionTypes.size();
397 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
398 = TypeValue;
399 }
400
401 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000402 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000403
Douglas Gregor8071e422010-08-15 06:18:01 +0000404 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000405
406 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000407 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000408 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
409 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000410 uint64_t NNSContexts
411 = (1LL << CodeCompletionContext::CCC_TopLevel)
412 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
413 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
414 | (1LL << CodeCompletionContext::CCC_Statement)
415 | (1LL << CodeCompletionContext::CCC_Expression)
416 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
417 | (1LL << CodeCompletionContext::CCC_EnumTag)
418 | (1LL << CodeCompletionContext::CCC_UnionTag)
419 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
420 | (1LL << CodeCompletionContext::CCC_Type)
421 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
422 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000423
424 if (isa<NamespaceDecl>(Results[I].Declaration) ||
425 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000426 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000427
428 if (unsigned RemainingContexts
429 = NNSContexts & ~CachedResult.ShowInContexts) {
430 // If there any contexts where this completion can be a
431 // nested-name-specifier but isn't already an option, create a
432 // nested-name-specifier completion.
433 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000434 CachedResult.Completion
435 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000436 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000437 getCodeCompletionTUInfo(),
438 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000439 CachedResult.ShowInContexts = RemainingContexts;
440 CachedResult.Priority = CCP_NestedNameSpecifier;
441 CachedResult.TypeClass = STC_Void;
442 CachedResult.Type = 0;
443 CachedCompletionResults.push_back(CachedResult);
444 }
445 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000446 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000447 }
448
Douglas Gregor87c08a52010-08-13 22:48:40 +0000449 case Result::RK_Keyword:
450 case Result::RK_Pattern:
451 // Ignore keywords and patterns; we don't care, since they are so
452 // easily regenerated.
453 break;
454
455 case Result::RK_Macro: {
456 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000457 CachedResult.Completion
458 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000459 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000460 getCodeCompletionTUInfo(),
461 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000462 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000463 = (1LL << CodeCompletionContext::CCC_TopLevel)
464 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
465 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
466 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
467 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
468 | (1LL << CodeCompletionContext::CCC_Statement)
469 | (1LL << CodeCompletionContext::CCC_Expression)
470 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
471 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
472 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
473 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
474 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000475
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476 CachedResult.Priority = Results[I].Priority;
477 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000478 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000479 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000480 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481 CachedCompletionResults.push_back(CachedResult);
482 break;
483 }
484 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000486
487 // Save the current top-level hash value.
488 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000489}
490
491void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000493 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000494 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000495}
496
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497namespace {
498
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000499/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000501class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000502 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000503 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504 LangOptions &LangOpt;
505 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000506 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507 std::string &Predefines;
508 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000514 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
515 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000516 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000517 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000518 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000519 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000520 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000521 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000523 virtual bool ReadLanguageOptions(const serialization::ModuleFile &M,
524 const LangOptions &LangOpts) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000525 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000526 return false;
527
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000528 assert(M.Kind == serialization::MK_MainFile);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000529
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000530 LangOpt = LangOpts;
531 InitializedLanguage = true;
532
533 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000534 return false;
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000537 virtual bool ReadTargetTriple(const serialization::ModuleFile &M,
538 StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000539 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000540 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000541 return false;
542
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000543 assert(M.Kind == serialization::MK_MainFile);
544
Douglas Gregor998b3d32011-09-01 23:39:15 +0000545 // FIXME: This is broken, we should store the TargetOptions in the AST file.
546 TargetOptions TargetOpts;
547 TargetOpts.ABI = "";
548 TargetOpts.CXXABI = "";
549 TargetOpts.CPU = "";
550 TargetOpts.Features.clear();
551 TargetOpts.Triple = Triple;
552 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000553
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000554 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000555 return false;
556 }
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000558 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000559 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000560 std::string &SuggestedPredefines,
561 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000562 Predefines = Buffers[0].Data;
563 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
564 Predefines += Buffers[I].Data;
565 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000566 return false;
567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000569 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000570 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
571 }
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000573 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000574 Counter = Value;
575 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000576
577private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000578 void updated() {
579 if (!Target || !InitializedLanguage)
580 return;
581
582 // Inform the target of the language options.
583 //
584 // FIXME: We shouldn't need to do this, the target should be immutable once
585 // created. This complexity should be lifted elsewhere.
586 Target->setForcedLangOptions(LangOpt);
587
588 // Initialize the preprocessor.
589 PP.Initialize(*Target);
590
591 // Initialize the ASTContext
592 Context.InitBuiltinTypes(*Target);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000593 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000594};
595
David Blaikie26e7a902011-09-26 00:01:39 +0000596class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000598
599public:
David Blaikie26e7a902011-09-26 00:01:39 +0000600 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000601 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000602 : StoredDiags(StoredDiags) { }
603
David Blaikied6471f72011-09-25 23:23:43 +0000604 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000605 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000606
607 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
608 // Just drop any diagnostics that come from cloned consumers; they'll
609 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000610 // FIXME: We'd like to be able to capture these somehow, even if it's just
611 // file/line/column, because they could occur when parsing module maps or
612 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000613 return new IgnoringDiagConsumer();
614 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000615};
616
617/// \brief RAII object that optionally captures diagnostics, if
618/// there is no diagnostic client to capture them already.
619class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000620 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000621 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000622 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000623
624public:
David Blaikied6471f72011-09-25 23:23:43 +0000625 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000626 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000627 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000628 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000629 if (RequestCapture || Diags.getClient() == 0) {
630 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000631 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000632 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000633 }
634
635 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000636 if (Diags.getClient() == &Client) {
637 Diags.takeClient();
638 Diags.setClient(PreviousClient);
639 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000640 }
641};
642
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000643} // anonymous namespace
644
David Blaikie26e7a902011-09-26 00:01:39 +0000645void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000646 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000647 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000648 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000649
Douglas Gregora88084b2010-02-18 18:08:43 +0000650 StoredDiags.push_back(StoredDiagnostic(Level, Info));
651}
652
Steve Naroff77accc12009-09-03 18:19:54 +0000653const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000654 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000655}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000656
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000657ASTDeserializationListener *ASTUnit::getDeserializationListener() {
658 if (WriterData)
659 return &WriterData->Writer;
660 return 0;
661}
662
Chris Lattner5f9e2722011-07-23 10:55:15 +0000663llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000664 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000665 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000666 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000667}
668
Douglas Gregore47be3e2010-11-11 00:39:14 +0000669/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000670void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000671 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000672 ASTUnit &AST, bool CaptureDiagnostics) {
673 if (!Diags.getPtr()) {
674 // No diagnostics engine was provided, so create our own diagnostics object
675 // with the default options.
676 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000677 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000678 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000679 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000680 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
681 ArgBegin, Client,
682 /*ShouldOwnClient=*/true,
683 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000684 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000685 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000686 }
687}
688
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000689ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000690 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000691 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000692 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000693 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000694 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000695 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000696 bool AllowPCHWithCompilerErrors,
697 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000698 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000699
700 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000701 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
702 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000703 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
704 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000705 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000706
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000707 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000708
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000709 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000710 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000711 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000712 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000713 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000714 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000715 AST->getFileManager(),
716 UserFilesAreVolatile);
Douglas Gregor8e238062011-11-11 00:35:06 +0000717 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000718 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000719 AST->ASTFileLangOpts,
720 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000721
Douglas Gregor4db64a42010-01-23 00:14:00 +0000722 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000723 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
724 if (const llvm::MemoryBuffer *
725 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
726 // Create the file entry for the file that we're mapping from.
727 const FileEntry *FromFile
728 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
729 memBuf->getBufferSize(),
730 0);
731 if (!FromFile) {
732 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
733 << RemappedFiles[I].first;
734 delete memBuf;
735 continue;
736 }
737
738 // Override the contents of the "from" file with the contents of
739 // the "to" file.
740 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
741
742 } else {
743 const char *fname = fileOrBuf.get<const char *>();
744 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
745 if (!ToFile) {
746 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
747 << RemappedFiles[I].first << fname;
748 continue;
749 }
750
751 // Create the file entry for the file that we're mapping from.
752 const FileEntry *FromFile
753 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
754 ToFile->getSize(),
755 0);
756 if (!FromFile) {
757 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
758 << RemappedFiles[I].first;
759 delete memBuf;
760 continue;
761 }
762
763 // Override the contents of the "from" file with the contents of
764 // the "to" file.
765 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000766 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000767 }
768
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000769 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000771 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000772 std::string Predefines;
773 unsigned Counter;
774
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000775 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000776
Douglas Gregor998b3d32011-09-01 23:39:15 +0000777 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
778 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
779 *AST,
780 /*IILookup=*/0,
781 /*OwnsHeaderSearch=*/false,
782 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000783 Preprocessor &PP = *AST->PP;
784
785 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
786 AST->getSourceManager(),
787 /*Target=*/0,
788 PP.getIdentifierTable(),
789 PP.getSelectorTable(),
790 PP.getBuiltinInfo(),
791 /* size_reserve = */0,
792 /*DelayInitialization=*/true);
793 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000794
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000795 bool disableValid = false;
796 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
797 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000798 Reader.reset(new ASTReader(PP, Context,
799 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000800 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000801 /*DisableStatCache=*/false,
802 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000803
804 // Recover resources if we crash before exiting this method.
805 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
806 ReaderCleanup(Reader.get());
807
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000808 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000809 AST->ASTFileLangOpts, HeaderInfo,
810 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000811
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000812 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000813 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000814 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000816 case ASTReader::Failure:
817 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000818 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000819 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000822 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
823
Daniel Dunbard5b61262009-09-21 03:03:47 +0000824 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000825 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000827 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000828 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000829 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000830 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000831 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000832
833 // Unregister the cleanup for ASTReader. It will get cleaned up
834 // by the ASTUnit cleanup.
835 ReaderCleanup.unregister();
836
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000837 Context.setExternalSource(Source);
838
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000839 // Create an AST consumer, even though it isn't used.
840 AST->Consumer.reset(new ASTConsumer);
841
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000842 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000843 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
844 AST->TheSema->Initialize();
845 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000846 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000849}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000850
851namespace {
852
Douglas Gregor9b7db622011-02-16 18:16:54 +0000853/// \brief Preprocessor callback class that updates a hash value with the names
854/// of all macros that have been defined by the translation unit.
855class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
856 unsigned &Hash;
857
858public:
859 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
860
861 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
862 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
863 }
864};
865
866/// \brief Add the given declaration to the hash of all top-level entities.
867void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
868 if (!D)
869 return;
870
871 DeclContext *DC = D->getDeclContext();
872 if (!DC)
873 return;
874
875 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
876 return;
877
878 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
879 if (ND->getIdentifier())
880 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
881 else if (DeclarationName Name = ND->getDeclName()) {
882 std::string NameStr = Name.getAsString();
883 Hash = llvm::HashString(NameStr, Hash);
884 }
885 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000886 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000887}
888
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000889class TopLevelDeclTrackerConsumer : public ASTConsumer {
890 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000891 unsigned &Hash;
892
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000893public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000894 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
895 : Unit(_Unit), Hash(Hash) {
896 Hash = 0;
897 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000898
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000899 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000900 if (!D)
901 return;
902
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000903 // FIXME: Currently ObjC method declarations are incorrectly being
904 // reported as top-level declarations, even though their DeclContext
905 // is the containing ObjC @interface/@implementation. This is a
906 // fundamental problem in the parser right now.
907 if (isa<ObjCMethodDecl>(D))
908 return;
909
910 AddTopLevelDeclarationToHash(D, Hash);
911 Unit.addTopLevelDecl(D);
912
913 handleFileLevelDecl(D);
914 }
915
916 void handleFileLevelDecl(Decl *D) {
917 Unit.addFileLevelDecl(D);
918 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
919 for (NamespaceDecl::decl_iterator
920 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
921 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000922 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000923 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000924
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000925 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000926 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
927 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000928 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000929 }
930
Sebastian Redl27372b42010-08-11 18:52:41 +0000931 // We're not interested in "interesting" decls.
932 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000933
934 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
935 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
936 handleTopLevelDecl(*it);
937 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000938
939 virtual ASTDeserializationListener *GetASTDeserializationListener() {
940 return Unit.getDeserializationListener();
941 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000942};
943
944class TopLevelDeclTrackerAction : public ASTFrontendAction {
945public:
946 ASTUnit &Unit;
947
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000948 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000949 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000950 CI.getPreprocessor().addPPCallbacks(
951 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
952 return new TopLevelDeclTrackerConsumer(Unit,
953 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000954 }
955
956public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000957 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
958
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000959 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000960 virtual TranslationUnitKind getTranslationUnitKind() {
961 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000962 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000963};
964
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000965class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000966 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000967 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000968 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000969
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000970public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000971 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000972 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000973 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000974 Hash(Unit.getCurrentTopLevelHashValue()) {
975 Hash = 0;
976 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000977
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000978 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000979 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
980 Decl *D = *it;
981 // FIXME: Currently ObjC method declarations are incorrectly being
982 // reported as top-level declarations, even though their DeclContext
983 // is the containing ObjC @interface/@implementation. This is a
984 // fundamental problem in the parser right now.
985 if (isa<ObjCMethodDecl>(D))
986 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000987 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000988 TopLevelDecls.push_back(D);
989 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000990 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000991 }
992
993 virtual void HandleTranslationUnit(ASTContext &Ctx) {
994 PCHGenerator::HandleTranslationUnit(Ctx);
995 if (!Unit.getDiagnostics().hasErrorOccurred()) {
996 // Translate the top-level declarations we captured during
997 // parsing into declaration IDs in the precompiled
998 // preamble. This will allow us to deserialize those top-level
999 // declarations when requested.
1000 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1001 Unit.addTopLevelDeclFromPreamble(
1002 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001003 }
1004 }
1005};
1006
1007class PrecompilePreambleAction : public ASTFrontendAction {
1008 ASTUnit &Unit;
1009
1010public:
1011 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1012
1013 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001014 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001015 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001016 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001017 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001018 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1019 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001020 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001021 return 0;
1022
Douglas Gregor832d6202011-07-22 16:35:34 +00001023 if (!CI.getFrontendOpts().RelocatablePCH)
1024 Sysroot.clear();
1025
Douglas Gregor9b7db622011-02-16 18:16:54 +00001026 CI.getPreprocessor().addPPCallbacks(
1027 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001028 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1029 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001030 }
1031
1032 virtual bool hasCodeCompletionSupport() const { return false; }
1033 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001034 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001035};
1036
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001037}
1038
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001039static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1040 StoredDiagnostics) {
1041 // Get rid of stored diagnostics except the ones from the driver which do not
1042 // have a source location.
1043 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1044 if (StoredDiagnostics[I].getLocation().isValid()) {
1045 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1046 --I;
1047 }
1048 }
1049}
1050
1051static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1052 StoredDiagnostics,
1053 SourceManager &SM) {
1054 // The stored diagnostic has the old source manager in it; update
1055 // the locations to refer into the new source manager. Since we've
1056 // been careful to make sure that the source manager's state
1057 // before and after are identical, so that we can reuse the source
1058 // location itself.
1059 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1060 if (StoredDiagnostics[I].getLocation().isValid()) {
1061 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1062 StoredDiagnostics[I].setLocation(Loc);
1063 }
1064 }
1065}
1066
Douglas Gregorabc563f2010-07-19 21:46:24 +00001067/// Parse the source file into a translation unit using the given compiler
1068/// invocation, replacing the current translation unit.
1069///
1070/// \returns True if a failure occurred that causes the ASTUnit not to
1071/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001072bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001073 delete SavedMainFileBuffer;
1074 SavedMainFileBuffer = 0;
1075
Ted Kremenek4f327862011-03-21 18:40:17 +00001076 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001077 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001078 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001079 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001080
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001081 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001082 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001083
1084 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001085 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1086 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001087
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001088 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001089 CCInvocation(new CompilerInvocation(*Invocation));
1090
1091 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001092 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001093
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001094 // Set up diagnostics, capturing any diagnostics that would
1095 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001096 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001097
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001098 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001099 Clang->getTargetOpts().Features = TargetFeatures;
1100 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001101 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001102 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001103 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001104 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001105 }
1106
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001107 // Inform the target of the language options.
1108 //
1109 // FIXME: We shouldn't need to do this, the target should be immutable once
1110 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001111 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001112
Ted Kremenek03201fb2011-03-21 18:40:07 +00001113 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001114 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001115 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001116 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001117 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001118 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001119
Douglas Gregorabc563f2010-07-19 21:46:24 +00001120 // Configure the various subsystems.
1121 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001122 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001123 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001124 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001125 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1126 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001127 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001128 Ctx = 0;
1129 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001130 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001131
1132 // Clear out old caches and data.
1133 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001134 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001135 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001136
Douglas Gregorf128fed2010-08-20 00:02:33 +00001137 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001138 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001139 TopLevelDeclsInPreamble.clear();
1140 }
1141
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001142 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001143 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001144
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001145 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001146 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001147
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001148 // If the main file has been overridden due to the use of a preamble,
1149 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001150 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001151 if (OverrideMainBuffer) {
1152 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1153 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1154 PreprocessorOpts.PrecompiledPreambleBytes.second
1155 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001156 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001157 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001158
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001159 // The stored diagnostic has the old source manager in it; update
1160 // the locations to refer into the new source manager. Since we've
1161 // been careful to make sure that the source manager's state
1162 // before and after are identical, so that we can reuse the source
1163 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001164 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001165
1166 // Keep track of the override buffer;
1167 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001168 }
1169
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001170 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001171 new TopLevelDeclTrackerAction(*this));
1172
1173 // Recover resources if we crash before exiting this method.
1174 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1175 ActCleanup(Act.get());
1176
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001177 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001178 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001179
1180 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001181 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001182 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1183 getSourceManager(), PreambleDiagnostics,
1184 StoredDiagnostics);
1185 }
1186
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001187 if (!Act->Execute())
1188 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001189
1190 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001191
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001192 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001193
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001194 FailedParseDiagnostics.clear();
1195
Douglas Gregorabc563f2010-07-19 21:46:24 +00001196 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001197
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001198error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001199 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001200 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001201 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001202 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001203 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001204
1205 // Keep the ownership of the data in the ASTUnit because the client may
1206 // want to see the diagnostics.
1207 transferASTDataFromCompilerInstance(*Clang);
1208 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001209 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001210 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001211 return true;
1212}
1213
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214/// \brief Simple function to retrieve a path for a preamble precompiled header.
1215static std::string GetPreamblePCHPath() {
1216 // FIXME: This is lame; sys::Path should provide this function (in particular,
1217 // it should know how to find the temporary files dir).
1218 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001219 // FIXME: This is a hack so that we can override the preamble file during
1220 // crash-recovery testing, which is the only case where the preamble files
1221 // are not necessarily cleaned up.
1222 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1223 if (TmpFile)
1224 return TmpFile;
1225
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226 std::string Error;
1227 const char *TmpDir = ::getenv("TMPDIR");
1228 if (!TmpDir)
1229 TmpDir = ::getenv("TEMP");
1230 if (!TmpDir)
1231 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001232#ifdef LLVM_ON_WIN32
1233 if (!TmpDir)
1234 TmpDir = ::getenv("USERPROFILE");
1235#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 if (!TmpDir)
1237 TmpDir = "/tmp";
1238 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001239 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001240 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001241 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001242 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001243 return std::string();
1244
Douglas Gregor44c181a2010-07-23 00:33:23 +00001245 return P.str();
1246}
1247
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001248/// \brief Compute the preamble for the main file, providing the source buffer
1249/// that corresponds to the main file along with a pair (bytes, start-of-line)
1250/// that describes the preamble.
1251std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001252ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1253 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001254 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001255 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 CreatedBuffer = false;
1257
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 // Try to determine if the main file has been remapped, either from the
1259 // command line (to another file) or directly through the compiler invocation
1260 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001261 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001262 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001263 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1264 // Check whether there is a file-file remapping of the main file
1265 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001266 M = PreprocessorOpts.remapped_file_begin(),
1267 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001268 M != E;
1269 ++M) {
1270 llvm::sys::PathWithStatus MPath(M->first);
1271 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1272 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1273 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001274 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001275 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001276 CreatedBuffer = false;
1277 }
1278
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001279 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001280 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001281 return std::make_pair((llvm::MemoryBuffer*)0,
1282 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001284 }
1285 }
1286 }
1287
1288 // Check whether there is a file-buffer remapping. It supercedes the
1289 // file-file remapping.
1290 for (PreprocessorOptions::remapped_file_buffer_iterator
1291 M = PreprocessorOpts.remapped_file_buffer_begin(),
1292 E = PreprocessorOpts.remapped_file_buffer_end();
1293 M != E;
1294 ++M) {
1295 llvm::sys::PathWithStatus MPath(M->first);
1296 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1297 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1298 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001299 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001300 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001301 CreatedBuffer = false;
1302 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001303
Douglas Gregor175c4a92010-07-23 23:58:40 +00001304 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001305 }
1306 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001307 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308 }
1309
1310 // If the main source file was not remapped, load it now.
1311 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001312 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001313 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001314 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001315
1316 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001317 }
1318
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001319 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001320 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001321 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001322}
1323
Douglas Gregor754f3492010-07-24 00:38:13 +00001324static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001325 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001326 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001327 llvm::MemoryBuffer *Result
1328 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1329 memcpy(const_cast<char*>(Result->getBufferStart()),
1330 Old->getBufferStart(), Old->getBufferSize());
1331 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001332 ' ', NewSize - Old->getBufferSize() - 1);
1333 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001334
Douglas Gregor754f3492010-07-24 00:38:13 +00001335 return Result;
1336}
1337
Douglas Gregor175c4a92010-07-23 23:58:40 +00001338/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1339/// the source file.
1340///
1341/// This routine will compute the preamble of the main source file. If a
1342/// non-trivial preamble is found, it will precompile that preamble into a
1343/// precompiled header so that the precompiled preamble can be used to reduce
1344/// reparsing time. If a precompiled preamble has already been constructed,
1345/// this routine will determine if it is still valid and, if so, avoid
1346/// rebuilding the precompiled preamble.
1347///
Douglas Gregordf95a132010-08-09 20:45:32 +00001348/// \param AllowRebuild When true (the default), this routine is
1349/// allowed to rebuild the precompiled preamble if it is found to be
1350/// out-of-date.
1351///
1352/// \param MaxLines When non-zero, the maximum number of lines that
1353/// can occur within the preamble.
1354///
Douglas Gregor754f3492010-07-24 00:38:13 +00001355/// \returns If the precompiled preamble can be used, returns a newly-allocated
1356/// buffer that should be used in place of the main file when doing so.
1357/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001358llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001359 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001360 bool AllowRebuild,
1361 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001362
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001363 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001364 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1365 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001366 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001367 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001368
1369 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001370 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001371 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001372
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001373 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001374 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001375 if (CreatedPreambleBuffer)
1376 OwnedPreambleBuffer.reset(NewPreamble.first);
1377
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001378 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001379 // We couldn't find a preamble in the main source. Clear out the current
1380 // preamble, if we have one. It's obviously no good any more.
1381 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001382 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001383
1384 // The next time we actually see a preamble, precompile it.
1385 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001386 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001387 }
1388
1389 if (!Preamble.empty()) {
1390 // We've previously computed a preamble. Check whether we have the same
1391 // preamble now that we did before, and that there's enough space in
1392 // the main-file buffer within the precompiled preamble to fit the
1393 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001394 if (Preamble.size() == NewPreamble.second.first &&
1395 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001396 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001397 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001398 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001399 // The preamble has not changed. We may be able to re-use the precompiled
1400 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001401
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001402 // Check that none of the files used by the preamble have changed.
1403 bool AnyFileChanged = false;
1404
1405 // First, make a record of those files that have been overridden via
1406 // remapping or unsaved_files.
1407 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1408 for (PreprocessorOptions::remapped_file_iterator
1409 R = PreprocessorOpts.remapped_file_begin(),
1410 REnd = PreprocessorOpts.remapped_file_end();
1411 !AnyFileChanged && R != REnd;
1412 ++R) {
1413 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001414 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001415 // If we can't stat the file we're remapping to, assume that something
1416 // horrible happened.
1417 AnyFileChanged = true;
1418 break;
1419 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001420
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001421 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1422 StatBuf.st_mtime);
1423 }
1424 for (PreprocessorOptions::remapped_file_buffer_iterator
1425 R = PreprocessorOpts.remapped_file_buffer_begin(),
1426 REnd = PreprocessorOpts.remapped_file_buffer_end();
1427 !AnyFileChanged && R != REnd;
1428 ++R) {
1429 // FIXME: Should we actually compare the contents of file->buffer
1430 // remappings?
1431 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1432 0);
1433 }
1434
1435 // Check whether anything has changed.
1436 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1437 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1438 !AnyFileChanged && F != FEnd;
1439 ++F) {
1440 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1441 = OverriddenFiles.find(F->first());
1442 if (Overridden != OverriddenFiles.end()) {
1443 // This file was remapped; check whether the newly-mapped file
1444 // matches up with the previous mapping.
1445 if (Overridden->second != F->second)
1446 AnyFileChanged = true;
1447 continue;
1448 }
1449
1450 // The file was not remapped; check whether it has changed on disk.
1451 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001452 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001453 // If we can't stat the file, assume that something horrible happened.
1454 AnyFileChanged = true;
1455 } else if (StatBuf.st_size != F->second.first ||
1456 StatBuf.st_mtime != F->second.second)
1457 AnyFileChanged = true;
1458 }
1459
1460 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001461 // Okay! We can re-use the precompiled preamble.
1462
1463 // Set the state of the diagnostic object to mimic its state
1464 // after parsing the preamble.
1465 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001466 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001467 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001468 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001469
1470 // Create a version of the main file buffer that is padded to
1471 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001472 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001473 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001474 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001475 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001476 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001477
1478 // If we aren't allowed to rebuild the precompiled preamble, just
1479 // return now.
1480 if (!AllowRebuild)
1481 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001482
Douglas Gregor175c4a92010-07-23 23:58:40 +00001483 // We can't reuse the previously-computed preamble. Build a new one.
1484 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001485 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001486 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001487 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001488 } else if (!AllowRebuild) {
1489 // We aren't allowed to rebuild the precompiled preamble; just
1490 // return now.
1491 return 0;
1492 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001493
1494 // If the preamble rebuild counter > 1, it's because we previously
1495 // failed to build a preamble and we're not yet ready to try
1496 // again. Decrement the counter and return a failure.
1497 if (PreambleRebuildCounter > 1) {
1498 --PreambleRebuildCounter;
1499 return 0;
1500 }
1501
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001502 // Create a temporary file for the precompiled preamble. In rare
1503 // circumstances, this can fail.
1504 std::string PreamblePCHPath = GetPreamblePCHPath();
1505 if (PreamblePCHPath.empty()) {
1506 // Try again next time.
1507 PreambleRebuildCounter = 1;
1508 return 0;
1509 }
1510
Douglas Gregor175c4a92010-07-23 23:58:40 +00001511 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001512 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001513 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001514
1515 // Create a new buffer that stores the preamble. The buffer also contains
1516 // extra space for the original contents of the file (which will be present
1517 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001518 // grows.
1519 PreambleReservedSize = NewPreamble.first->getBufferSize();
1520 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001521 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001523 PreambleReservedSize *= 2;
1524
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001525 // Save the preamble text for later; we'll need to compare against it for
1526 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001527 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001528 Preamble.assign(FileMgr->getFile(MainFilename),
1529 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001530 NewPreamble.first->getBufferStart()
1531 + NewPreamble.second.first);
1532 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1533
Douglas Gregor671947b2010-08-19 01:33:06 +00001534 delete PreambleBuffer;
1535 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001536 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001537 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001538 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001539 NewPreamble.first->getBufferStart(), Preamble.size());
1540 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001541 ' ', PreambleReservedSize - Preamble.size() - 1);
1542 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001543
1544 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001545 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001546 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1547
1548 // Tell the compiler invocation to generate a temporary precompiled header.
1549 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001550 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001551 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001552 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1553 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001554
1555 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001556 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001557
1558 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001559 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1560 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001561
Douglas Gregor01b6e312011-07-01 18:22:13 +00001562 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001563 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001564
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001565 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001566 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001567
1568 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001569 Clang->getTargetOpts().Features = TargetFeatures;
1570 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1571 Clang->getTargetOpts()));
1572 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001573 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1574 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001575 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001576 PreprocessorOpts.eraseRemappedFile(
1577 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001578 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579 }
1580
1581 // Inform the target of the language options.
1582 //
1583 // FIXME: We shouldn't need to do this, the target should be immutable once
1584 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001585 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001586
Ted Kremenek03201fb2011-03-21 18:40:07 +00001587 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001588 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001589 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001591 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001592 "IR inputs not support here!");
1593
1594 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001595 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001596 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001597 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001598 TopLevelDecls.clear();
1599 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001600
1601 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001602 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001603
1604 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001605 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001606 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001607
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001608 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001609 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001610 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001611 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1612 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001613 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001614 PreprocessorOpts.eraseRemappedFile(
1615 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001616 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001617 }
1618
1619 Act->Execute();
1620 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001621
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001622 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001623 // There were errors parsing the preamble, so no precompiled header was
1624 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001625 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001626 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1627 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001628 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001629 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001630 PreprocessorOpts.eraseRemappedFile(
1631 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001632 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001633 }
1634
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001635 // Transfer any diagnostics generated when parsing the preamble into the set
1636 // of preamble diagnostics.
1637 PreambleDiagnostics.clear();
1638 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001639 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001640 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001641
Douglas Gregor175c4a92010-07-23 23:58:40 +00001642 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001643 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001644 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001645
1646 // Keep track of all of the files that the source manager knows about,
1647 // so we can verify whether they have changed or not.
1648 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001649 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001650 const llvm::MemoryBuffer *MainFileBuffer
1651 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1652 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1653 FEnd = SourceMgr.fileinfo_end();
1654 F != FEnd;
1655 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001656 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001657 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1658 continue;
1659
1660 FilesInPreamble[File->getName()]
1661 = std::make_pair(F->second->getSize(), File->getModificationTime());
1662 }
1663
Douglas Gregoreababfb2010-08-04 05:53:38 +00001664 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001665 PreprocessorOpts.eraseRemappedFile(
1666 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001667
1668 // If the hash of top-level entities differs from the hash of the top-level
1669 // entities the last time we rebuilt the preamble, clear out the completion
1670 // cache.
1671 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1672 CompletionCacheTopLevelHashValue = 0;
1673 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1674 }
1675
Douglas Gregor754f3492010-07-24 00:38:13 +00001676 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001677 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001678 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001679}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001680
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001681void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1682 std::vector<Decl *> Resolved;
1683 Resolved.reserve(TopLevelDeclsInPreamble.size());
1684 ExternalASTSource &Source = *getASTContext().getExternalSource();
1685 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1686 // Resolve the declaration ID to an actual declaration, possibly
1687 // deserializing the declaration in the process.
1688 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1689 if (D)
1690 Resolved.push_back(D);
1691 }
1692 TopLevelDeclsInPreamble.clear();
1693 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1694}
1695
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001696void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1697 // Steal the created target, context, and preprocessor.
1698 TheSema.reset(CI.takeSema());
1699 Consumer.reset(CI.takeASTConsumer());
1700 Ctx = &CI.getASTContext();
1701 PP = &CI.getPreprocessor();
1702 CI.setSourceManager(0);
1703 CI.setFileManager(0);
1704 Target = &CI.getTarget();
1705 Reader = CI.getModuleManager();
1706}
1707
Chris Lattner5f9e2722011-07-23 10:55:15 +00001708StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001709 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001710}
1711
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001712ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001713 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001714 bool CaptureDiagnostics,
1715 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001716 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001717 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001718 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001719 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001720 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001721 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001722 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001723 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1724 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1725 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001726
1727 return AST.take();
1728}
1729
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001730ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001731 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001732 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001733 ASTUnit *Unit,
1734 bool Persistent,
1735 StringRef ResourceFilesPath,
1736 bool OnlyLocalDecls,
1737 bool CaptureDiagnostics,
1738 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001739 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001740 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001741 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001742 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001743 assert(CI && "A CompilerInvocation is required");
1744
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001745 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001746 ASTUnit *AST = Unit;
1747 if (!AST) {
1748 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001749 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001750 AST = OwnAST.get();
1751 }
1752
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001753 if (!ResourceFilesPath.empty()) {
1754 // Override the resources path.
1755 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1756 }
1757 AST->OnlyLocalDecls = OnlyLocalDecls;
1758 AST->CaptureDiagnostics = CaptureDiagnostics;
1759 if (PrecompilePreamble)
1760 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001761 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001762 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001763 AST->IncludeBriefCommentsInCodeCompletion
1764 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765
1766 // Recover resources if we crash before exiting this method.
1767 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001768 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001769 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1770 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001771 DiagCleanup(Diags.getPtr());
1772
1773 // We'll manage file buffers ourselves.
1774 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1775 CI->getFrontendOpts().DisableFree = false;
1776 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1777
1778 // Save the target features.
1779 AST->TargetFeatures = CI->getTargetOpts().Features;
1780
1781 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001782 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001783
1784 // Recover resources if we crash before exiting this method.
1785 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1786 CICleanup(Clang.get());
1787
1788 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001789 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001790
1791 // Set up diagnostics, capturing any diagnostics that would
1792 // otherwise be dropped.
1793 Clang->setDiagnostics(&AST->getDiagnostics());
1794
1795 // Create the target instance.
1796 Clang->getTargetOpts().Features = AST->TargetFeatures;
1797 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1798 Clang->getTargetOpts()));
1799 if (!Clang->hasTarget())
1800 return 0;
1801
1802 // Inform the target of the language options.
1803 //
1804 // FIXME: We shouldn't need to do this, the target should be immutable once
1805 // created. This complexity should be lifted elsewhere.
1806 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1807
1808 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1809 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001810 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001811 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001812 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813 "IR inputs not supported here!");
1814
1815 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001816 AST->TheSema.reset();
1817 AST->Ctx = 0;
1818 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001819 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001820
1821 // Create a file manager object to provide access to and cache the filesystem.
1822 Clang->setFileManager(&AST->getFileManager());
1823
1824 // Create the source manager.
1825 Clang->setSourceManager(&AST->getSourceManager());
1826
1827 ASTFrontendAction *Act = Action;
1828
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001829 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001830 if (!Act) {
1831 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1832 Act = TrackerAct.get();
1833 }
1834
1835 // Recover resources if we crash before exiting this method.
1836 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1837 ActCleanup(TrackerAct.get());
1838
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001839 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1840 AST->transferASTDataFromCompilerInstance(*Clang);
1841 if (OwnAST && ErrAST)
1842 ErrAST->swap(OwnAST);
1843
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001844 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001845 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001846
1847 if (Persistent && !TrackerAct) {
1848 Clang->getPreprocessor().addPPCallbacks(
1849 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1850 std::vector<ASTConsumer*> Consumers;
1851 if (Clang->hasASTConsumer())
1852 Consumers.push_back(Clang->takeASTConsumer());
1853 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1854 AST->getCurrentTopLevelHashValue()));
1855 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1856 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001857 if (!Act->Execute()) {
1858 AST->transferASTDataFromCompilerInstance(*Clang);
1859 if (OwnAST && ErrAST)
1860 ErrAST->swap(OwnAST);
1861
1862 return 0;
1863 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001864
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001865 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001866 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001867
1868 Act->EndSourceFile();
1869
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001870 if (OwnAST)
1871 return OwnAST.take();
1872 else
1873 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001874}
1875
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001876bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1877 if (!Invocation)
1878 return true;
1879
1880 // We'll manage file buffers ourselves.
1881 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1882 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001883 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001884
Douglas Gregor1aa27302011-01-27 18:02:58 +00001885 // Save the target features.
1886 TargetFeatures = Invocation->getTargetOpts().Features;
1887
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001888 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001889 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001890 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001891 OverrideMainBuffer
1892 = getMainBufferWithPrecompiledPreamble(*Invocation);
1893 }
1894
Douglas Gregor213f18b2010-10-28 15:44:59 +00001895 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001896 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001897
Ted Kremenek25a11e12011-03-22 01:15:24 +00001898 // Recover resources if we crash before exiting this method.
1899 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1900 MemBufferCleanup(OverrideMainBuffer);
1901
Douglas Gregor213f18b2010-10-28 15:44:59 +00001902 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001903}
1904
Douglas Gregorabc563f2010-07-19 21:46:24 +00001905ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001906 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001907 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001908 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001909 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001910 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001911 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001912 bool IncludeBriefCommentsInCodeCompletion,
1913 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001914 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001915 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001916 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001917 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001918 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001919 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001920 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001921 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001922 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001923 AST->IncludeBriefCommentsInCodeCompletion
1924 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001925 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001926 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001927
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001928 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001929 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1930 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001931 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1932 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001933 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001934
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001935 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001936}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001937
1938ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1939 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001940 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001941 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001942 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001943 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001944 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001945 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001946 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001947 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001948 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001949 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001950 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001951 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001952 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001953 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001954 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001955 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001956 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001957 // No diagnostics engine was provided, so create our own diagnostics object
1958 // with the default options.
1959 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001960 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1961 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001962 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001963
Chris Lattner5f9e2722011-07-23 10:55:15 +00001964 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001965
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001966 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001967
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001968 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001969
Douglas Gregore47be3e2010-11-11 00:39:14 +00001970 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001971 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001972
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001973 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001974 llvm::makeArrayRef(ArgBegin, ArgEnd),
1975 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001976 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001977 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001978 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001979
Douglas Gregor4db64a42010-01-23 00:14:00 +00001980 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001981 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1982 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1983 if (const llvm::MemoryBuffer *
1984 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1985 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1986 } else {
1987 const char *fname = fileOrBuf.get<const char *>();
1988 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1989 }
1990 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001991 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1992 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1993 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001994
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001995 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001996 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001997
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001998 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1999
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002000 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002001 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002002 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002003 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002004 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002005 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002006 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002007 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002008 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002009 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002010 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002011 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002012 AST->IncludeBriefCommentsInCodeCompletion
2013 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002014 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002015 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002016 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002017 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002018 if (ForSerialization)
2019 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002020 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002021
2022 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002023 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2024 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002025
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002026 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2027 // Some error occurred, if caller wants to examine diagnostics, pass it the
2028 // ASTUnit.
2029 if (ErrAST) {
2030 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2031 ErrAST->swap(AST);
2032 }
2033 return 0;
2034 }
2035
2036 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002037}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002038
2039bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002040 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002041 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002042
2043 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002044
Douglas Gregor213f18b2010-10-28 15:44:59 +00002045 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002046 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002047
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002048 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002049 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002050 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002051 for (PreprocessorOptions::remapped_file_buffer_iterator
2052 R = PPOpts.remapped_file_buffer_begin(),
2053 REnd = PPOpts.remapped_file_buffer_end();
2054 R != REnd;
2055 ++R) {
2056 delete R->second;
2057 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002058 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002059 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2060 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2061 if (const llvm::MemoryBuffer *
2062 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2063 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2064 memBuf);
2065 } else {
2066 const char *fname = fileOrBuf.get<const char *>();
2067 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2068 fname);
2069 }
2070 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002071
Douglas Gregoreababfb2010-08-04 05:53:38 +00002072 // If we have a preamble file lying around, or if we might try to
2073 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002074 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002075 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002076 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002077
Douglas Gregorabc563f2010-07-19 21:46:24 +00002078 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002079 getDiagnostics().Reset();
2080 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002081 if (OverrideMainBuffer)
2082 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002083
Douglas Gregor175c4a92010-07-23 23:58:40 +00002084 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002085 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002086
2087 // If we're caching global code-completion results, and the top-level
2088 // declarations have changed, clear out the code-completion cache.
2089 if (!Result && ShouldCacheCodeCompletionResults &&
2090 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2091 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002092
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002093 // We now need to clear out the completion info related to this translation
2094 // unit; it'll be recreated if necessary.
2095 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002096
Douglas Gregor175c4a92010-07-23 23:58:40 +00002097 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002098}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002099
Douglas Gregor87c08a52010-08-13 22:48:40 +00002100//----------------------------------------------------------------------------//
2101// Code completion
2102//----------------------------------------------------------------------------//
2103
2104namespace {
2105 /// \brief Code completion consumer that combines the cached code-completion
2106 /// results from an ASTUnit with the code-completion results provided to it,
2107 /// then passes the result on to
2108 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002109 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002110 ASTUnit &AST;
2111 CodeCompleteConsumer &Next;
2112
2113 public:
2114 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002115 const CodeCompleteOptions &CodeCompleteOpts)
2116 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2117 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002118 {
2119 // Compute the set of contexts in which we will look when we don't have
2120 // any information about the specific context.
2121 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002122 = (1LL << CodeCompletionContext::CCC_TopLevel)
2123 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2124 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2125 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2126 | (1LL << CodeCompletionContext::CCC_Statement)
2127 | (1LL << CodeCompletionContext::CCC_Expression)
2128 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2129 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2130 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2131 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2132 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2133 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2134 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002135
David Blaikie4e4d0842012-03-11 07:00:24 +00002136 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002137 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2138 | (1LL << CodeCompletionContext::CCC_UnionTag)
2139 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002140 }
2141
2142 virtual void ProcessCodeCompleteResults(Sema &S,
2143 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002144 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002145 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002146
2147 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2148 OverloadCandidate *Candidates,
2149 unsigned NumCandidates) {
2150 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2151 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002152
Douglas Gregordae68752011-02-01 22:57:45 +00002153 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002154 return Next.getAllocator();
2155 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002156
2157 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2158 return Next.getCodeCompletionTUInfo();
2159 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002160 };
2161}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002162
Douglas Gregor5f808c22010-08-16 21:18:39 +00002163/// \brief Helper function that computes which global names are hidden by the
2164/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002165static void CalculateHiddenNames(const CodeCompletionContext &Context,
2166 CodeCompletionResult *Results,
2167 unsigned NumResults,
2168 ASTContext &Ctx,
2169 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002170 bool OnlyTagNames = false;
2171 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002172 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002173 case CodeCompletionContext::CCC_TopLevel:
2174 case CodeCompletionContext::CCC_ObjCInterface:
2175 case CodeCompletionContext::CCC_ObjCImplementation:
2176 case CodeCompletionContext::CCC_ObjCIvarList:
2177 case CodeCompletionContext::CCC_ClassStructUnion:
2178 case CodeCompletionContext::CCC_Statement:
2179 case CodeCompletionContext::CCC_Expression:
2180 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002181 case CodeCompletionContext::CCC_DotMemberAccess:
2182 case CodeCompletionContext::CCC_ArrowMemberAccess:
2183 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002184 case CodeCompletionContext::CCC_Namespace:
2185 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002186 case CodeCompletionContext::CCC_Name:
2187 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002188 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002189 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002190 break;
2191
2192 case CodeCompletionContext::CCC_EnumTag:
2193 case CodeCompletionContext::CCC_UnionTag:
2194 case CodeCompletionContext::CCC_ClassOrStructTag:
2195 OnlyTagNames = true;
2196 break;
2197
2198 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002199 case CodeCompletionContext::CCC_MacroName:
2200 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002201 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002202 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002203 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002204 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002205 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002206 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002207 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002208 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2209 case CodeCompletionContext::CCC_ObjCClassMessage:
2210 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002211 // We're looking for nothing, or we're looking for names that cannot
2212 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002213 return;
2214 }
2215
John McCall0a2c5e22010-08-25 06:19:51 +00002216 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002217 for (unsigned I = 0; I != NumResults; ++I) {
2218 if (Results[I].Kind != Result::RK_Declaration)
2219 continue;
2220
2221 unsigned IDNS
2222 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2223
2224 bool Hiding = false;
2225 if (OnlyTagNames)
2226 Hiding = (IDNS & Decl::IDNS_Tag);
2227 else {
2228 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002229 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2230 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002232 HiddenIDNS |= Decl::IDNS_Tag;
2233 Hiding = (IDNS & HiddenIDNS);
2234 }
2235
2236 if (!Hiding)
2237 continue;
2238
2239 DeclarationName Name = Results[I].Declaration->getDeclName();
2240 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2241 HiddenNames.insert(Identifier->getName());
2242 else
2243 HiddenNames.insert(Name.getAsString());
2244 }
2245}
2246
2247
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002248void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2249 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002250 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002251 unsigned NumResults) {
2252 // Merge the results we were given with the results we cached.
2253 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002254 uint64_t InContexts =
2255 Context.getKind() == CodeCompletionContext::CCC_Recovery
2256 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002257 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002258 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002259 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002260 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002261 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002262 C = AST.cached_completion_begin(),
2263 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002264 C != CEnd; ++C) {
2265 // If the context we are in matches any of the contexts we are
2266 // interested in, we'll add this result.
2267 if ((C->ShowInContexts & InContexts) == 0)
2268 continue;
2269
2270 // If we haven't added any results previously, do so now.
2271 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002272 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2273 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002274 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2275 AddedResult = true;
2276 }
2277
Douglas Gregor5f808c22010-08-16 21:18:39 +00002278 // Determine whether this global completion result is hidden by a local
2279 // completion result. If so, skip it.
2280 if (C->Kind != CXCursor_MacroDefinition &&
2281 HiddenNames.count(C->Completion->getTypedText()))
2282 continue;
2283
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002284 // Adjust priority based on similar type classes.
2285 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002286 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002287 if (!Context.getPreferredType().isNull()) {
2288 if (C->Kind == CXCursor_MacroDefinition) {
2289 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002290 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002291 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002292 } else if (C->Type) {
2293 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002294 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002295 Context.getPreferredType().getUnqualifiedType());
2296 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2297 if (ExpectedSTC == C->TypeClass) {
2298 // We know this type is similar; check for an exact match.
2299 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002300 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002302 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002303 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2304 Priority /= CCF_ExactTypeMatch;
2305 else
2306 Priority /= CCF_SimilarTypeMatch;
2307 }
2308 }
2309 }
2310
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002311 // Adjust the completion string, if required.
2312 if (C->Kind == CXCursor_MacroDefinition &&
2313 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2314 // Create a new code-completion string that just contains the
2315 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002316 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2317 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002318 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002319 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002320 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002321 }
2322
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002323 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002324 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002325 }
2326
2327 // If we did not add any cached completion results, just forward the
2328 // results we were given to the next consumer.
2329 if (!AddedResult) {
2330 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2331 return;
2332 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002333
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002334 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2335 AllResults.size());
2336}
2337
2338
2339
Chris Lattner5f9e2722011-07-23 10:55:15 +00002340void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341 RemappedFile *RemappedFiles,
2342 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002343 bool IncludeMacros,
2344 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002345 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002346 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002347 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002349 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2350 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002351 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002352 return;
2353
Douglas Gregor213f18b2010-10-28 15:44:59 +00002354 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002355 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002356 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002357
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002358 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002359 CCInvocation(new CompilerInvocation(*Invocation));
2360
2361 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002362 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002363 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002364
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002365 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2366 CachedCompletionResults.empty();
2367 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2368 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2369 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2370
2371 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2372
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002373 FrontendOpts.CodeCompletionAt.FileName = File;
2374 FrontendOpts.CodeCompletionAt.Line = Line;
2375 FrontendOpts.CodeCompletionAt.Column = Column;
2376
2377 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002378 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002379
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002380 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002381
2382 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002383 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2384 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002385
Ted Kremenek4f327862011-03-21 18:40:17 +00002386 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002387 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002388
2389 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002390 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002391 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002392 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002393 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002394 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002395
2396 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002397 Clang->getTargetOpts().Features = TargetFeatures;
2398 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2399 Clang->getTargetOpts()));
2400 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002401 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002402 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002403 }
2404
2405 // Inform the target of the language options.
2406 //
2407 // FIXME: We shouldn't need to do this, the target should be immutable once
2408 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002409 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002410
Ted Kremenek03201fb2011-03-21 18:40:07 +00002411 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002412 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002413 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002414 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002415 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002416 "IR inputs not support here!");
2417
2418
2419 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002420 Clang->setFileManager(&FileMgr);
2421 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002422
2423 // Remap files.
2424 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002425 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002426 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002427 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2428 if (const llvm::MemoryBuffer *
2429 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2430 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2431 OwnedBuffers.push_back(memBuf);
2432 } else {
2433 const char *fname = fileOrBuf.get<const char *>();
2434 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2435 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002436 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002437
Douglas Gregor87c08a52010-08-13 22:48:40 +00002438 // Use the code completion consumer we were given, but adding any cached
2439 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002440 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002441 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002442 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002443
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002444 Clang->getFrontendOpts().SkipFunctionBodies = true;
2445
Douglas Gregordf95a132010-08-09 20:45:32 +00002446 // If we have a precompiled preamble, try to use it. We only allow
2447 // the use of the precompiled preamble if we're if the completion
2448 // point is within the main file, after the end of the precompiled
2449 // preamble.
2450 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002451 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002452 using llvm::sys::FileStatus;
2453 llvm::sys::PathWithStatus CompleteFilePath(File);
2454 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2455 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2456 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002457 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2458 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002459 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002460 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002461 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002462 }
2463
2464 // If the main file has been overridden due to the use of a preamble,
2465 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002466 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002467 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002468 stored_diag_begin(),
2469 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002470 if (OverrideMainBuffer) {
2471 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2472 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2473 PreprocessorOpts.PrecompiledPreambleBytes.second
2474 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002475 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002476 PreprocessorOpts.DisablePCHValidation = true;
2477
Douglas Gregor2283d792010-08-20 00:59:43 +00002478 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002479 } else {
2480 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2481 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002482 }
2483
Douglas Gregordca8ee82011-05-06 16:33:08 +00002484 // Disable the preprocessing record
2485 PreprocessorOpts.DetailedRecord = false;
2486
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002487 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002488 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002489 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002490 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002491 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002492 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2493 getSourceManager(), PreambleDiagnostics,
2494 StoredDiagnostics);
2495 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002496 Act->Execute();
2497 Act->EndSourceFile();
2498 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002499
2500 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002501}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002502
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002503bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002504 // Write to a temporary file and later rename it to the actual file, to avoid
2505 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002506 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002507 TempPath = File;
2508 TempPath += "-%%%%%%%%";
2509 int fd;
2510 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2511 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002512 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002513
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002514 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2515 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002516 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002517
2518 serialize(Out);
2519 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002520 if (Out.has_error()) {
2521 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002522 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002523 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002524
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002525 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002526 bool exists;
2527 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002528 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002529 }
2530
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002531 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002532}
2533
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002534static bool serializeUnit(ASTWriter &Writer,
2535 SmallVectorImpl<char> &Buffer,
2536 Sema &S,
2537 bool hasErrors,
2538 raw_ostream &OS) {
2539 Writer.WriteAST(S, 0, std::string(), 0, "", hasErrors);
2540
2541 // Write the generated bitstream to "Out".
2542 if (!Buffer.empty())
2543 OS.write(Buffer.data(), Buffer.size());
2544
2545 return false;
2546}
2547
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002549 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002550
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002551 if (WriterData)
2552 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2553 getSema(), hasErrors, OS);
2554
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002555 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002556 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002557 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002558 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002559}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002560
2561typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2562
2563static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2564 unsigned Raw = L.getRawEncoding();
2565 const unsigned MacroBit = 1U << 31;
2566 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2567 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2568}
2569
2570void ASTUnit::TranslateStoredDiagnostics(
2571 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002573 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 const SmallVectorImpl<StoredDiagnostic> &Diags,
2575 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002576 // The stored diagnostic has the old source manager in it; update
2577 // the locations to refer into the new source manager. We also need to remap
2578 // all the locations to the new view. This includes the diag location, any
2579 // associated source ranges, and the source ranges of associated fix-its.
2580 // FIXME: There should be a cleaner way to do this.
2581
Chris Lattner5f9e2722011-07-23 10:55:15 +00002582 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002583 Result.reserve(Diags.size());
2584 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002585 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002586 assert(Mod && "Don't have preamble module");
2587 SLocRemap &Remap = Mod->SLocRemap;
2588 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2589 // Rebuild the StoredDiagnostic.
2590 const StoredDiagnostic &SD = Diags[I];
2591 SourceLocation L = SD.getLocation();
2592 TranslateSLoc(L, Remap);
2593 FullSourceLoc Loc(L, SrcMgr);
2594
Chris Lattner5f9e2722011-07-23 10:55:15 +00002595 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002596 Ranges.reserve(SD.range_size());
2597 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2598 E = SD.range_end();
2599 I != E; ++I) {
2600 SourceLocation BL = I->getBegin();
2601 TranslateSLoc(BL, Remap);
2602 SourceLocation EL = I->getEnd();
2603 TranslateSLoc(EL, Remap);
2604 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2605 }
2606
Chris Lattner5f9e2722011-07-23 10:55:15 +00002607 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002608 FixIts.reserve(SD.fixit_size());
2609 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2610 E = SD.fixit_end();
2611 I != E; ++I) {
2612 FixIts.push_back(FixItHint());
2613 FixItHint &FH = FixIts.back();
2614 FH.CodeToInsert = I->CodeToInsert;
2615 SourceLocation BL = I->RemoveRange.getBegin();
2616 TranslateSLoc(BL, Remap);
2617 SourceLocation EL = I->RemoveRange.getEnd();
2618 TranslateSLoc(EL, Remap);
2619 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2620 I->RemoveRange.isTokenRange());
2621 }
2622
2623 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2624 SD.getMessage(), Loc, Ranges, FixIts));
2625 }
2626 Result.swap(Out);
2627}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002628
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002629static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2630 std::pair<unsigned, Decl *> R) {
2631 return L.first < R.first;
2632}
2633
2634void ASTUnit::addFileLevelDecl(Decl *D) {
2635 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002636
2637 // We only care about local declarations.
2638 if (D->isFromASTFile())
2639 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002640
2641 SourceManager &SM = *SourceMgr;
2642 SourceLocation Loc = D->getLocation();
2643 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2644 return;
2645
2646 // We only keep track of the file-level declarations of each file.
2647 if (!D->getLexicalDeclContext()->isFileContext())
2648 return;
2649
2650 SourceLocation FileLoc = SM.getFileLoc(Loc);
2651 assert(SM.isLocalSourceLocation(FileLoc));
2652 FileID FID;
2653 unsigned Offset;
2654 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2655 if (FID.isInvalid())
2656 return;
2657
2658 LocDeclsTy *&Decls = FileDecls[FID];
2659 if (!Decls)
2660 Decls = new LocDeclsTy();
2661
2662 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2663
2664 if (Decls->empty() || Decls->back().first <= Offset) {
2665 Decls->push_back(LocDecl);
2666 return;
2667 }
2668
2669 LocDeclsTy::iterator
2670 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2671
2672 Decls->insert(I, LocDecl);
2673}
2674
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002675void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2676 SmallVectorImpl<Decl *> &Decls) {
2677 if (File.isInvalid())
2678 return;
2679
2680 if (SourceMgr->isLoadedFileID(File)) {
2681 assert(Ctx->getExternalSource() && "No external source!");
2682 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2683 Decls);
2684 }
2685
2686 FileDeclsTy::iterator I = FileDecls.find(File);
2687 if (I == FileDecls.end())
2688 return;
2689
2690 LocDeclsTy &LocDecls = *I->second;
2691 if (LocDecls.empty())
2692 return;
2693
2694 LocDeclsTy::iterator
2695 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2696 std::make_pair(Offset, (Decl*)0), compLocDecl);
2697 if (BeginIt != LocDecls.begin())
2698 --BeginIt;
2699
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002700 // If we are pointing at a top-level decl inside an objc container, we need
2701 // to backtrack until we find it otherwise we will fail to report that the
2702 // region overlaps with an objc container.
2703 while (BeginIt != LocDecls.begin() &&
2704 BeginIt->second->isTopLevelDeclInObjCContainer())
2705 --BeginIt;
2706
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002707 LocDeclsTy::iterator
2708 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2709 std::make_pair(Offset+Length, (Decl*)0),
2710 compLocDecl);
2711 if (EndIt != LocDecls.end())
2712 ++EndIt;
2713
2714 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2715 Decls.push_back(DIt->second);
2716}
2717
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002718SourceLocation ASTUnit::getLocation(const FileEntry *File,
2719 unsigned Line, unsigned Col) const {
2720 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002721 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002722 return SM.getMacroArgExpandedLocation(Loc);
2723}
2724
2725SourceLocation ASTUnit::getLocation(const FileEntry *File,
2726 unsigned Offset) const {
2727 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002728 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002729 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2730}
2731
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002732/// \brief If \arg Loc is a loaded location from the preamble, returns
2733/// the corresponding local location of the main file, otherwise it returns
2734/// \arg Loc.
2735SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2736 FileID PreambleID;
2737 if (SourceMgr)
2738 PreambleID = SourceMgr->getPreambleFileID();
2739
2740 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2741 return Loc;
2742
2743 unsigned Offs;
2744 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2745 SourceLocation FileLoc
2746 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2747 return FileLoc.getLocWithOffset(Offs);
2748 }
2749
2750 return Loc;
2751}
2752
2753/// \brief If \arg Loc is a local location of the main file but inside the
2754/// preamble chunk, returns the corresponding loaded location from the
2755/// preamble, otherwise it returns \arg Loc.
2756SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2757 FileID PreambleID;
2758 if (SourceMgr)
2759 PreambleID = SourceMgr->getPreambleFileID();
2760
2761 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2762 return Loc;
2763
2764 unsigned Offs;
2765 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2766 Offs < Preamble.size()) {
2767 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2768 return FileLoc.getLocWithOffset(Offs);
2769 }
2770
2771 return Loc;
2772}
2773
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002774bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2775 FileID FID;
2776 if (SourceMgr)
2777 FID = SourceMgr->getPreambleFileID();
2778
2779 if (Loc.isInvalid() || FID.isInvalid())
2780 return false;
2781
2782 return SourceMgr->isInFileID(Loc, FID);
2783}
2784
2785bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2786 FileID FID;
2787 if (SourceMgr)
2788 FID = SourceMgr->getMainFileID();
2789
2790 if (Loc.isInvalid() || FID.isInvalid())
2791 return false;
2792
2793 return SourceMgr->isInFileID(Loc, FID);
2794}
2795
2796SourceLocation ASTUnit::getEndOfPreambleFileID() {
2797 FileID FID;
2798 if (SourceMgr)
2799 FID = SourceMgr->getPreambleFileID();
2800
2801 if (FID.isInvalid())
2802 return SourceLocation();
2803
2804 return SourceMgr->getLocForEndOfFile(FID);
2805}
2806
2807SourceLocation ASTUnit::getStartOfMainFileID() {
2808 FileID FID;
2809 if (SourceMgr)
2810 FID = SourceMgr->getMainFileID();
2811
2812 if (FID.isInvalid())
2813 return SourceLocation();
2814
2815 return SourceMgr->getLocForStartOfFile(FID);
2816}
2817
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002818std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2819ASTUnit::getLocalPreprocessingEntities() const {
2820 if (isMainFileAST()) {
2821 serialization::ModuleFile &
2822 Mod = Reader->getModuleManager().getPrimaryModule();
2823 return Reader->getModulePreprocessedEntities(Mod);
2824 }
2825
2826 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2827 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2828
2829 return std::make_pair(PreprocessingRecord::iterator(),
2830 PreprocessingRecord::iterator());
2831}
2832
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002833bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002834 if (isMainFileAST()) {
2835 serialization::ModuleFile &
2836 Mod = Reader->getModuleManager().getPrimaryModule();
2837 ASTReader::ModuleDeclIterator MDI, MDE;
2838 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2839 for (; MDI != MDE; ++MDI) {
2840 if (!Fn(context, *MDI))
2841 return false;
2842 }
2843
2844 return true;
2845 }
2846
2847 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2848 TLEnd = top_level_end();
2849 TL != TLEnd; ++TL) {
2850 if (!Fn(context, *TL))
2851 return false;
2852 }
2853
2854 return true;
2855}
2856
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002857namespace {
2858struct PCHLocatorInfo {
2859 serialization::ModuleFile *Mod;
2860 PCHLocatorInfo() : Mod(0) {}
2861};
2862}
2863
2864static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2865 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2866 switch (M.Kind) {
2867 case serialization::MK_Module:
2868 return true; // skip dependencies.
2869 case serialization::MK_PCH:
2870 Info.Mod = &M;
2871 return true; // found it.
2872 case serialization::MK_Preamble:
2873 return false; // look in dependencies.
2874 case serialization::MK_MainFile:
2875 return false; // look in dependencies.
2876 }
2877
2878 return true;
2879}
2880
2881const FileEntry *ASTUnit::getPCHFile() {
2882 if (!Reader)
2883 return 0;
2884
2885 PCHLocatorInfo Info;
2886 Reader->getModuleManager().visit(PCHLocator, &Info);
2887 if (Info.Mod)
2888 return Info.Mod->File;
2889
2890 return 0;
2891}
2892
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002893bool ASTUnit::isModuleFile() {
2894 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2895}
2896
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002897void ASTUnit::PreambleData::countLines() const {
2898 NumLines = 0;
2899 if (empty())
2900 return;
2901
2902 for (std::vector<char>::const_iterator
2903 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2904 if (*I == '\n')
2905 ++NumLines;
2906 }
2907 if (Buffer.back() != '\n')
2908 ++NumLines;
2909}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002910
2911#ifndef NDEBUG
2912ASTUnit::ConcurrencyState::ConcurrencyState() {
2913 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2914}
2915
2916ASTUnit::ConcurrencyState::~ConcurrencyState() {
2917 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2918}
2919
2920void ASTUnit::ConcurrencyState::start() {
2921 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2922 assert(acquired && "Concurrent access to ASTUnit!");
2923}
2924
2925void ASTUnit::ConcurrencyState::finish() {
2926 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2927}
2928
2929#else // NDEBUG
2930
2931ASTUnit::ConcurrencyState::ConcurrencyState() {}
2932ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2933void ASTUnit::ConcurrencyState::start() {}
2934void ASTUnit::ConcurrencyState::finish() {}
2935
2936#endif