blob: d2f63a80fee9c2ecefbaca909ab76439753ba396 [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) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000119 // No mutex required here since we are leaving the program.
Ted Kremenek1872b312011-10-27 17:55:18 +0000120 OnDiskDataMap &M = getOnDiskDataMap();
121 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
122 // We don't worry about freeing the memory associated with OnDiskDataMap.
123 // All we care about is erasing stale files.
124 I->second->Cleanup();
125 }
126}
127
128static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000129 // We require the mutex since we are modifying the structure of the
130 // DenseMap.
131 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000132 OnDiskDataMap &M = getOnDiskDataMap();
133 OnDiskData *&D = M[AU];
134 if (!D)
135 D = new OnDiskData();
136 return *D;
137}
138
139static void erasePreambleFile(const ASTUnit *AU) {
140 getOnDiskData(AU).CleanPreambleFile();
141}
142
143static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000144 // We require the mutex since we are modifying the structure of the
145 // DenseMap.
146 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000147 OnDiskDataMap &M = getOnDiskDataMap();
148 OnDiskDataMap::iterator I = M.find(AU);
149 if (I != M.end()) {
150 I->second->Cleanup();
151 delete I->second;
152 M.erase(AU);
153 }
154}
155
156static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
157 getOnDiskData(AU).PreambleFile = preambleFile;
158}
159
160static const std::string &getPreambleFile(const ASTUnit *AU) {
161 return getOnDiskData(AU).PreambleFile;
162}
163
164void OnDiskData::CleanTemporaryFiles() {
165 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
166 TemporaryFiles[I].eraseFromDisk();
167 TemporaryFiles.clear();
168}
169
170void OnDiskData::CleanPreambleFile() {
171 if (!PreambleFile.empty()) {
172 llvm::sys::Path(PreambleFile).eraseFromDisk();
173 PreambleFile.clear();
174 }
175}
176
177void OnDiskData::Cleanup() {
178 CleanTemporaryFiles();
179 CleanPreambleFile();
180}
181
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000182void ASTUnit::clearFileLevelDecls() {
183 for (FileDeclsTy::iterator
184 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
185 delete I->second;
186 FileDecls.clear();
187}
188
Ted Kremenek1872b312011-10-27 17:55:18 +0000189void ASTUnit::CleanTemporaryFiles() {
190 getOnDiskData(this).CleanTemporaryFiles();
191}
192
193void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
194 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000195}
196
Douglas Gregoreababfb2010-08-04 05:53:38 +0000197/// \brief After failing to build a precompiled preamble (due to
198/// errors in the source that occurs in the preamble), the number of
199/// reparses during which we'll skip even trying to precompile the
200/// preamble.
201const unsigned DefaultPreambleRebuildInterval = 5;
202
Douglas Gregore3c60a72010-11-17 00:13:31 +0000203/// \brief Tracks the number of ASTUnit objects that are currently active.
204///
205/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000206static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000207
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000208ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000209 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000210 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000211 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000212 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000213 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000214 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000215 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000216 ShouldCacheCodeCompletionResults(false),
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000217 IncludeBriefCommentsInCodeCompletion(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000218 CompletionCacheTopLevelHashValue(0),
219 PreambleTopLevelHashValue(0),
220 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000221 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000222 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000223 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000224 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
225 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000226}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000227
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000228ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000229 clearFileLevelDecls();
230
Ted Kremenek1872b312011-10-27 17:55:18 +0000231 // Clean up the temporary files and the preamble file.
232 removeOnDiskEntry(this);
233
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000234 // Free the buffers associated with remapped files. We are required to
235 // perform this operation here because we explicitly request that the
236 // compiler instance *not* free these buffers for each invocation of the
237 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000238 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000239 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
240 for (PreprocessorOptions::remapped_file_buffer_iterator
241 FB = PPOpts.remapped_file_buffer_begin(),
242 FBEnd = PPOpts.remapped_file_buffer_end();
243 FB != FBEnd;
244 ++FB)
245 delete FB->second;
246 }
Douglas Gregor28233422010-07-27 14:52:07 +0000247
248 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000249 delete PreambleBuffer;
250
Douglas Gregor213f18b2010-10-28 15:44:59 +0000251 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000252
253 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000254 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000255 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
256 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000257}
258
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000259void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
260
Douglas Gregor8071e422010-08-15 06:18:01 +0000261/// \brief Determine the set of code-completion contexts in which this
262/// declaration should be shown.
263static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000264 const LangOptions &LangOpts,
265 bool &IsNestedNameSpecifier) {
266 IsNestedNameSpecifier = false;
267
Douglas Gregor8071e422010-08-15 06:18:01 +0000268 if (isa<UsingShadowDecl>(ND))
269 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
270 if (!ND)
271 return 0;
272
273 unsigned Contexts = 0;
274 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
275 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
276 // Types can appear in these contexts.
277 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
278 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
279 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
280 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
281 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000282 | (1 << (CodeCompletionContext::CCC_Type - 1))
283 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000284
285 // In C++, types can appear in expressions contexts (for functional casts).
286 if (LangOpts.CPlusPlus)
287 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
288
289 // In Objective-C, message sends can send interfaces. In Objective-C++,
290 // all types are available due to functional casts.
291 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
292 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000293
294 // In Objective-C, you can only be a subclass of another Objective-C class
295 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000296 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000297
298 // Deal with tag names.
299 if (isa<EnumDecl>(ND)) {
300 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
301
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000302 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000303 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000304 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000305 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
306 if (Record->isUnion())
307 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
308 else
309 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
310
Douglas Gregor8071e422010-08-15 06:18:01 +0000311 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000312 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000313 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000315 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
316 // Values can appear in these contexts.
317 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
318 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000319 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
321 } else if (isa<ObjCProtocolDecl>(ND)) {
322 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000323 } else if (isa<ObjCCategoryDecl>(ND)) {
324 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000326 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000327
328 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 }
331
332 return Contexts;
333}
334
Douglas Gregor87c08a52010-08-13 22:48:40 +0000335void ASTUnit::CacheCodeCompletionResults() {
336 if (!TheSema)
337 return;
338
Douglas Gregor213f18b2010-10-28 15:44:59 +0000339 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000340 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000341
342 // Clear out the previous results.
343 ClearCachedCompletionResults();
344
345 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000346 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000347 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000348 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000349 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
350 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000351
352 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000353 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
354
Douglas Gregor87c08a52010-08-13 22:48:40 +0000355 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
356 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000357 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000358 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000359 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000360 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000361 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000362 getCodeCompletionTUInfo(),
363 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000364 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000365 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000366 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 CachedResult.Priority = Results[I].Priority;
368 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000369 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000370
Douglas Gregorf5586f62010-08-16 18:08:11 +0000371 // Keep track of the type of this completion in an ASTContext-agnostic
372 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000373 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000374 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000375 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000376 CachedResult.Type = 0;
377 } else {
378 CanQualType CanUsageType
379 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
380 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
381
382 // Determine whether we have already seen this type. If so, we save
383 // ourselves the work of formatting the type string by using the
384 // temporary, CanQualType-based hash table to find the associated value.
385 unsigned &TypeValue = CompletionTypes[CanUsageType];
386 if (TypeValue == 0) {
387 TypeValue = CompletionTypes.size();
388 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
389 = TypeValue;
390 }
391
392 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000393 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000394
Douglas Gregor8071e422010-08-15 06:18:01 +0000395 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000396
397 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000398 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000399 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
400 // The contexts in which a nested-name-specifier can appear in C++.
401 unsigned NNSContexts
402 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
403 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
404 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
405 | (1 << (CodeCompletionContext::CCC_Statement - 1))
406 | (1 << (CodeCompletionContext::CCC_Expression - 1))
407 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
408 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
409 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
410 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000411 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000412 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
413 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000414
415 if (isa<NamespaceDecl>(Results[I].Declaration) ||
416 isa<NamespaceAliasDecl>(Results[I].Declaration))
417 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
418
419 if (unsigned RemainingContexts
420 = NNSContexts & ~CachedResult.ShowInContexts) {
421 // If there any contexts where this completion can be a
422 // nested-name-specifier but isn't already an option, create a
423 // nested-name-specifier completion.
424 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000425 CachedResult.Completion
426 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000427 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000428 getCodeCompletionTUInfo(),
429 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000430 CachedResult.ShowInContexts = RemainingContexts;
431 CachedResult.Priority = CCP_NestedNameSpecifier;
432 CachedResult.TypeClass = STC_Void;
433 CachedResult.Type = 0;
434 CachedCompletionResults.push_back(CachedResult);
435 }
436 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000437 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000438 }
439
Douglas Gregor87c08a52010-08-13 22:48:40 +0000440 case Result::RK_Keyword:
441 case Result::RK_Pattern:
442 // Ignore keywords and patterns; we don't care, since they are so
443 // easily regenerated.
444 break;
445
446 case Result::RK_Macro: {
447 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000448 CachedResult.Completion
449 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000450 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000451 getCodeCompletionTUInfo(),
452 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000453 CachedResult.ShowInContexts
454 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
455 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
456 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
457 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
458 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
459 | (1 << (CodeCompletionContext::CCC_Statement - 1))
460 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000461 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000462 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000463 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000464 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
465 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000466
Douglas Gregor87c08a52010-08-13 22:48:40 +0000467 CachedResult.Priority = Results[I].Priority;
468 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000469 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000470 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000471 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000472 CachedCompletionResults.push_back(CachedResult);
473 break;
474 }
475 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000477
478 // Save the current top-level hash value.
479 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000480}
481
482void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000484 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000485 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000486}
487
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000488namespace {
489
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000490/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000491/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000492class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000493 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000494 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000495 LangOptions &LangOpt;
496 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000497 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498 std::string &Predefines;
499 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000503 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000505 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
506 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000507 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000508 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000511 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000515 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000516 return false;
517
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000518 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000519
520 // Initialize the preprocessor.
521 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000522
523 // Initialize the ASTContext
524 Context.InitBuiltinTypes(*Target);
525
526 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000527 return false;
528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner5f9e2722011-07-23 10:55:15 +0000530 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000531 // If we've already initialized the target, don't do it again.
532 if (Target)
533 return false;
534
535 // FIXME: This is broken, we should store the TargetOptions in the AST file.
536 TargetOptions TargetOpts;
537 TargetOpts.ABI = "";
538 TargetOpts.CXXABI = "";
539 TargetOpts.CPU = "";
540 TargetOpts.Features.clear();
541 TargetOpts.Triple = Triple;
542 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000543 return false;
544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000546 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000547 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000548 std::string &SuggestedPredefines,
549 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000550 Predefines = Buffers[0].Data;
551 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
552 Predefines += Buffers[I].Data;
553 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 return false;
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000557 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000558 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000561 virtual void ReadCounter(unsigned Value) {
562 Counter = Value;
563 }
564};
565
David Blaikie26e7a902011-09-26 00:01:39 +0000566class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000567 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000568
569public:
David Blaikie26e7a902011-09-26 00:01:39 +0000570 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000571 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000572 : StoredDiags(StoredDiags) { }
573
David Blaikied6471f72011-09-25 23:23:43 +0000574 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000575 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000576
577 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
578 // Just drop any diagnostics that come from cloned consumers; they'll
579 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000580 // FIXME: We'd like to be able to capture these somehow, even if it's just
581 // file/line/column, because they could occur when parsing module maps or
582 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000583 return new IgnoringDiagConsumer();
584 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000585};
586
587/// \brief RAII object that optionally captures diagnostics, if
588/// there is no diagnostic client to capture them already.
589class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000590 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000591 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000592 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000593
594public:
David Blaikied6471f72011-09-25 23:23:43 +0000595 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000596 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000597 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000598 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000599 if (RequestCapture || Diags.getClient() == 0) {
600 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000601 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000602 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000603 }
604
605 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000606 if (Diags.getClient() == &Client) {
607 Diags.takeClient();
608 Diags.setClient(PreviousClient);
609 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000610 }
611};
612
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000613} // anonymous namespace
614
David Blaikie26e7a902011-09-26 00:01:39 +0000615void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000616 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000617 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000618 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000619
Douglas Gregora88084b2010-02-18 18:08:43 +0000620 StoredDiags.push_back(StoredDiagnostic(Level, Info));
621}
622
Steve Naroff77accc12009-09-03 18:19:54 +0000623const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000624 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000625}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000626
Chris Lattner5f9e2722011-07-23 10:55:15 +0000627llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000628 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000629 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000630 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000631}
632
Douglas Gregore47be3e2010-11-11 00:39:14 +0000633/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000634void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000635 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000636 ASTUnit &AST, bool CaptureDiagnostics) {
637 if (!Diags.getPtr()) {
638 // No diagnostics engine was provided, so create our own diagnostics object
639 // with the default options.
640 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000641 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000642 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000643 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000644 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
645 ArgBegin, Client,
646 /*ShouldOwnClient=*/true,
647 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000648 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000650 }
651}
652
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000653ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000655 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000656 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000657 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000658 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000659 bool CaptureDiagnostics,
660 bool AllowPCHWithCompilerErrors) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000661 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000662
663 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000664 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
665 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000666 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
667 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000668 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000669
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000670 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000671
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000672 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000673 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000674 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000675 AST->FileMgr = new FileManager(FileSystemOpts);
676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
677 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000678 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000679 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000680 AST->ASTFileLangOpts,
681 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000682
Douglas Gregor4db64a42010-01-23 00:14:00 +0000683 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000684 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
685 if (const llvm::MemoryBuffer *
686 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
687 // Create the file entry for the file that we're mapping from.
688 const FileEntry *FromFile
689 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
690 memBuf->getBufferSize(),
691 0);
692 if (!FromFile) {
693 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
694 << RemappedFiles[I].first;
695 delete memBuf;
696 continue;
697 }
698
699 // Override the contents of the "from" file with the contents of
700 // the "to" file.
701 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
702
703 } else {
704 const char *fname = fileOrBuf.get<const char *>();
705 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
706 if (!ToFile) {
707 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
708 << RemappedFiles[I].first << fname;
709 continue;
710 }
711
712 // Create the file entry for the file that we're mapping from.
713 const FileEntry *FromFile
714 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
715 ToFile->getSize(),
716 0);
717 if (!FromFile) {
718 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
719 << RemappedFiles[I].first;
720 delete memBuf;
721 continue;
722 }
723
724 // Override the contents of the "from" file with the contents of
725 // the "to" file.
726 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000727 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000728 }
729
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000730 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000732 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000733 std::string Predefines;
734 unsigned Counter;
735
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000736 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000737
Douglas Gregor998b3d32011-09-01 23:39:15 +0000738 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
739 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
740 *AST,
741 /*IILookup=*/0,
742 /*OwnsHeaderSearch=*/false,
743 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000744 Preprocessor &PP = *AST->PP;
745
746 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
747 AST->getSourceManager(),
748 /*Target=*/0,
749 PP.getIdentifierTable(),
750 PP.getSelectorTable(),
751 PP.getBuiltinInfo(),
752 /* size_reserve = */0,
753 /*DelayInitialization=*/true);
754 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000755
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000756 Reader.reset(new ASTReader(PP, Context,
757 /*isysroot=*/"",
758 /*DisableValidation=*/false,
759 /*DisableStatCache=*/false,
760 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000761
762 // Recover resources if we crash before exiting this method.
763 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
764 ReaderCleanup(Reader.get());
765
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000766 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000767 AST->ASTFileLangOpts, HeaderInfo,
768 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000769
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000770 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000771 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000772 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000774 case ASTReader::Failure:
775 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000776 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000777 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000780 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
781
Daniel Dunbard5b61262009-09-21 03:03:47 +0000782 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000783 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000785 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000786 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000787 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000788 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000789 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000790
791 // Unregister the cleanup for ASTReader. It will get cleaned up
792 // by the ASTUnit cleanup.
793 ReaderCleanup.unregister();
794
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000795 Context.setExternalSource(Source);
796
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000797 // Create an AST consumer, even though it isn't used.
798 AST->Consumer.reset(new ASTConsumer);
799
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000800 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000801 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
802 AST->TheSema->Initialize();
803 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000804 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000805
Mike Stump1eb44332009-09-09 15:08:12 +0000806 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000807}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000808
809namespace {
810
Douglas Gregor9b7db622011-02-16 18:16:54 +0000811/// \brief Preprocessor callback class that updates a hash value with the names
812/// of all macros that have been defined by the translation unit.
813class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
814 unsigned &Hash;
815
816public:
817 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
818
819 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
820 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
821 }
822};
823
824/// \brief Add the given declaration to the hash of all top-level entities.
825void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
826 if (!D)
827 return;
828
829 DeclContext *DC = D->getDeclContext();
830 if (!DC)
831 return;
832
833 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
834 return;
835
836 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
837 if (ND->getIdentifier())
838 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
839 else if (DeclarationName Name = ND->getDeclName()) {
840 std::string NameStr = Name.getAsString();
841 Hash = llvm::HashString(NameStr, Hash);
842 }
843 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000844 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000845}
846
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000847class TopLevelDeclTrackerConsumer : public ASTConsumer {
848 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000849 unsigned &Hash;
850
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000851public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000852 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
853 : Unit(_Unit), Hash(Hash) {
854 Hash = 0;
855 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000856
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000857 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000858 if (!D)
859 return;
860
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000861 // FIXME: Currently ObjC method declarations are incorrectly being
862 // reported as top-level declarations, even though their DeclContext
863 // is the containing ObjC @interface/@implementation. This is a
864 // fundamental problem in the parser right now.
865 if (isa<ObjCMethodDecl>(D))
866 return;
867
868 AddTopLevelDeclarationToHash(D, Hash);
869 Unit.addTopLevelDecl(D);
870
871 handleFileLevelDecl(D);
872 }
873
874 void handleFileLevelDecl(Decl *D) {
875 Unit.addFileLevelDecl(D);
876 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
877 for (NamespaceDecl::decl_iterator
878 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
879 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000880 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000881 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000882
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000883 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000884 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
885 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000886 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000887 }
888
Sebastian Redl27372b42010-08-11 18:52:41 +0000889 // We're not interested in "interesting" decls.
890 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000891
892 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
893 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
894 handleTopLevelDecl(*it);
895 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000896};
897
898class TopLevelDeclTrackerAction : public ASTFrontendAction {
899public:
900 ASTUnit &Unit;
901
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000902 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000903 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000904 CI.getPreprocessor().addPPCallbacks(
905 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
906 return new TopLevelDeclTrackerConsumer(Unit,
907 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000908 }
909
910public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000911 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
912
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000913 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000914 virtual TranslationUnitKind getTranslationUnitKind() {
915 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000916 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000917};
918
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000919class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000920 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000921 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000922 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000923
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000924public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000925 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000926 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000927 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000928 Hash(Unit.getCurrentTopLevelHashValue()) {
929 Hash = 0;
930 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000931
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000932 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000933 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
934 Decl *D = *it;
935 // FIXME: Currently ObjC method declarations are incorrectly being
936 // reported as top-level declarations, even though their DeclContext
937 // is the containing ObjC @interface/@implementation. This is a
938 // fundamental problem in the parser right now.
939 if (isa<ObjCMethodDecl>(D))
940 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000941 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000942 TopLevelDecls.push_back(D);
943 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000944 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000945 }
946
947 virtual void HandleTranslationUnit(ASTContext &Ctx) {
948 PCHGenerator::HandleTranslationUnit(Ctx);
949 if (!Unit.getDiagnostics().hasErrorOccurred()) {
950 // Translate the top-level declarations we captured during
951 // parsing into declaration IDs in the precompiled
952 // preamble. This will allow us to deserialize those top-level
953 // declarations when requested.
954 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
955 Unit.addTopLevelDeclFromPreamble(
956 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000957 }
958 }
959};
960
961class PrecompilePreambleAction : public ASTFrontendAction {
962 ASTUnit &Unit;
963
964public:
965 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
966
967 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000968 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000969 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000970 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000971 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000972 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
973 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000974 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000975 return 0;
976
Douglas Gregor832d6202011-07-22 16:35:34 +0000977 if (!CI.getFrontendOpts().RelocatablePCH)
978 Sysroot.clear();
979
Douglas Gregor9b7db622011-02-16 18:16:54 +0000980 CI.getPreprocessor().addPPCallbacks(
981 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000982 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
983 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000984 }
985
986 virtual bool hasCodeCompletionSupport() const { return false; }
987 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000988 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000989};
990
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000991}
992
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000993static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
994 StoredDiagnostics) {
995 // Get rid of stored diagnostics except the ones from the driver which do not
996 // have a source location.
997 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
998 if (StoredDiagnostics[I].getLocation().isValid()) {
999 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1000 --I;
1001 }
1002 }
1003}
1004
1005static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1006 StoredDiagnostics,
1007 SourceManager &SM) {
1008 // The stored diagnostic has the old source manager in it; update
1009 // the locations to refer into the new source manager. Since we've
1010 // been careful to make sure that the source manager's state
1011 // before and after are identical, so that we can reuse the source
1012 // location itself.
1013 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1014 if (StoredDiagnostics[I].getLocation().isValid()) {
1015 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1016 StoredDiagnostics[I].setLocation(Loc);
1017 }
1018 }
1019}
1020
Douglas Gregorabc563f2010-07-19 21:46:24 +00001021/// Parse the source file into a translation unit using the given compiler
1022/// invocation, replacing the current translation unit.
1023///
1024/// \returns True if a failure occurred that causes the ASTUnit not to
1025/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001026bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001027 delete SavedMainFileBuffer;
1028 SavedMainFileBuffer = 0;
1029
Ted Kremenek4f327862011-03-21 18:40:17 +00001030 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001031 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001032 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001033 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001034
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001035 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001036 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001037
1038 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001039 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1040 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001041
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001042 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001043 CCInvocation(new CompilerInvocation(*Invocation));
1044
1045 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001046 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001047
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001048 // Set up diagnostics, capturing any diagnostics that would
1049 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001050 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001051
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001052 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001053 Clang->getTargetOpts().Features = TargetFeatures;
1054 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001055 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001056 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001057 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001058 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001059 }
1060
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001061 // Inform the target of the language options.
1062 //
1063 // FIXME: We shouldn't need to do this, the target should be immutable once
1064 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001065 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001066
Ted Kremenek03201fb2011-03-21 18:40:07 +00001067 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001068 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001069 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001070 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001071 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001072 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001073
Douglas Gregorabc563f2010-07-19 21:46:24 +00001074 // Configure the various subsystems.
1075 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001076 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001077 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001078 FileMgr = new FileManager(FileSystemOpts);
1079 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001080 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001081 Ctx = 0;
1082 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001083 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001084
1085 // Clear out old caches and data.
1086 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001087 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001089
Douglas Gregorf128fed2010-08-20 00:02:33 +00001090 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001091 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001092 TopLevelDeclsInPreamble.clear();
1093 }
1094
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001095 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001096 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001097
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001098 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001099 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001100
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001101 // If the main file has been overridden due to the use of a preamble,
1102 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001103 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001104 if (OverrideMainBuffer) {
1105 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1106 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1107 PreprocessorOpts.PrecompiledPreambleBytes.second
1108 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001109 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001110 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001111
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001112 // The stored diagnostic has the old source manager in it; update
1113 // the locations to refer into the new source manager. Since we've
1114 // been careful to make sure that the source manager's state
1115 // before and after are identical, so that we can reuse the source
1116 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001117 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001118
1119 // Keep track of the override buffer;
1120 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001121 }
1122
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001123 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001124 new TopLevelDeclTrackerAction(*this));
1125
1126 // Recover resources if we crash before exiting this method.
1127 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1128 ActCleanup(Act.get());
1129
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001130 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001131 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001132
1133 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001134 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001135 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1136 getSourceManager(), PreambleDiagnostics,
1137 StoredDiagnostics);
1138 }
1139
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001140 if (!Act->Execute())
1141 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001142
1143 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001144
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001145 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001146
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001147 FailedParseDiagnostics.clear();
1148
Douglas Gregorabc563f2010-07-19 21:46:24 +00001149 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001150
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001151error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001152 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001153 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001154 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001155 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001156 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001157
1158 // Keep the ownership of the data in the ASTUnit because the client may
1159 // want to see the diagnostics.
1160 transferASTDataFromCompilerInstance(*Clang);
1161 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001162 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001163 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001164 return true;
1165}
1166
Douglas Gregor44c181a2010-07-23 00:33:23 +00001167/// \brief Simple function to retrieve a path for a preamble precompiled header.
1168static std::string GetPreamblePCHPath() {
1169 // FIXME: This is lame; sys::Path should provide this function (in particular,
1170 // it should know how to find the temporary files dir).
1171 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001172 // FIXME: This is a hack so that we can override the preamble file during
1173 // crash-recovery testing, which is the only case where the preamble files
1174 // are not necessarily cleaned up.
1175 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1176 if (TmpFile)
1177 return TmpFile;
1178
Douglas Gregor44c181a2010-07-23 00:33:23 +00001179 std::string Error;
1180 const char *TmpDir = ::getenv("TMPDIR");
1181 if (!TmpDir)
1182 TmpDir = ::getenv("TEMP");
1183 if (!TmpDir)
1184 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001185#ifdef LLVM_ON_WIN32
1186 if (!TmpDir)
1187 TmpDir = ::getenv("USERPROFILE");
1188#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001189 if (!TmpDir)
1190 TmpDir = "/tmp";
1191 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001192 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001193 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001194 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001195 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001196 return std::string();
1197
Douglas Gregor44c181a2010-07-23 00:33:23 +00001198 return P.str();
1199}
1200
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001201/// \brief Compute the preamble for the main file, providing the source buffer
1202/// that corresponds to the main file along with a pair (bytes, start-of-line)
1203/// that describes the preamble.
1204std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001205ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1206 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001207 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001208 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001209 CreatedBuffer = false;
1210
Douglas Gregor44c181a2010-07-23 00:33:23 +00001211 // Try to determine if the main file has been remapped, either from the
1212 // command line (to another file) or directly through the compiler invocation
1213 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001214 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001215 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1217 // Check whether there is a file-file remapping of the main file
1218 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001219 M = PreprocessorOpts.remapped_file_begin(),
1220 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001221 M != E;
1222 ++M) {
1223 llvm::sys::PathWithStatus MPath(M->first);
1224 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1225 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1226 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001227 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001229 CreatedBuffer = false;
1230 }
1231
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001232 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001234 return std::make_pair((llvm::MemoryBuffer*)0,
1235 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001236 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001237 }
1238 }
1239 }
1240
1241 // Check whether there is a file-buffer remapping. It supercedes the
1242 // file-file remapping.
1243 for (PreprocessorOptions::remapped_file_buffer_iterator
1244 M = PreprocessorOpts.remapped_file_buffer_begin(),
1245 E = PreprocessorOpts.remapped_file_buffer_end();
1246 M != E;
1247 ++M) {
1248 llvm::sys::PathWithStatus MPath(M->first);
1249 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1250 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1251 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001254 CreatedBuffer = false;
1255 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256
Douglas Gregor175c4a92010-07-23 23:58:40 +00001257 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 }
1259 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001260 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261 }
1262
1263 // If the main source file was not remapped, load it now.
1264 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001265 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001267 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001268
1269 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001270 }
1271
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001272 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001273 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001274 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001275}
1276
Douglas Gregor754f3492010-07-24 00:38:13 +00001277static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001278 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001279 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001280 llvm::MemoryBuffer *Result
1281 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1282 memcpy(const_cast<char*>(Result->getBufferStart()),
1283 Old->getBufferStart(), Old->getBufferSize());
1284 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001285 ' ', NewSize - Old->getBufferSize() - 1);
1286 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001287
Douglas Gregor754f3492010-07-24 00:38:13 +00001288 return Result;
1289}
1290
Douglas Gregor175c4a92010-07-23 23:58:40 +00001291/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1292/// the source file.
1293///
1294/// This routine will compute the preamble of the main source file. If a
1295/// non-trivial preamble is found, it will precompile that preamble into a
1296/// precompiled header so that the precompiled preamble can be used to reduce
1297/// reparsing time. If a precompiled preamble has already been constructed,
1298/// this routine will determine if it is still valid and, if so, avoid
1299/// rebuilding the precompiled preamble.
1300///
Douglas Gregordf95a132010-08-09 20:45:32 +00001301/// \param AllowRebuild When true (the default), this routine is
1302/// allowed to rebuild the precompiled preamble if it is found to be
1303/// out-of-date.
1304///
1305/// \param MaxLines When non-zero, the maximum number of lines that
1306/// can occur within the preamble.
1307///
Douglas Gregor754f3492010-07-24 00:38:13 +00001308/// \returns If the precompiled preamble can be used, returns a newly-allocated
1309/// buffer that should be used in place of the main file when doing so.
1310/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001311llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001312 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001313 bool AllowRebuild,
1314 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001315
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001316 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001317 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1318 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001319 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001320 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001321
1322 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001323 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001324 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001325
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001326 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001327 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001328 if (CreatedPreambleBuffer)
1329 OwnedPreambleBuffer.reset(NewPreamble.first);
1330
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001331 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001332 // We couldn't find a preamble in the main source. Clear out the current
1333 // preamble, if we have one. It's obviously no good any more.
1334 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001335 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001336
1337 // The next time we actually see a preamble, precompile it.
1338 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001339 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001340 }
1341
1342 if (!Preamble.empty()) {
1343 // We've previously computed a preamble. Check whether we have the same
1344 // preamble now that we did before, and that there's enough space in
1345 // the main-file buffer within the precompiled preamble to fit the
1346 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001347 if (Preamble.size() == NewPreamble.second.first &&
1348 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001349 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001350 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001351 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001352 // The preamble has not changed. We may be able to re-use the precompiled
1353 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001354
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001355 // Check that none of the files used by the preamble have changed.
1356 bool AnyFileChanged = false;
1357
1358 // First, make a record of those files that have been overridden via
1359 // remapping or unsaved_files.
1360 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1361 for (PreprocessorOptions::remapped_file_iterator
1362 R = PreprocessorOpts.remapped_file_begin(),
1363 REnd = PreprocessorOpts.remapped_file_end();
1364 !AnyFileChanged && R != REnd;
1365 ++R) {
1366 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001367 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001368 // If we can't stat the file we're remapping to, assume that something
1369 // horrible happened.
1370 AnyFileChanged = true;
1371 break;
1372 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001373
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001374 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1375 StatBuf.st_mtime);
1376 }
1377 for (PreprocessorOptions::remapped_file_buffer_iterator
1378 R = PreprocessorOpts.remapped_file_buffer_begin(),
1379 REnd = PreprocessorOpts.remapped_file_buffer_end();
1380 !AnyFileChanged && R != REnd;
1381 ++R) {
1382 // FIXME: Should we actually compare the contents of file->buffer
1383 // remappings?
1384 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1385 0);
1386 }
1387
1388 // Check whether anything has changed.
1389 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1390 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1391 !AnyFileChanged && F != FEnd;
1392 ++F) {
1393 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1394 = OverriddenFiles.find(F->first());
1395 if (Overridden != OverriddenFiles.end()) {
1396 // This file was remapped; check whether the newly-mapped file
1397 // matches up with the previous mapping.
1398 if (Overridden->second != F->second)
1399 AnyFileChanged = true;
1400 continue;
1401 }
1402
1403 // The file was not remapped; check whether it has changed on disk.
1404 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001405 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001406 // If we can't stat the file, assume that something horrible happened.
1407 AnyFileChanged = true;
1408 } else if (StatBuf.st_size != F->second.first ||
1409 StatBuf.st_mtime != F->second.second)
1410 AnyFileChanged = true;
1411 }
1412
1413 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001414 // Okay! We can re-use the precompiled preamble.
1415
1416 // Set the state of the diagnostic object to mimic its state
1417 // after parsing the preamble.
1418 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001419 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001420 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001421 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001422
1423 // Create a version of the main file buffer that is padded to
1424 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001425 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001426 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001427 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001428 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001429 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001430
1431 // If we aren't allowed to rebuild the precompiled preamble, just
1432 // return now.
1433 if (!AllowRebuild)
1434 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001435
Douglas Gregor175c4a92010-07-23 23:58:40 +00001436 // We can't reuse the previously-computed preamble. Build a new one.
1437 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001438 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001439 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001440 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001441 } else if (!AllowRebuild) {
1442 // We aren't allowed to rebuild the precompiled preamble; just
1443 // return now.
1444 return 0;
1445 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001446
1447 // If the preamble rebuild counter > 1, it's because we previously
1448 // failed to build a preamble and we're not yet ready to try
1449 // again. Decrement the counter and return a failure.
1450 if (PreambleRebuildCounter > 1) {
1451 --PreambleRebuildCounter;
1452 return 0;
1453 }
1454
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001455 // Create a temporary file for the precompiled preamble. In rare
1456 // circumstances, this can fail.
1457 std::string PreamblePCHPath = GetPreamblePCHPath();
1458 if (PreamblePCHPath.empty()) {
1459 // Try again next time.
1460 PreambleRebuildCounter = 1;
1461 return 0;
1462 }
1463
Douglas Gregor175c4a92010-07-23 23:58:40 +00001464 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001465 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001466 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001467
1468 // Create a new buffer that stores the preamble. The buffer also contains
1469 // extra space for the original contents of the file (which will be present
1470 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001471 // grows.
1472 PreambleReservedSize = NewPreamble.first->getBufferSize();
1473 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001474 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001475 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001476 PreambleReservedSize *= 2;
1477
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001478 // Save the preamble text for later; we'll need to compare against it for
1479 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001480 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001481 Preamble.assign(FileMgr->getFile(MainFilename),
1482 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001483 NewPreamble.first->getBufferStart()
1484 + NewPreamble.second.first);
1485 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1486
Douglas Gregor671947b2010-08-19 01:33:06 +00001487 delete PreambleBuffer;
1488 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001489 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001490 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001491 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001492 NewPreamble.first->getBufferStart(), Preamble.size());
1493 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001494 ' ', PreambleReservedSize - Preamble.size() - 1);
1495 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001496
1497 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001498 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001499 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1500
1501 // Tell the compiler invocation to generate a temporary precompiled header.
1502 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001503 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001504 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001505 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1506 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001507
1508 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001509 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001510
1511 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001512 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1513 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001514
Douglas Gregor01b6e312011-07-01 18:22:13 +00001515 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001516 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001517
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001518 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001519 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001520
1521 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001522 Clang->getTargetOpts().Features = TargetFeatures;
1523 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1524 Clang->getTargetOpts()));
1525 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001526 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1527 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001528 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001529 PreprocessorOpts.eraseRemappedFile(
1530 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001531 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001532 }
1533
1534 // Inform the target of the language options.
1535 //
1536 // FIXME: We shouldn't need to do this, the target should be immutable once
1537 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001538 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001539
Ted Kremenek03201fb2011-03-21 18:40:07 +00001540 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001541 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001542 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001543 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001544 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001545 "IR inputs not support here!");
1546
1547 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001548 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001549 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001550 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001551 TopLevelDecls.clear();
1552 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001553
1554 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001555 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001556
1557 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001558 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001559 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001560
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001561 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001562 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001563 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001564 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1565 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001566 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001567 PreprocessorOpts.eraseRemappedFile(
1568 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001569 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001570 }
1571
1572 Act->Execute();
1573 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001574
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001575 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001576 // There were errors parsing the preamble, so no precompiled header was
1577 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001578 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001579 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1580 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001581 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001582 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001583 PreprocessorOpts.eraseRemappedFile(
1584 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001585 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001586 }
1587
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001588 // Transfer any diagnostics generated when parsing the preamble into the set
1589 // of preamble diagnostics.
1590 PreambleDiagnostics.clear();
1591 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001592 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001593 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001594
Douglas Gregor175c4a92010-07-23 23:58:40 +00001595 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001596 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001597 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001598
1599 // Keep track of all of the files that the source manager knows about,
1600 // so we can verify whether they have changed or not.
1601 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001602 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001603 const llvm::MemoryBuffer *MainFileBuffer
1604 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1605 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1606 FEnd = SourceMgr.fileinfo_end();
1607 F != FEnd;
1608 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001609 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001610 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1611 continue;
1612
1613 FilesInPreamble[File->getName()]
1614 = std::make_pair(F->second->getSize(), File->getModificationTime());
1615 }
1616
Douglas Gregoreababfb2010-08-04 05:53:38 +00001617 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001618 PreprocessorOpts.eraseRemappedFile(
1619 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001620
1621 // If the hash of top-level entities differs from the hash of the top-level
1622 // entities the last time we rebuilt the preamble, clear out the completion
1623 // cache.
1624 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1625 CompletionCacheTopLevelHashValue = 0;
1626 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1627 }
1628
Douglas Gregor754f3492010-07-24 00:38:13 +00001629 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001630 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001631 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001632}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001633
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001634void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1635 std::vector<Decl *> Resolved;
1636 Resolved.reserve(TopLevelDeclsInPreamble.size());
1637 ExternalASTSource &Source = *getASTContext().getExternalSource();
1638 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1639 // Resolve the declaration ID to an actual declaration, possibly
1640 // deserializing the declaration in the process.
1641 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1642 if (D)
1643 Resolved.push_back(D);
1644 }
1645 TopLevelDeclsInPreamble.clear();
1646 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1647}
1648
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001649void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1650 // Steal the created target, context, and preprocessor.
1651 TheSema.reset(CI.takeSema());
1652 Consumer.reset(CI.takeASTConsumer());
1653 Ctx = &CI.getASTContext();
1654 PP = &CI.getPreprocessor();
1655 CI.setSourceManager(0);
1656 CI.setFileManager(0);
1657 Target = &CI.getTarget();
1658 Reader = CI.getModuleManager();
1659}
1660
Chris Lattner5f9e2722011-07-23 10:55:15 +00001661StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001662 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001663}
1664
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001665ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001666 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001667 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001668 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001669 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001670 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001671 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001672 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001673 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001674 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001675 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001676
1677 return AST.take();
1678}
1679
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001680ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001681 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001682 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001683 ASTUnit *Unit,
1684 bool Persistent,
1685 StringRef ResourceFilesPath,
1686 bool OnlyLocalDecls,
1687 bool CaptureDiagnostics,
1688 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001689 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001690 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001691 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001692 assert(CI && "A CompilerInvocation is required");
1693
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001694 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001695 ASTUnit *AST = Unit;
1696 if (!AST) {
1697 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001698 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001699 AST = OwnAST.get();
1700 }
1701
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001702 if (!ResourceFilesPath.empty()) {
1703 // Override the resources path.
1704 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1705 }
1706 AST->OnlyLocalDecls = OnlyLocalDecls;
1707 AST->CaptureDiagnostics = CaptureDiagnostics;
1708 if (PrecompilePreamble)
1709 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001710 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001711 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001712 AST->IncludeBriefCommentsInCodeCompletion
1713 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001714
1715 // Recover resources if we crash before exiting this method.
1716 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001717 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001718 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1719 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001720 DiagCleanup(Diags.getPtr());
1721
1722 // We'll manage file buffers ourselves.
1723 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1724 CI->getFrontendOpts().DisableFree = false;
1725 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1726
1727 // Save the target features.
1728 AST->TargetFeatures = CI->getTargetOpts().Features;
1729
1730 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001731 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001732
1733 // Recover resources if we crash before exiting this method.
1734 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1735 CICleanup(Clang.get());
1736
1737 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001738 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001739
1740 // Set up diagnostics, capturing any diagnostics that would
1741 // otherwise be dropped.
1742 Clang->setDiagnostics(&AST->getDiagnostics());
1743
1744 // Create the target instance.
1745 Clang->getTargetOpts().Features = AST->TargetFeatures;
1746 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1747 Clang->getTargetOpts()));
1748 if (!Clang->hasTarget())
1749 return 0;
1750
1751 // Inform the target of the language options.
1752 //
1753 // FIXME: We shouldn't need to do this, the target should be immutable once
1754 // created. This complexity should be lifted elsewhere.
1755 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1756
1757 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1758 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001759 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001760 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001761 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001762 "IR inputs not supported here!");
1763
1764 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765 AST->TheSema.reset();
1766 AST->Ctx = 0;
1767 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001768 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001769
1770 // Create a file manager object to provide access to and cache the filesystem.
1771 Clang->setFileManager(&AST->getFileManager());
1772
1773 // Create the source manager.
1774 Clang->setSourceManager(&AST->getSourceManager());
1775
1776 ASTFrontendAction *Act = Action;
1777
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001778 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001779 if (!Act) {
1780 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1781 Act = TrackerAct.get();
1782 }
1783
1784 // Recover resources if we crash before exiting this method.
1785 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1786 ActCleanup(TrackerAct.get());
1787
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001788 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1789 AST->transferASTDataFromCompilerInstance(*Clang);
1790 if (OwnAST && ErrAST)
1791 ErrAST->swap(OwnAST);
1792
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001793 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001794 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001795
1796 if (Persistent && !TrackerAct) {
1797 Clang->getPreprocessor().addPPCallbacks(
1798 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1799 std::vector<ASTConsumer*> Consumers;
1800 if (Clang->hasASTConsumer())
1801 Consumers.push_back(Clang->takeASTConsumer());
1802 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1803 AST->getCurrentTopLevelHashValue()));
1804 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1805 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001806 if (!Act->Execute()) {
1807 AST->transferASTDataFromCompilerInstance(*Clang);
1808 if (OwnAST && ErrAST)
1809 ErrAST->swap(OwnAST);
1810
1811 return 0;
1812 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001813
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001814 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001815 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001816
1817 Act->EndSourceFile();
1818
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001819 if (OwnAST)
1820 return OwnAST.take();
1821 else
1822 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001823}
1824
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001825bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1826 if (!Invocation)
1827 return true;
1828
1829 // We'll manage file buffers ourselves.
1830 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1831 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001832 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001833
Douglas Gregor1aa27302011-01-27 18:02:58 +00001834 // Save the target features.
1835 TargetFeatures = Invocation->getTargetOpts().Features;
1836
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001837 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001838 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001839 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001840 OverrideMainBuffer
1841 = getMainBufferWithPrecompiledPreamble(*Invocation);
1842 }
1843
Douglas Gregor213f18b2010-10-28 15:44:59 +00001844 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001845 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001846
Ted Kremenek25a11e12011-03-22 01:15:24 +00001847 // Recover resources if we crash before exiting this method.
1848 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1849 MemBufferCleanup(OverrideMainBuffer);
1850
Douglas Gregor213f18b2010-10-28 15:44:59 +00001851 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001852}
1853
Douglas Gregorabc563f2010-07-19 21:46:24 +00001854ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001855 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001856 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001857 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001858 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001859 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001860 bool CacheCodeCompletionResults,
1861 bool IncludeBriefCommentsInCodeCompletion) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001862 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001863 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001864 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001865 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001866 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001867 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001868 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001869 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001870 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001871 AST->IncludeBriefCommentsInCodeCompletion
1872 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001873 AST->Invocation = CI;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001874
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001875 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001876 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1877 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001878 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1879 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001880 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001881
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001882 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001883}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001884
1885ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1886 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001887 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001888 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001889 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001890 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001891 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001892 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001893 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001894 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001895 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001896 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001897 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001898 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001899 bool SkipFunctionBodies,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001900 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001901 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001902 // No diagnostics engine was provided, so create our own diagnostics object
1903 // with the default options.
1904 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001905 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1906 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001907 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001908
Chris Lattner5f9e2722011-07-23 10:55:15 +00001909 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001910
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001911 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001912
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001913 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001914
Douglas Gregore47be3e2010-11-11 00:39:14 +00001915 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001916 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001917
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001918 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001919 llvm::makeArrayRef(ArgBegin, ArgEnd),
1920 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001921 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001922 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001923 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001924
Douglas Gregor4db64a42010-01-23 00:14:00 +00001925 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001926 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1927 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1928 if (const llvm::MemoryBuffer *
1929 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1930 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1931 } else {
1932 const char *fname = fileOrBuf.get<const char *>();
1933 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1934 }
1935 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001936 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1937 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1938 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001939
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001940 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001941 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001942
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001943 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1944
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001945 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001946 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001947 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001948 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001949 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001950 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001951 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001952 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001953 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001954 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001955 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001956 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001957 AST->IncludeBriefCommentsInCodeCompletion
1958 = IncludeBriefCommentsInCodeCompletion;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001959 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001960 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001961 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001962 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001963
1964 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001965 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1966 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001967
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001968 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1969 // Some error occurred, if caller wants to examine diagnostics, pass it the
1970 // ASTUnit.
1971 if (ErrAST) {
1972 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1973 ErrAST->swap(AST);
1974 }
1975 return 0;
1976 }
1977
1978 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001979}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001980
1981bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001982 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001983 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001984
1985 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001986
Douglas Gregor213f18b2010-10-28 15:44:59 +00001987 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001988 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001989
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001990 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001991 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001992 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001993 for (PreprocessorOptions::remapped_file_buffer_iterator
1994 R = PPOpts.remapped_file_buffer_begin(),
1995 REnd = PPOpts.remapped_file_buffer_end();
1996 R != REnd;
1997 ++R) {
1998 delete R->second;
1999 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002000 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002001 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2002 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2003 if (const llvm::MemoryBuffer *
2004 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2005 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2006 memBuf);
2007 } else {
2008 const char *fname = fileOrBuf.get<const char *>();
2009 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2010 fname);
2011 }
2012 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002013
Douglas Gregoreababfb2010-08-04 05:53:38 +00002014 // If we have a preamble file lying around, or if we might try to
2015 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002016 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002017 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002018 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002019
Douglas Gregorabc563f2010-07-19 21:46:24 +00002020 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002021 getDiagnostics().Reset();
2022 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002023 if (OverrideMainBuffer)
2024 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002025
Douglas Gregor175c4a92010-07-23 23:58:40 +00002026 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002027 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002028
2029 // If we're caching global code-completion results, and the top-level
2030 // declarations have changed, clear out the code-completion cache.
2031 if (!Result && ShouldCacheCodeCompletionResults &&
2032 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2033 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002034
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002035 // We now need to clear out the completion info related to this translation
2036 // unit; it'll be recreated if necessary.
2037 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002038
Douglas Gregor175c4a92010-07-23 23:58:40 +00002039 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002040}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002041
Douglas Gregor87c08a52010-08-13 22:48:40 +00002042//----------------------------------------------------------------------------//
2043// Code completion
2044//----------------------------------------------------------------------------//
2045
2046namespace {
2047 /// \brief Code completion consumer that combines the cached code-completion
2048 /// results from an ASTUnit with the code-completion results provided to it,
2049 /// then passes the result on to
2050 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00002051 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002052 ASTUnit &AST;
2053 CodeCompleteConsumer &Next;
2054
2055 public:
2056 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002057 const CodeCompleteOptions &CodeCompleteOpts)
2058 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2059 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002060 {
2061 // Compute the set of contexts in which we will look when we don't have
2062 // any information about the specific context.
2063 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002064 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2065 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2066 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2067 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2068 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2069 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2070 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2071 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2072 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2073 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2074 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2075 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2076 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002077
David Blaikie4e4d0842012-03-11 07:00:24 +00002078 if (AST.getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002079 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2080 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2081 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002082 }
2083
2084 virtual void ProcessCodeCompleteResults(Sema &S,
2085 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002086 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002087 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002088
2089 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2090 OverloadCandidate *Candidates,
2091 unsigned NumCandidates) {
2092 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2093 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002094
Douglas Gregordae68752011-02-01 22:57:45 +00002095 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002096 return Next.getAllocator();
2097 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002098
2099 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2100 return Next.getCodeCompletionTUInfo();
2101 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002102 };
2103}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002104
Douglas Gregor5f808c22010-08-16 21:18:39 +00002105/// \brief Helper function that computes which global names are hidden by the
2106/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002107static void CalculateHiddenNames(const CodeCompletionContext &Context,
2108 CodeCompletionResult *Results,
2109 unsigned NumResults,
2110 ASTContext &Ctx,
2111 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002112 bool OnlyTagNames = false;
2113 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002114 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002115 case CodeCompletionContext::CCC_TopLevel:
2116 case CodeCompletionContext::CCC_ObjCInterface:
2117 case CodeCompletionContext::CCC_ObjCImplementation:
2118 case CodeCompletionContext::CCC_ObjCIvarList:
2119 case CodeCompletionContext::CCC_ClassStructUnion:
2120 case CodeCompletionContext::CCC_Statement:
2121 case CodeCompletionContext::CCC_Expression:
2122 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002123 case CodeCompletionContext::CCC_DotMemberAccess:
2124 case CodeCompletionContext::CCC_ArrowMemberAccess:
2125 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002126 case CodeCompletionContext::CCC_Namespace:
2127 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002128 case CodeCompletionContext::CCC_Name:
2129 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002130 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002131 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002132 break;
2133
2134 case CodeCompletionContext::CCC_EnumTag:
2135 case CodeCompletionContext::CCC_UnionTag:
2136 case CodeCompletionContext::CCC_ClassOrStructTag:
2137 OnlyTagNames = true;
2138 break;
2139
2140 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002141 case CodeCompletionContext::CCC_MacroName:
2142 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002143 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002144 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002145 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002146 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002147 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002148 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002149 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002150 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2151 case CodeCompletionContext::CCC_ObjCClassMessage:
2152 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002153 // We're looking for nothing, or we're looking for names that cannot
2154 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002155 return;
2156 }
2157
John McCall0a2c5e22010-08-25 06:19:51 +00002158 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002159 for (unsigned I = 0; I != NumResults; ++I) {
2160 if (Results[I].Kind != Result::RK_Declaration)
2161 continue;
2162
2163 unsigned IDNS
2164 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2165
2166 bool Hiding = false;
2167 if (OnlyTagNames)
2168 Hiding = (IDNS & Decl::IDNS_Tag);
2169 else {
2170 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002171 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2172 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002173 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002174 HiddenIDNS |= Decl::IDNS_Tag;
2175 Hiding = (IDNS & HiddenIDNS);
2176 }
2177
2178 if (!Hiding)
2179 continue;
2180
2181 DeclarationName Name = Results[I].Declaration->getDeclName();
2182 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2183 HiddenNames.insert(Identifier->getName());
2184 else
2185 HiddenNames.insert(Name.getAsString());
2186 }
2187}
2188
2189
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002190void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2191 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002192 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002193 unsigned NumResults) {
2194 // Merge the results we were given with the results we cached.
2195 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002196 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002197 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002198 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002199 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002200 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002201 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002202 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002203 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002204 C = AST.cached_completion_begin(),
2205 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002206 C != CEnd; ++C) {
2207 // If the context we are in matches any of the contexts we are
2208 // interested in, we'll add this result.
2209 if ((C->ShowInContexts & InContexts) == 0)
2210 continue;
2211
2212 // If we haven't added any results previously, do so now.
2213 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002214 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2215 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002216 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2217 AddedResult = true;
2218 }
2219
Douglas Gregor5f808c22010-08-16 21:18:39 +00002220 // Determine whether this global completion result is hidden by a local
2221 // completion result. If so, skip it.
2222 if (C->Kind != CXCursor_MacroDefinition &&
2223 HiddenNames.count(C->Completion->getTypedText()))
2224 continue;
2225
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002226 // Adjust priority based on similar type classes.
2227 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002228 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002229 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002230 if (!Context.getPreferredType().isNull()) {
2231 if (C->Kind == CXCursor_MacroDefinition) {
2232 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002233 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002234 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002235 } else if (C->Type) {
2236 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002237 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002238 Context.getPreferredType().getUnqualifiedType());
2239 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2240 if (ExpectedSTC == C->TypeClass) {
2241 // We know this type is similar; check for an exact match.
2242 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002243 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002244 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002245 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002246 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2247 Priority /= CCF_ExactTypeMatch;
2248 else
2249 Priority /= CCF_SimilarTypeMatch;
2250 }
2251 }
2252 }
2253
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002254 // Adjust the completion string, if required.
2255 if (C->Kind == CXCursor_MacroDefinition &&
2256 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2257 // Create a new code-completion string that just contains the
2258 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002259 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2260 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002261 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002262 CursorKind = CXCursor_NotImplemented;
2263 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002264 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002265 }
2266
Douglas Gregor4125c372010-08-25 18:03:13 +00002267 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002268 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002269 }
2270
2271 // If we did not add any cached completion results, just forward the
2272 // results we were given to the next consumer.
2273 if (!AddedResult) {
2274 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2275 return;
2276 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002277
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002278 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2279 AllResults.size());
2280}
2281
2282
2283
Chris Lattner5f9e2722011-07-23 10:55:15 +00002284void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002285 RemappedFile *RemappedFiles,
2286 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002287 bool IncludeMacros,
2288 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002289 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002290 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002291 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002292 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002293 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2294 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002295 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002296 return;
2297
Douglas Gregor213f18b2010-10-28 15:44:59 +00002298 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002299 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002300 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002301
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002302 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002303 CCInvocation(new CompilerInvocation(*Invocation));
2304
2305 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002306 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002307 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002308
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002309 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2310 CachedCompletionResults.empty();
2311 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2312 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2313 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2314
2315 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2316
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002317 FrontendOpts.CodeCompletionAt.FileName = File;
2318 FrontendOpts.CodeCompletionAt.Line = Line;
2319 FrontendOpts.CodeCompletionAt.Column = Column;
2320
2321 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002322 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002323
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002324 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002325
2326 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002327 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2328 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002329
Ted Kremenek4f327862011-03-21 18:40:17 +00002330 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002331 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002332
2333 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002334 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002335 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002336 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002337 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002338 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002339
2340 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002341 Clang->getTargetOpts().Features = TargetFeatures;
2342 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2343 Clang->getTargetOpts()));
2344 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002345 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002346 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002347 }
2348
2349 // Inform the target of the language options.
2350 //
2351 // FIXME: We shouldn't need to do this, the target should be immutable once
2352 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002353 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002354
Ted Kremenek03201fb2011-03-21 18:40:07 +00002355 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002356 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002357 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002358 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002359 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002360 "IR inputs not support here!");
2361
2362
2363 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002364 Clang->setFileManager(&FileMgr);
2365 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002366
2367 // Remap files.
2368 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002369 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002370 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002371 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2372 if (const llvm::MemoryBuffer *
2373 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2374 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2375 OwnedBuffers.push_back(memBuf);
2376 } else {
2377 const char *fname = fileOrBuf.get<const char *>();
2378 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2379 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002380 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002381
Douglas Gregor87c08a52010-08-13 22:48:40 +00002382 // Use the code completion consumer we were given, but adding any cached
2383 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002384 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002385 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002386 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002387
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002388 Clang->getFrontendOpts().SkipFunctionBodies = true;
2389
Douglas Gregordf95a132010-08-09 20:45:32 +00002390 // If we have a precompiled preamble, try to use it. We only allow
2391 // the use of the precompiled preamble if we're if the completion
2392 // point is within the main file, after the end of the precompiled
2393 // preamble.
2394 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002395 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002396 using llvm::sys::FileStatus;
2397 llvm::sys::PathWithStatus CompleteFilePath(File);
2398 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2399 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2400 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002401 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2402 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002403 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002404 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002405 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002406 }
2407
2408 // If the main file has been overridden due to the use of a preamble,
2409 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002410 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002411 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002412 stored_diag_begin(),
2413 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002414 if (OverrideMainBuffer) {
2415 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2416 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2417 PreprocessorOpts.PrecompiledPreambleBytes.second
2418 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002419 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002420 PreprocessorOpts.DisablePCHValidation = true;
2421
Douglas Gregor2283d792010-08-20 00:59:43 +00002422 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002423 } else {
2424 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2425 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002426 }
2427
Douglas Gregordca8ee82011-05-06 16:33:08 +00002428 // Disable the preprocessing record
2429 PreprocessorOpts.DetailedRecord = false;
2430
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002431 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002432 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002433 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002434 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002435 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002436 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2437 getSourceManager(), PreambleDiagnostics,
2438 StoredDiagnostics);
2439 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002440 Act->Execute();
2441 Act->EndSourceFile();
2442 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002443
2444 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002445}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002446
Chris Lattner5f9e2722011-07-23 10:55:15 +00002447CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002448 // Write to a temporary file and later rename it to the actual file, to avoid
2449 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002450 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002451 TempPath = File;
2452 TempPath += "-%%%%%%%%";
2453 int fd;
2454 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2455 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002456 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002457
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002458 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2459 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002460 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002461
2462 serialize(Out);
2463 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002464 if (Out.has_error()) {
2465 Out.clear_error();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002466 return CXSaveError_Unknown;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002467 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002468
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002469 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002470 bool exists;
2471 llvm::sys::fs::remove(TempPath.str(), exists);
2472 return CXSaveError_Unknown;
2473 }
2474
2475 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002476}
2477
Chris Lattner5f9e2722011-07-23 10:55:15 +00002478bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002479 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002480
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002481 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002482 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002483 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002484 // FIXME: Handle modules
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002485 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002486
2487 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002488 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002489 OS.write((char *)&Buffer.front(), Buffer.size());
2490
2491 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002492}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002493
2494typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2495
2496static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2497 unsigned Raw = L.getRawEncoding();
2498 const unsigned MacroBit = 1U << 31;
2499 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2500 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2501}
2502
2503void ASTUnit::TranslateStoredDiagnostics(
2504 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002505 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002506 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002507 const SmallVectorImpl<StoredDiagnostic> &Diags,
2508 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002509 // The stored diagnostic has the old source manager in it; update
2510 // the locations to refer into the new source manager. We also need to remap
2511 // all the locations to the new view. This includes the diag location, any
2512 // associated source ranges, and the source ranges of associated fix-its.
2513 // FIXME: There should be a cleaner way to do this.
2514
Chris Lattner5f9e2722011-07-23 10:55:15 +00002515 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002516 Result.reserve(Diags.size());
2517 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002518 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002519 assert(Mod && "Don't have preamble module");
2520 SLocRemap &Remap = Mod->SLocRemap;
2521 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2522 // Rebuild the StoredDiagnostic.
2523 const StoredDiagnostic &SD = Diags[I];
2524 SourceLocation L = SD.getLocation();
2525 TranslateSLoc(L, Remap);
2526 FullSourceLoc Loc(L, SrcMgr);
2527
Chris Lattner5f9e2722011-07-23 10:55:15 +00002528 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002529 Ranges.reserve(SD.range_size());
2530 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2531 E = SD.range_end();
2532 I != E; ++I) {
2533 SourceLocation BL = I->getBegin();
2534 TranslateSLoc(BL, Remap);
2535 SourceLocation EL = I->getEnd();
2536 TranslateSLoc(EL, Remap);
2537 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2538 }
2539
Chris Lattner5f9e2722011-07-23 10:55:15 +00002540 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002541 FixIts.reserve(SD.fixit_size());
2542 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2543 E = SD.fixit_end();
2544 I != E; ++I) {
2545 FixIts.push_back(FixItHint());
2546 FixItHint &FH = FixIts.back();
2547 FH.CodeToInsert = I->CodeToInsert;
2548 SourceLocation BL = I->RemoveRange.getBegin();
2549 TranslateSLoc(BL, Remap);
2550 SourceLocation EL = I->RemoveRange.getEnd();
2551 TranslateSLoc(EL, Remap);
2552 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2553 I->RemoveRange.isTokenRange());
2554 }
2555
2556 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2557 SD.getMessage(), Loc, Ranges, FixIts));
2558 }
2559 Result.swap(Out);
2560}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002561
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002562static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2563 std::pair<unsigned, Decl *> R) {
2564 return L.first < R.first;
2565}
2566
2567void ASTUnit::addFileLevelDecl(Decl *D) {
2568 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002569
2570 // We only care about local declarations.
2571 if (D->isFromASTFile())
2572 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002573
2574 SourceManager &SM = *SourceMgr;
2575 SourceLocation Loc = D->getLocation();
2576 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2577 return;
2578
2579 // We only keep track of the file-level declarations of each file.
2580 if (!D->getLexicalDeclContext()->isFileContext())
2581 return;
2582
2583 SourceLocation FileLoc = SM.getFileLoc(Loc);
2584 assert(SM.isLocalSourceLocation(FileLoc));
2585 FileID FID;
2586 unsigned Offset;
2587 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2588 if (FID.isInvalid())
2589 return;
2590
2591 LocDeclsTy *&Decls = FileDecls[FID];
2592 if (!Decls)
2593 Decls = new LocDeclsTy();
2594
2595 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2596
2597 if (Decls->empty() || Decls->back().first <= Offset) {
2598 Decls->push_back(LocDecl);
2599 return;
2600 }
2601
2602 LocDeclsTy::iterator
2603 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2604
2605 Decls->insert(I, LocDecl);
2606}
2607
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002608void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2609 SmallVectorImpl<Decl *> &Decls) {
2610 if (File.isInvalid())
2611 return;
2612
2613 if (SourceMgr->isLoadedFileID(File)) {
2614 assert(Ctx->getExternalSource() && "No external source!");
2615 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2616 Decls);
2617 }
2618
2619 FileDeclsTy::iterator I = FileDecls.find(File);
2620 if (I == FileDecls.end())
2621 return;
2622
2623 LocDeclsTy &LocDecls = *I->second;
2624 if (LocDecls.empty())
2625 return;
2626
2627 LocDeclsTy::iterator
2628 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2629 std::make_pair(Offset, (Decl*)0), compLocDecl);
2630 if (BeginIt != LocDecls.begin())
2631 --BeginIt;
2632
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002633 // If we are pointing at a top-level decl inside an objc container, we need
2634 // to backtrack until we find it otherwise we will fail to report that the
2635 // region overlaps with an objc container.
2636 while (BeginIt != LocDecls.begin() &&
2637 BeginIt->second->isTopLevelDeclInObjCContainer())
2638 --BeginIt;
2639
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002640 LocDeclsTy::iterator
2641 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2642 std::make_pair(Offset+Length, (Decl*)0),
2643 compLocDecl);
2644 if (EndIt != LocDecls.end())
2645 ++EndIt;
2646
2647 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2648 Decls.push_back(DIt->second);
2649}
2650
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002651SourceLocation ASTUnit::getLocation(const FileEntry *File,
2652 unsigned Line, unsigned Col) const {
2653 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002654 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002655 return SM.getMacroArgExpandedLocation(Loc);
2656}
2657
2658SourceLocation ASTUnit::getLocation(const FileEntry *File,
2659 unsigned Offset) const {
2660 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002661 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002662 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2663}
2664
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002665/// \brief If \arg Loc is a loaded location from the preamble, returns
2666/// the corresponding local location of the main file, otherwise it returns
2667/// \arg Loc.
2668SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2669 FileID PreambleID;
2670 if (SourceMgr)
2671 PreambleID = SourceMgr->getPreambleFileID();
2672
2673 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2674 return Loc;
2675
2676 unsigned Offs;
2677 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2678 SourceLocation FileLoc
2679 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2680 return FileLoc.getLocWithOffset(Offs);
2681 }
2682
2683 return Loc;
2684}
2685
2686/// \brief If \arg Loc is a local location of the main file but inside the
2687/// preamble chunk, returns the corresponding loaded location from the
2688/// preamble, otherwise it returns \arg Loc.
2689SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2690 FileID PreambleID;
2691 if (SourceMgr)
2692 PreambleID = SourceMgr->getPreambleFileID();
2693
2694 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2695 return Loc;
2696
2697 unsigned Offs;
2698 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2699 Offs < Preamble.size()) {
2700 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2701 return FileLoc.getLocWithOffset(Offs);
2702 }
2703
2704 return Loc;
2705}
2706
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002707bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2708 FileID FID;
2709 if (SourceMgr)
2710 FID = SourceMgr->getPreambleFileID();
2711
2712 if (Loc.isInvalid() || FID.isInvalid())
2713 return false;
2714
2715 return SourceMgr->isInFileID(Loc, FID);
2716}
2717
2718bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2719 FileID FID;
2720 if (SourceMgr)
2721 FID = SourceMgr->getMainFileID();
2722
2723 if (Loc.isInvalid() || FID.isInvalid())
2724 return false;
2725
2726 return SourceMgr->isInFileID(Loc, FID);
2727}
2728
2729SourceLocation ASTUnit::getEndOfPreambleFileID() {
2730 FileID FID;
2731 if (SourceMgr)
2732 FID = SourceMgr->getPreambleFileID();
2733
2734 if (FID.isInvalid())
2735 return SourceLocation();
2736
2737 return SourceMgr->getLocForEndOfFile(FID);
2738}
2739
2740SourceLocation ASTUnit::getStartOfMainFileID() {
2741 FileID FID;
2742 if (SourceMgr)
2743 FID = SourceMgr->getMainFileID();
2744
2745 if (FID.isInvalid())
2746 return SourceLocation();
2747
2748 return SourceMgr->getLocForStartOfFile(FID);
2749}
2750
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002751void ASTUnit::PreambleData::countLines() const {
2752 NumLines = 0;
2753 if (empty())
2754 return;
2755
2756 for (std::vector<char>::const_iterator
2757 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2758 if (*I == '\n')
2759 ++NumLines;
2760 }
2761 if (Buffer.back() != '\n')
2762 ++NumLines;
2763}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002764
2765#ifndef NDEBUG
2766ASTUnit::ConcurrencyState::ConcurrencyState() {
2767 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2768}
2769
2770ASTUnit::ConcurrencyState::~ConcurrencyState() {
2771 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2772}
2773
2774void ASTUnit::ConcurrencyState::start() {
2775 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2776 assert(acquired && "Concurrent access to ASTUnit!");
2777}
2778
2779void ASTUnit::ConcurrencyState::finish() {
2780 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2781}
2782
2783#else // NDEBUG
2784
2785ASTUnit::ConcurrencyState::ConcurrencyState() {}
2786ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2787void ASTUnit::ConcurrencyState::start() {}
2788void ASTUnit::ConcurrencyState::finish() {}
2789
2790#endif