blob: c1678d4ef01a37d5a86682f1f34de283a69b659f [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 Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000030#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000031#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000032#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000049#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000050#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000051#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000052#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000053#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000054#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000055using namespace clang;
56
Douglas Gregor213f18b2010-10-28 15:44:59 +000057using llvm::TimeRecord;
58
59namespace {
60 class SimpleTimer {
61 bool WantTiming;
62 TimeRecord Start;
63 std::string Output;
64
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000066 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Chris Lattner5f9e2722011-07-23 10:55:15 +000071 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000072 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000073 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000074 }
75
Douglas Gregor213f18b2010-10-28 15:44:59 +000076 ~SimpleTimer() {
77 if (WantTiming) {
78 TimeRecord Elapsed = TimeRecord::getCurrentTime();
79 Elapsed -= Start;
80 llvm::errs() << Output << ':';
81 Elapsed.print(Elapsed, llvm::errs());
82 llvm::errs() << '\n';
83 }
84 }
85 };
Ted Kremenek1872b312011-10-27 17:55:18 +000086
87 struct OnDiskData {
88 /// \brief The file in which the precompiled preamble is stored.
89 std::string PreambleFile;
90
91 /// \brief Temporary files that should be removed when the ASTUnit is
92 /// destroyed.
93 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
94
95 /// \brief Erase temporary files.
96 void CleanTemporaryFiles();
97
98 /// \brief Erase the preamble file.
99 void CleanPreambleFile();
100
101 /// \brief Erase temporary files and the preamble file.
102 void Cleanup();
103 };
104}
105
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000106static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
107 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
108 return M;
109}
110
Ted Kremenek1872b312011-10-27 17:55:18 +0000111static void cleanupOnDiskMapAtExit(void);
112
113typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
114static OnDiskDataMap &getOnDiskDataMap() {
115 static OnDiskDataMap M;
116 static bool hasRegisteredAtExit = false;
117 if (!hasRegisteredAtExit) {
118 hasRegisteredAtExit = true;
119 atexit(cleanupOnDiskMapAtExit);
120 }
121 return M;
122}
123
124static void cleanupOnDiskMapAtExit(void) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000125 // No mutex required here since we are leaving the program.
Ted Kremenek1872b312011-10-27 17:55:18 +0000126 OnDiskDataMap &M = getOnDiskDataMap();
127 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
128 // We don't worry about freeing the memory associated with OnDiskDataMap.
129 // All we care about is erasing stale files.
130 I->second->Cleanup();
131 }
132}
133
134static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000135 // We require the mutex since we are modifying the structure of the
136 // DenseMap.
137 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000138 OnDiskDataMap &M = getOnDiskDataMap();
139 OnDiskData *&D = M[AU];
140 if (!D)
141 D = new OnDiskData();
142 return *D;
143}
144
145static void erasePreambleFile(const ASTUnit *AU) {
146 getOnDiskData(AU).CleanPreambleFile();
147}
148
149static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000150 // We require the mutex since we are modifying the structure of the
151 // DenseMap.
152 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000153 OnDiskDataMap &M = getOnDiskDataMap();
154 OnDiskDataMap::iterator I = M.find(AU);
155 if (I != M.end()) {
156 I->second->Cleanup();
157 delete I->second;
158 M.erase(AU);
159 }
160}
161
162static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
163 getOnDiskData(AU).PreambleFile = preambleFile;
164}
165
166static const std::string &getPreambleFile(const ASTUnit *AU) {
167 return getOnDiskData(AU).PreambleFile;
168}
169
170void OnDiskData::CleanTemporaryFiles() {
171 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
172 TemporaryFiles[I].eraseFromDisk();
173 TemporaryFiles.clear();
174}
175
176void OnDiskData::CleanPreambleFile() {
177 if (!PreambleFile.empty()) {
178 llvm::sys::Path(PreambleFile).eraseFromDisk();
179 PreambleFile.clear();
180 }
181}
182
183void OnDiskData::Cleanup() {
184 CleanTemporaryFiles();
185 CleanPreambleFile();
186}
187
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000188void ASTUnit::clearFileLevelDecls() {
189 for (FileDeclsTy::iterator
190 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
191 delete I->second;
192 FileDecls.clear();
193}
194
Ted Kremenek1872b312011-10-27 17:55:18 +0000195void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
197}
198
199void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000201}
202
Douglas Gregoreababfb2010-08-04 05:53:38 +0000203/// \brief After failing to build a precompiled preamble (due to
204/// errors in the source that occurs in the preamble), the number of
205/// reparses during which we'll skip even trying to precompile the
206/// preamble.
207const unsigned DefaultPreambleRebuildInterval = 5;
208
Douglas Gregore3c60a72010-11-17 00:13:31 +0000209/// \brief Tracks the number of ASTUnit objects that are currently active.
210///
211/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000212static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000215 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000216 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000217 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000218 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000219 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000220 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000221 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000222 ShouldCacheCodeCompletionResults(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000223 CompletionCacheTopLevelHashValue(0),
224 PreambleTopLevelHashValue(0),
225 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000226 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000227 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000228 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000229 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
230 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000231}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000232
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000234 clearFileLevelDecls();
235
Ted Kremenek1872b312011-10-27 17:55:18 +0000236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
238
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
242 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000243 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
245 for (PreprocessorOptions::remapped_file_buffer_iterator
246 FB = PPOpts.remapped_file_buffer_begin(),
247 FBEnd = PPOpts.remapped_file_buffer_end();
248 FB != FBEnd;
249 ++FB)
250 delete FB->second;
251 }
Douglas Gregor28233422010-07-27 14:52:07 +0000252
253 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000254 delete PreambleBuffer;
255
Douglas Gregor213f18b2010-10-28 15:44:59 +0000256 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000257
258 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000259 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000260 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
261 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000262}
263
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000264void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
265
Douglas Gregor8071e422010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
268static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor8071e422010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
278 unsigned Contexts = 0;
279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
283 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
286 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000287 | (1 << (CodeCompletionContext::CCC_Type - 1))
288 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
292 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
297 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000301 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
305 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
306
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000308 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000310 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
311 if (Record->isUnion())
312 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
313 else
314 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
315
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
322 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
323 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000324 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
326 } else if (isa<ObjCProtocolDecl>(ND)) {
327 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
329 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000331 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregor87c08a52010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor213f18b2010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000353 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
354 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000355
356 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000357 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
358
Douglas Gregor87c08a52010-08-13 22:48:40 +0000359 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
360 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000361 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000362 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000363 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000364 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000365 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000367 Ctx->getLangOptions(),
368 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000369 CachedResult.Priority = Results[I].Priority;
370 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000371 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000372
Douglas Gregorf5586f62010-08-16 18:08:11 +0000373 // Keep track of the type of this completion in an ASTContext-agnostic
374 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000375 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000376 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000377 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000378 CachedResult.Type = 0;
379 } else {
380 CanQualType CanUsageType
381 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
382 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
383
384 // Determine whether we have already seen this type. If so, we save
385 // ourselves the work of formatting the type string by using the
386 // temporary, CanQualType-based hash table to find the associated value.
387 unsigned &TypeValue = CompletionTypes[CanUsageType];
388 if (TypeValue == 0) {
389 TypeValue = CompletionTypes.size();
390 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
391 = TypeValue;
392 }
393
394 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000395 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000396
Douglas Gregor8071e422010-08-15 06:18:01 +0000397 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000398
399 /// Handle nested-name-specifiers in C++.
400 if (TheSema->Context.getLangOptions().CPlusPlus &&
401 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
402 // The contexts in which a nested-name-specifier can appear in C++.
403 unsigned NNSContexts
404 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
405 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
406 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
407 | (1 << (CodeCompletionContext::CCC_Statement - 1))
408 | (1 << (CodeCompletionContext::CCC_Expression - 1))
409 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
410 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
411 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
412 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000413 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000414 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
415 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000416
417 if (isa<NamespaceDecl>(Results[I].Declaration) ||
418 isa<NamespaceAliasDecl>(Results[I].Declaration))
419 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
420
421 if (unsigned RemainingContexts
422 = NNSContexts & ~CachedResult.ShowInContexts) {
423 // If there any contexts where this completion can be a
424 // nested-name-specifier but isn't already an option, create a
425 // nested-name-specifier completion.
426 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000427 CachedResult.Completion
428 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000429 *CachedCompletionAllocator);
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,
Douglas Gregor48601b32011-02-16 19:08:06 +0000450 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000451 CachedResult.ShowInContexts
452 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
453 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
454 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
455 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
456 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
457 | (1 << (CodeCompletionContext::CCC_Statement - 1))
458 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000459 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000460 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000461 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000462 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
463 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000464
Douglas Gregor87c08a52010-08-13 22:48:40 +0000465 CachedResult.Priority = Results[I].Priority;
466 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000467 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000468 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000469 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000470 CachedCompletionResults.push_back(CachedResult);
471 break;
472 }
473 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000474 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000475
476 // Save the current top-level hash value.
477 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478}
479
480void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000482 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000483 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000484}
485
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000486namespace {
487
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000488/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000489/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000490class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000491 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000492 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000493 LangOptions &LangOpt;
494 HeaderSearch &HSI;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000495 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000496 std::string &Predefines;
497 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000501 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000503 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
504 HeaderSearch &HSI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000505 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000506 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000508 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000512 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000514 return false;
515
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000517
518 // Initialize the preprocessor.
519 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000520
521 // Initialize the ASTContext
522 Context.InitBuiltinTypes(*Target);
523
524 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000525 return false;
526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattner5f9e2722011-07-23 10:55:15 +0000528 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000529 // If we've already initialized the target, don't do it again.
530 if (Target)
531 return false;
532
533 // FIXME: This is broken, we should store the TargetOptions in the AST file.
534 TargetOptions TargetOpts;
535 TargetOpts.ABI = "";
536 TargetOpts.CXXABI = "";
537 TargetOpts.CPU = "";
538 TargetOpts.Features.clear();
539 TargetOpts.Triple = Triple;
540 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000541 return false;
542 }
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000544 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000545 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000546 std::string &SuggestedPredefines,
547 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000548 Predefines = Buffers[0].Data;
549 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
550 Predefines += Buffers[I].Data;
551 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000552 return false;
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000555 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000559 virtual void ReadCounter(unsigned Value) {
560 Counter = Value;
561 }
562};
563
David Blaikie26e7a902011-09-26 00:01:39 +0000564class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000565 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000566
567public:
David Blaikie26e7a902011-09-26 00:01:39 +0000568 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000569 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000570 : StoredDiags(StoredDiags) { }
571
David Blaikied6471f72011-09-25 23:23:43 +0000572 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000573 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000574
575 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
576 // Just drop any diagnostics that come from cloned consumers; they'll
577 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000578 // FIXME: We'd like to be able to capture these somehow, even if it's just
579 // file/line/column, because they could occur when parsing module maps or
580 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000581 return new IgnoringDiagConsumer();
582 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000583};
584
585/// \brief RAII object that optionally captures diagnostics, if
586/// there is no diagnostic client to capture them already.
587class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000588 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000589 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000590 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000591
592public:
David Blaikied6471f72011-09-25 23:23:43 +0000593 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000594 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000595 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000596 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000597 if (RequestCapture || Diags.getClient() == 0) {
598 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000599 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000600 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000601 }
602
603 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000604 if (Diags.getClient() == &Client) {
605 Diags.takeClient();
606 Diags.setClient(PreviousClient);
607 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000608 }
609};
610
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000611} // anonymous namespace
612
David Blaikie26e7a902011-09-26 00:01:39 +0000613void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000614 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000615 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000616 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000617
Douglas Gregora88084b2010-02-18 18:08:43 +0000618 StoredDiags.push_back(StoredDiagnostic(Level, Info));
619}
620
Steve Naroff77accc12009-09-03 18:19:54 +0000621const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000622 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000623}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000624
Chris Lattner5f9e2722011-07-23 10:55:15 +0000625llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000626 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000627 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000628 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000629}
630
Douglas Gregore47be3e2010-11-11 00:39:14 +0000631/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000632void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000633 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000634 ASTUnit &AST, bool CaptureDiagnostics) {
635 if (!Diags.getPtr()) {
636 // No diagnostics engine was provided, so create our own diagnostics object
637 // with the default options.
638 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000639 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000640 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000641 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000642 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
643 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000644 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000645 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000646 }
647}
648
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000649ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000650 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000651 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000652 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000653 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000654 unsigned NumRemappedFiles,
655 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000656 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000657
658 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000659 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
660 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000661 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
662 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000663 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000664
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000665 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000666
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000667 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000668 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000669 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000670 AST->FileMgr = new FileManager(FileSystemOpts);
671 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
672 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000673 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000674 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000675 AST->ASTFileLangOpts,
676 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000677
Douglas Gregor4db64a42010-01-23 00:14:00 +0000678 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000679 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
680 if (const llvm::MemoryBuffer *
681 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
682 // Create the file entry for the file that we're mapping from.
683 const FileEntry *FromFile
684 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
685 memBuf->getBufferSize(),
686 0);
687 if (!FromFile) {
688 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
689 << RemappedFiles[I].first;
690 delete memBuf;
691 continue;
692 }
693
694 // Override the contents of the "from" file with the contents of
695 // the "to" file.
696 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
697
698 } else {
699 const char *fname = fileOrBuf.get<const char *>();
700 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
701 if (!ToFile) {
702 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
703 << RemappedFiles[I].first << fname;
704 continue;
705 }
706
707 // Create the file entry for the file that we're mapping from.
708 const FileEntry *FromFile
709 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
710 ToFile->getSize(),
711 0);
712 if (!FromFile) {
713 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
714 << RemappedFiles[I].first;
715 delete memBuf;
716 continue;
717 }
718
719 // Override the contents of the "from" file with the contents of
720 // the "to" file.
721 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000722 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000723 }
724
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000725 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000727 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000728 std::string Predefines;
729 unsigned Counter;
730
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000731 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000732
Douglas Gregor998b3d32011-09-01 23:39:15 +0000733 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
734 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
735 *AST,
736 /*IILookup=*/0,
737 /*OwnsHeaderSearch=*/false,
738 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000739 Preprocessor &PP = *AST->PP;
740
741 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
742 AST->getSourceManager(),
743 /*Target=*/0,
744 PP.getIdentifierTable(),
745 PP.getSelectorTable(),
746 PP.getBuiltinInfo(),
747 /* size_reserve = */0,
748 /*DelayInitialization=*/true);
749 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000750
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000751 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000752
753 // Recover resources if we crash before exiting this method.
754 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
755 ReaderCleanup(Reader.get());
756
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000757 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000758 AST->ASTFileLangOpts, HeaderInfo,
759 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000760
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000761 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000762 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000763 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000765 case ASTReader::Failure:
766 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000767 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000769 }
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000771 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
772
Daniel Dunbard5b61262009-09-21 03:03:47 +0000773 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000774 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000776 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000777 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000778 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000779 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000780 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000781
782 // Unregister the cleanup for ASTReader. It will get cleaned up
783 // by the ASTUnit cleanup.
784 ReaderCleanup.unregister();
785
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000786 Context.setExternalSource(Source);
787
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000788 // Create an AST consumer, even though it isn't used.
789 AST->Consumer.reset(new ASTConsumer);
790
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000791 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000792 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
793 AST->TheSema->Initialize();
794 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000795 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000796
Mike Stump1eb44332009-09-09 15:08:12 +0000797 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000798}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000799
800namespace {
801
Douglas Gregor9b7db622011-02-16 18:16:54 +0000802/// \brief Preprocessor callback class that updates a hash value with the names
803/// of all macros that have been defined by the translation unit.
804class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
805 unsigned &Hash;
806
807public:
808 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
809
810 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
811 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
812 }
813};
814
815/// \brief Add the given declaration to the hash of all top-level entities.
816void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
817 if (!D)
818 return;
819
820 DeclContext *DC = D->getDeclContext();
821 if (!DC)
822 return;
823
824 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
825 return;
826
827 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
828 if (ND->getIdentifier())
829 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
830 else if (DeclarationName Name = ND->getDeclName()) {
831 std::string NameStr = Name.getAsString();
832 Hash = llvm::HashString(NameStr, Hash);
833 }
834 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000835 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000836}
837
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000838class TopLevelDeclTrackerConsumer : public ASTConsumer {
839 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000840 unsigned &Hash;
841
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000842public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000843 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
844 : Unit(_Unit), Hash(Hash) {
845 Hash = 0;
846 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000847
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000848 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000849 if (!D)
850 return;
851
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000852 // FIXME: Currently ObjC method declarations are incorrectly being
853 // reported as top-level declarations, even though their DeclContext
854 // is the containing ObjC @interface/@implementation. This is a
855 // fundamental problem in the parser right now.
856 if (isa<ObjCMethodDecl>(D))
857 return;
858
859 AddTopLevelDeclarationToHash(D, Hash);
860 Unit.addTopLevelDecl(D);
861
862 handleFileLevelDecl(D);
863 }
864
865 void handleFileLevelDecl(Decl *D) {
866 Unit.addFileLevelDecl(D);
867 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
868 for (NamespaceDecl::decl_iterator
869 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
870 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000871 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000872 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000873
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000874 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000875 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
876 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000877 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000878 }
879
Sebastian Redl27372b42010-08-11 18:52:41 +0000880 // We're not interested in "interesting" decls.
881 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000882
883 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
884 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
885 handleTopLevelDecl(*it);
886 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000887};
888
889class TopLevelDeclTrackerAction : public ASTFrontendAction {
890public:
891 ASTUnit &Unit;
892
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000893 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000894 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000895 CI.getPreprocessor().addPPCallbacks(
896 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
897 return new TopLevelDeclTrackerConsumer(Unit,
898 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000899 }
900
901public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000902 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
903
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000904 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000905 virtual TranslationUnitKind getTranslationUnitKind() {
906 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000907 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000908};
909
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000910class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000911 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000912 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000913 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000914
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000915public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000916 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000917 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000918 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000919 Hash(Unit.getCurrentTopLevelHashValue()) {
920 Hash = 0;
921 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000922
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000923 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000924 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
925 Decl *D = *it;
926 // FIXME: Currently ObjC method declarations are incorrectly being
927 // reported as top-level declarations, even though their DeclContext
928 // is the containing ObjC @interface/@implementation. This is a
929 // fundamental problem in the parser right now.
930 if (isa<ObjCMethodDecl>(D))
931 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000932 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000933 TopLevelDecls.push_back(D);
934 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000935 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000936 }
937
938 virtual void HandleTranslationUnit(ASTContext &Ctx) {
939 PCHGenerator::HandleTranslationUnit(Ctx);
940 if (!Unit.getDiagnostics().hasErrorOccurred()) {
941 // Translate the top-level declarations we captured during
942 // parsing into declaration IDs in the precompiled
943 // preamble. This will allow us to deserialize those top-level
944 // declarations when requested.
945 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
946 Unit.addTopLevelDeclFromPreamble(
947 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000948 }
949 }
950};
951
952class PrecompilePreambleAction : public ASTFrontendAction {
953 ASTUnit &Unit;
954
955public:
956 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
957
958 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000959 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000960 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000961 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000962 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000963 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
964 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000965 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000966 return 0;
967
Douglas Gregor832d6202011-07-22 16:35:34 +0000968 if (!CI.getFrontendOpts().RelocatablePCH)
969 Sysroot.clear();
970
Douglas Gregor9b7db622011-02-16 18:16:54 +0000971 CI.getPreprocessor().addPPCallbacks(
972 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000973 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
974 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000975 }
976
977 virtual bool hasCodeCompletionSupport() const { return false; }
978 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000979 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000980};
981
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000982}
983
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000984static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
985 StoredDiagnostics) {
986 // Get rid of stored diagnostics except the ones from the driver which do not
987 // have a source location.
988 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
989 if (StoredDiagnostics[I].getLocation().isValid()) {
990 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
991 --I;
992 }
993 }
994}
995
996static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
997 StoredDiagnostics,
998 SourceManager &SM) {
999 // The stored diagnostic has the old source manager in it; update
1000 // the locations to refer into the new source manager. Since we've
1001 // been careful to make sure that the source manager's state
1002 // before and after are identical, so that we can reuse the source
1003 // location itself.
1004 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1005 if (StoredDiagnostics[I].getLocation().isValid()) {
1006 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1007 StoredDiagnostics[I].setLocation(Loc);
1008 }
1009 }
1010}
1011
Douglas Gregorabc563f2010-07-19 21:46:24 +00001012/// Parse the source file into a translation unit using the given compiler
1013/// invocation, replacing the current translation unit.
1014///
1015/// \returns True if a failure occurred that causes the ASTUnit not to
1016/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001017bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001018 delete SavedMainFileBuffer;
1019 SavedMainFileBuffer = 0;
1020
Ted Kremenek4f327862011-03-21 18:40:17 +00001021 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001022 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001023 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001024 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001025
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001026 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001027 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001028
1029 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001030 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1031 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001032
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001033 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001034 CCInvocation(new CompilerInvocation(*Invocation));
1035
1036 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001037 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001038
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001039 // Set up diagnostics, capturing any diagnostics that would
1040 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001041 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001042
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001043 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001044 Clang->getTargetOpts().Features = TargetFeatures;
1045 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001046 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001047 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001048 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001049 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001050 }
1051
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001052 // Inform the target of the language options.
1053 //
1054 // FIXME: We shouldn't need to do this, the target should be immutable once
1055 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001056 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001057
Ted Kremenek03201fb2011-03-21 18:40:07 +00001058 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001059 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001060 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001061 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001062 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001063 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001064
Douglas Gregorabc563f2010-07-19 21:46:24 +00001065 // Configure the various subsystems.
1066 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001067 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001068 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001069 FileMgr = new FileManager(FileSystemOpts);
1070 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001071 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001072 Ctx = 0;
1073 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001074 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001075
1076 // Clear out old caches and data.
1077 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001078 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001079 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001080
Douglas Gregorf128fed2010-08-20 00:02:33 +00001081 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001082 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001083 TopLevelDeclsInPreamble.clear();
1084 }
1085
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001086 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001087 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001089 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001090 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001091
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001092 // If the main file has been overridden due to the use of a preamble,
1093 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001094 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001095 if (OverrideMainBuffer) {
1096 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1097 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1098 PreprocessorOpts.PrecompiledPreambleBytes.second
1099 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001100 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001101 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001102
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001103 // The stored diagnostic has the old source manager in it; update
1104 // the locations to refer into the new source manager. Since we've
1105 // been careful to make sure that the source manager's state
1106 // before and after are identical, so that we can reuse the source
1107 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001108 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001109
1110 // Keep track of the override buffer;
1111 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001112 }
1113
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001114 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001115 new TopLevelDeclTrackerAction(*this));
1116
1117 // Recover resources if we crash before exiting this method.
1118 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1119 ActCleanup(Act.get());
1120
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001121 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001122 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001123
1124 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001125 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001126 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1127 getSourceManager(), PreambleDiagnostics,
1128 StoredDiagnostics);
1129 }
1130
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001131 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001132
Ted Kremenek4f327862011-03-21 18:40:17 +00001133 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001134 TheSema.reset(Clang->takeSema());
1135 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +00001136 Ctx = &Clang->getASTContext();
1137 PP = &Clang->getPreprocessor();
1138 Clang->setSourceManager(0);
1139 Clang->setFileManager(0);
1140 Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001141 Reader = Clang->getModuleManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001142
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001143 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001144
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001146
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001147error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001148 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001149 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001150 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001151 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001152 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001153
Douglas Gregord54eb442010-10-12 16:25:54 +00001154 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001155 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001156 return true;
1157}
1158
Douglas Gregor44c181a2010-07-23 00:33:23 +00001159/// \brief Simple function to retrieve a path for a preamble precompiled header.
1160static std::string GetPreamblePCHPath() {
1161 // FIXME: This is lame; sys::Path should provide this function (in particular,
1162 // it should know how to find the temporary files dir).
1163 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001164 // FIXME: This is a hack so that we can override the preamble file during
1165 // crash-recovery testing, which is the only case where the preamble files
1166 // are not necessarily cleaned up.
1167 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1168 if (TmpFile)
1169 return TmpFile;
1170
Douglas Gregor44c181a2010-07-23 00:33:23 +00001171 std::string Error;
1172 const char *TmpDir = ::getenv("TMPDIR");
1173 if (!TmpDir)
1174 TmpDir = ::getenv("TEMP");
1175 if (!TmpDir)
1176 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001177#ifdef LLVM_ON_WIN32
1178 if (!TmpDir)
1179 TmpDir = ::getenv("USERPROFILE");
1180#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001181 if (!TmpDir)
1182 TmpDir = "/tmp";
1183 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001184 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001185 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001186 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001187 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001188 return std::string();
1189
Douglas Gregor44c181a2010-07-23 00:33:23 +00001190 return P.str();
1191}
1192
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001193/// \brief Compute the preamble for the main file, providing the source buffer
1194/// that corresponds to the main file along with a pair (bytes, start-of-line)
1195/// that describes the preamble.
1196std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001197ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1198 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001199 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001200 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001201 CreatedBuffer = false;
1202
Douglas Gregor44c181a2010-07-23 00:33:23 +00001203 // Try to determine if the main file has been remapped, either from the
1204 // command line (to another file) or directly through the compiler invocation
1205 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001206 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001207 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001208 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1209 // Check whether there is a file-file remapping of the main file
1210 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001211 M = PreprocessorOpts.remapped_file_begin(),
1212 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001213 M != E;
1214 ++M) {
1215 llvm::sys::PathWithStatus MPath(M->first);
1216 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1217 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1218 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001219 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001221 CreatedBuffer = false;
1222 }
1223
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001224 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001225 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001226 return std::make_pair((llvm::MemoryBuffer*)0,
1227 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001228 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229 }
1230 }
1231 }
1232
1233 // Check whether there is a file-buffer remapping. It supercedes the
1234 // file-file remapping.
1235 for (PreprocessorOptions::remapped_file_buffer_iterator
1236 M = PreprocessorOpts.remapped_file_buffer_begin(),
1237 E = PreprocessorOpts.remapped_file_buffer_end();
1238 M != E;
1239 ++M) {
1240 llvm::sys::PathWithStatus MPath(M->first);
1241 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1242 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1243 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001244 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001245 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001246 CreatedBuffer = false;
1247 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001248
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001250 }
1251 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 }
1254
1255 // If the main source file was not remapped, load it now.
1256 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001257 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001258 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001259 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001260
1261 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001262 }
1263
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001264 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001265 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001266 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001267}
1268
Douglas Gregor754f3492010-07-24 00:38:13 +00001269static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001270 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001271 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001272 llvm::MemoryBuffer *Result
1273 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1274 memcpy(const_cast<char*>(Result->getBufferStart()),
1275 Old->getBufferStart(), Old->getBufferSize());
1276 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001277 ' ', NewSize - Old->getBufferSize() - 1);
1278 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001279
Douglas Gregor754f3492010-07-24 00:38:13 +00001280 return Result;
1281}
1282
Douglas Gregor175c4a92010-07-23 23:58:40 +00001283/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1284/// the source file.
1285///
1286/// This routine will compute the preamble of the main source file. If a
1287/// non-trivial preamble is found, it will precompile that preamble into a
1288/// precompiled header so that the precompiled preamble can be used to reduce
1289/// reparsing time. If a precompiled preamble has already been constructed,
1290/// this routine will determine if it is still valid and, if so, avoid
1291/// rebuilding the precompiled preamble.
1292///
Douglas Gregordf95a132010-08-09 20:45:32 +00001293/// \param AllowRebuild When true (the default), this routine is
1294/// allowed to rebuild the precompiled preamble if it is found to be
1295/// out-of-date.
1296///
1297/// \param MaxLines When non-zero, the maximum number of lines that
1298/// can occur within the preamble.
1299///
Douglas Gregor754f3492010-07-24 00:38:13 +00001300/// \returns If the precompiled preamble can be used, returns a newly-allocated
1301/// buffer that should be used in place of the main file when doing so.
1302/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001303llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001304 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001305 bool AllowRebuild,
1306 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001307
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001308 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001309 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1310 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001311 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001312 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001313
1314 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001315 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001316 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001317
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001318 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001319 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001320 if (CreatedPreambleBuffer)
1321 OwnedPreambleBuffer.reset(NewPreamble.first);
1322
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001323 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001324 // We couldn't find a preamble in the main source. Clear out the current
1325 // preamble, if we have one. It's obviously no good any more.
1326 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001327 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001328
1329 // The next time we actually see a preamble, precompile it.
1330 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001331 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001332 }
1333
1334 if (!Preamble.empty()) {
1335 // We've previously computed a preamble. Check whether we have the same
1336 // preamble now that we did before, and that there's enough space in
1337 // the main-file buffer within the precompiled preamble to fit the
1338 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001339 if (Preamble.size() == NewPreamble.second.first &&
1340 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001341 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001342 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001343 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001344 // The preamble has not changed. We may be able to re-use the precompiled
1345 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001346
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001347 // Check that none of the files used by the preamble have changed.
1348 bool AnyFileChanged = false;
1349
1350 // First, make a record of those files that have been overridden via
1351 // remapping or unsaved_files.
1352 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1353 for (PreprocessorOptions::remapped_file_iterator
1354 R = PreprocessorOpts.remapped_file_begin(),
1355 REnd = PreprocessorOpts.remapped_file_end();
1356 !AnyFileChanged && R != REnd;
1357 ++R) {
1358 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001359 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001360 // If we can't stat the file we're remapping to, assume that something
1361 // horrible happened.
1362 AnyFileChanged = true;
1363 break;
1364 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001365
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001366 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1367 StatBuf.st_mtime);
1368 }
1369 for (PreprocessorOptions::remapped_file_buffer_iterator
1370 R = PreprocessorOpts.remapped_file_buffer_begin(),
1371 REnd = PreprocessorOpts.remapped_file_buffer_end();
1372 !AnyFileChanged && R != REnd;
1373 ++R) {
1374 // FIXME: Should we actually compare the contents of file->buffer
1375 // remappings?
1376 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1377 0);
1378 }
1379
1380 // Check whether anything has changed.
1381 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1382 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1383 !AnyFileChanged && F != FEnd;
1384 ++F) {
1385 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1386 = OverriddenFiles.find(F->first());
1387 if (Overridden != OverriddenFiles.end()) {
1388 // This file was remapped; check whether the newly-mapped file
1389 // matches up with the previous mapping.
1390 if (Overridden->second != F->second)
1391 AnyFileChanged = true;
1392 continue;
1393 }
1394
1395 // The file was not remapped; check whether it has changed on disk.
1396 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001397 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001398 // If we can't stat the file, assume that something horrible happened.
1399 AnyFileChanged = true;
1400 } else if (StatBuf.st_size != F->second.first ||
1401 StatBuf.st_mtime != F->second.second)
1402 AnyFileChanged = true;
1403 }
1404
1405 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001406 // Okay! We can re-use the precompiled preamble.
1407
1408 // Set the state of the diagnostic object to mimic its state
1409 // after parsing the preamble.
1410 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001411 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001412 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001413 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001414
1415 // Create a version of the main file buffer that is padded to
1416 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001417 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001418 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001419 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001420 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001421 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001422
1423 // If we aren't allowed to rebuild the precompiled preamble, just
1424 // return now.
1425 if (!AllowRebuild)
1426 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001427
Douglas Gregor175c4a92010-07-23 23:58:40 +00001428 // We can't reuse the previously-computed preamble. Build a new one.
1429 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001430 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001431 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001432 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001433 } else if (!AllowRebuild) {
1434 // We aren't allowed to rebuild the precompiled preamble; just
1435 // return now.
1436 return 0;
1437 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001438
1439 // If the preamble rebuild counter > 1, it's because we previously
1440 // failed to build a preamble and we're not yet ready to try
1441 // again. Decrement the counter and return a failure.
1442 if (PreambleRebuildCounter > 1) {
1443 --PreambleRebuildCounter;
1444 return 0;
1445 }
1446
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001447 // Create a temporary file for the precompiled preamble. In rare
1448 // circumstances, this can fail.
1449 std::string PreamblePCHPath = GetPreamblePCHPath();
1450 if (PreamblePCHPath.empty()) {
1451 // Try again next time.
1452 PreambleRebuildCounter = 1;
1453 return 0;
1454 }
1455
Douglas Gregor175c4a92010-07-23 23:58:40 +00001456 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001457 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001458 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001459
1460 // Create a new buffer that stores the preamble. The buffer also contains
1461 // extra space for the original contents of the file (which will be present
1462 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001463 // grows.
1464 PreambleReservedSize = NewPreamble.first->getBufferSize();
1465 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001466 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001467 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001468 PreambleReservedSize *= 2;
1469
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001470 // Save the preamble text for later; we'll need to compare against it for
1471 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001472 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001473 Preamble.assign(FileMgr->getFile(MainFilename),
1474 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001475 NewPreamble.first->getBufferStart()
1476 + NewPreamble.second.first);
1477 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1478
Douglas Gregor671947b2010-08-19 01:33:06 +00001479 delete PreambleBuffer;
1480 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001481 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001482 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001483 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001484 NewPreamble.first->getBufferStart(), Preamble.size());
1485 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001486 ' ', PreambleReservedSize - Preamble.size() - 1);
1487 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001488
1489 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001490 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001491 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1492
1493 // Tell the compiler invocation to generate a temporary precompiled header.
1494 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001496 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001497 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1498 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001499
1500 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001501 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001502
1503 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001504 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1505 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001506
Douglas Gregor01b6e312011-07-01 18:22:13 +00001507 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001508 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001509
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001510 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001511 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001512
1513 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001514 Clang->getTargetOpts().Features = TargetFeatures;
1515 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1516 Clang->getTargetOpts()));
1517 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001518 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1519 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001520 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001521 PreprocessorOpts.eraseRemappedFile(
1522 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001523 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001524 }
1525
1526 // Inform the target of the language options.
1527 //
1528 // FIXME: We shouldn't need to do this, the target should be immutable once
1529 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001530 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531
Ted Kremenek03201fb2011-03-21 18:40:07 +00001532 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001533 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001534 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001535 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001536 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537 "IR inputs not support here!");
1538
1539 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001540 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001541 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001542 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001543 TopLevelDecls.clear();
1544 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001545
1546 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001547 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548
1549 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001550 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001551 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001553 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001554 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001555 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001556 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1557 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001558 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001559 PreprocessorOpts.eraseRemappedFile(
1560 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001561 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001562 }
1563
1564 Act->Execute();
1565 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001566
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001567 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001568 // There were errors parsing the preamble, so no precompiled header was
1569 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001570 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001571 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1572 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001573 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001574 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001575 PreprocessorOpts.eraseRemappedFile(
1576 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001577 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001578 }
1579
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001580 // Transfer any diagnostics generated when parsing the preamble into the set
1581 // of preamble diagnostics.
1582 PreambleDiagnostics.clear();
1583 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001584 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001585 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001586
Douglas Gregor175c4a92010-07-23 23:58:40 +00001587 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001588 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001589 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001590
1591 // Keep track of all of the files that the source manager knows about,
1592 // so we can verify whether they have changed or not.
1593 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001594 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001595 const llvm::MemoryBuffer *MainFileBuffer
1596 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1597 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1598 FEnd = SourceMgr.fileinfo_end();
1599 F != FEnd;
1600 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001601 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001602 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1603 continue;
1604
1605 FilesInPreamble[File->getName()]
1606 = std::make_pair(F->second->getSize(), File->getModificationTime());
1607 }
1608
Douglas Gregoreababfb2010-08-04 05:53:38 +00001609 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001610 PreprocessorOpts.eraseRemappedFile(
1611 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001612
1613 // If the hash of top-level entities differs from the hash of the top-level
1614 // entities the last time we rebuilt the preamble, clear out the completion
1615 // cache.
1616 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1617 CompletionCacheTopLevelHashValue = 0;
1618 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1619 }
1620
Douglas Gregor754f3492010-07-24 00:38:13 +00001621 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001622 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001623 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001624}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001625
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001626void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1627 std::vector<Decl *> Resolved;
1628 Resolved.reserve(TopLevelDeclsInPreamble.size());
1629 ExternalASTSource &Source = *getASTContext().getExternalSource();
1630 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1631 // Resolve the declaration ID to an actual declaration, possibly
1632 // deserializing the declaration in the process.
1633 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1634 if (D)
1635 Resolved.push_back(D);
1636 }
1637 TopLevelDeclsInPreamble.clear();
1638 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1639}
1640
Chris Lattner5f9e2722011-07-23 10:55:15 +00001641StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001642 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001643}
1644
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001645ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001646 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001647 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001648 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001649 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001650 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001651 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001652 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001653 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001654 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001655 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001656
1657 return AST.take();
1658}
1659
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001660ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001661 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001662 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001663 ASTUnit *Unit,
1664 bool Persistent,
1665 StringRef ResourceFilesPath,
1666 bool OnlyLocalDecls,
1667 bool CaptureDiagnostics,
1668 bool PrecompilePreamble,
1669 bool CacheCodeCompletionResults) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001670 assert(CI && "A CompilerInvocation is required");
1671
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001672 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001673 ASTUnit *AST = Unit;
1674 if (!AST) {
1675 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001676 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001677 AST = OwnAST.get();
1678 }
1679
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001680 if (!ResourceFilesPath.empty()) {
1681 // Override the resources path.
1682 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1683 }
1684 AST->OnlyLocalDecls = OnlyLocalDecls;
1685 AST->CaptureDiagnostics = CaptureDiagnostics;
1686 if (PrecompilePreamble)
1687 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001688 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001689 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001690
1691 // Recover resources if we crash before exiting this method.
1692 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001693 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001694 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1695 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001696 DiagCleanup(Diags.getPtr());
1697
1698 // We'll manage file buffers ourselves.
1699 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1700 CI->getFrontendOpts().DisableFree = false;
1701 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1702
1703 // Save the target features.
1704 AST->TargetFeatures = CI->getTargetOpts().Features;
1705
1706 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001707 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001708
1709 // Recover resources if we crash before exiting this method.
1710 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1711 CICleanup(Clang.get());
1712
1713 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001714 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001715
1716 // Set up diagnostics, capturing any diagnostics that would
1717 // otherwise be dropped.
1718 Clang->setDiagnostics(&AST->getDiagnostics());
1719
1720 // Create the target instance.
1721 Clang->getTargetOpts().Features = AST->TargetFeatures;
1722 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1723 Clang->getTargetOpts()));
1724 if (!Clang->hasTarget())
1725 return 0;
1726
1727 // Inform the target of the language options.
1728 //
1729 // FIXME: We shouldn't need to do this, the target should be immutable once
1730 // created. This complexity should be lifted elsewhere.
1731 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1732
1733 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1734 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001735 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001736 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001737 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001738 "IR inputs not supported here!");
1739
1740 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001741 AST->TheSema.reset();
1742 AST->Ctx = 0;
1743 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001744 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001745
1746 // Create a file manager object to provide access to and cache the filesystem.
1747 Clang->setFileManager(&AST->getFileManager());
1748
1749 // Create the source manager.
1750 Clang->setSourceManager(&AST->getSourceManager());
1751
1752 ASTFrontendAction *Act = Action;
1753
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001754 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001755 if (!Act) {
1756 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1757 Act = TrackerAct.get();
1758 }
1759
1760 // Recover resources if we crash before exiting this method.
1761 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1762 ActCleanup(TrackerAct.get());
1763
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001764 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765 return 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001766
1767 if (Persistent && !TrackerAct) {
1768 Clang->getPreprocessor().addPPCallbacks(
1769 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1770 std::vector<ASTConsumer*> Consumers;
1771 if (Clang->hasASTConsumer())
1772 Consumers.push_back(Clang->takeASTConsumer());
1773 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1774 AST->getCurrentTopLevelHashValue()));
1775 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1776 }
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001777 Act->Execute();
1778
1779 // Steal the created target, context, and preprocessor.
1780 AST->TheSema.reset(Clang->takeSema());
1781 AST->Consumer.reset(Clang->takeASTConsumer());
1782 AST->Ctx = &Clang->getASTContext();
1783 AST->PP = &Clang->getPreprocessor();
1784 Clang->setSourceManager(0);
1785 Clang->setFileManager(0);
1786 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001787 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001788
1789 Act->EndSourceFile();
1790
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001791 if (OwnAST)
1792 return OwnAST.take();
1793 else
1794 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001795}
1796
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001797bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1798 if (!Invocation)
1799 return true;
1800
1801 // We'll manage file buffers ourselves.
1802 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1803 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001804 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001805
Douglas Gregor1aa27302011-01-27 18:02:58 +00001806 // Save the target features.
1807 TargetFeatures = Invocation->getTargetOpts().Features;
1808
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001809 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001810 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001811 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001812 OverrideMainBuffer
1813 = getMainBufferWithPrecompiledPreamble(*Invocation);
1814 }
1815
Douglas Gregor213f18b2010-10-28 15:44:59 +00001816 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001817 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001818
Ted Kremenek25a11e12011-03-22 01:15:24 +00001819 // Recover resources if we crash before exiting this method.
1820 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1821 MemBufferCleanup(OverrideMainBuffer);
1822
Douglas Gregor213f18b2010-10-28 15:44:59 +00001823 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001824}
1825
Douglas Gregorabc563f2010-07-19 21:46:24 +00001826ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001827 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001828 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001829 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001830 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001831 TranslationUnitKind TUKind,
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00001832 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001833 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001834 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001835 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001836 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001837 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001838 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001839 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001840 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001841 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001842 AST->Invocation = CI;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001843
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001844 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001845 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1846 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001847 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1848 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001849 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001850
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001851 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001852}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001853
1854ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1855 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001856 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001857 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001858 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001859 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001860 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001861 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001862 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001863 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001864 TranslationUnitKind TUKind,
Argyrios Kyrtzidise1d43302012-02-25 02:41:16 +00001865 bool CacheCodeCompletionResults) {
Douglas Gregor28019772010-04-05 23:52:57 +00001866 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001867 // No diagnostics engine was provided, so create our own diagnostics object
1868 // with the default options.
1869 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001870 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1871 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001872 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001873
Chris Lattner5f9e2722011-07-23 10:55:15 +00001874 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001875
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001876 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001877
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001878 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001879
Douglas Gregore47be3e2010-11-11 00:39:14 +00001880 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001881 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001882
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001883 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001884 llvm::makeArrayRef(ArgBegin, ArgEnd),
1885 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001886 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001887 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001888 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001889
Douglas Gregor4db64a42010-01-23 00:14:00 +00001890 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001891 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1892 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1893 if (const llvm::MemoryBuffer *
1894 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1895 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1896 } else {
1897 const char *fname = fileOrBuf.get<const char *>();
1898 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1899 }
1900 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001901 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1902 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001903
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001904 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001905 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001906
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001907 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001908 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001909 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001910 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001911 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001912 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001913 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001914 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001915 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001916 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001917 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001918 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1919 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001920 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001921 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001922 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001923
1924 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001925 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1926 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001927
Chris Lattner39b49bc2010-11-23 08:35:12 +00001928 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001929}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001930
1931bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001932 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001933 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001934
1935 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001936
Douglas Gregor213f18b2010-10-28 15:44:59 +00001937 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001938 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001939
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001940 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001941 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001942 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001943 for (PreprocessorOptions::remapped_file_buffer_iterator
1944 R = PPOpts.remapped_file_buffer_begin(),
1945 REnd = PPOpts.remapped_file_buffer_end();
1946 R != REnd;
1947 ++R) {
1948 delete R->second;
1949 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001950 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001951 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1952 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1953 if (const llvm::MemoryBuffer *
1954 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1955 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1956 memBuf);
1957 } else {
1958 const char *fname = fileOrBuf.get<const char *>();
1959 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1960 fname);
1961 }
1962 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001963
Douglas Gregoreababfb2010-08-04 05:53:38 +00001964 // If we have a preamble file lying around, or if we might try to
1965 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001966 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001967 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001968 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001969
Douglas Gregorabc563f2010-07-19 21:46:24 +00001970 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001971 getDiagnostics().Reset();
1972 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00001973 if (OverrideMainBuffer)
1974 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001975
Douglas Gregor175c4a92010-07-23 23:58:40 +00001976 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001977 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00001978
1979 // If we're caching global code-completion results, and the top-level
1980 // declarations have changed, clear out the code-completion cache.
1981 if (!Result && ShouldCacheCodeCompletionResults &&
1982 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1983 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00001984
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001985 // We now need to clear out the completion allocator for
1986 // clang_getCursorCompletionString; it'll be recreated if necessary.
1987 CursorCompletionAllocator = 0;
1988
Douglas Gregor175c4a92010-07-23 23:58:40 +00001989 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001990}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001991
Douglas Gregor87c08a52010-08-13 22:48:40 +00001992//----------------------------------------------------------------------------//
1993// Code completion
1994//----------------------------------------------------------------------------//
1995
1996namespace {
1997 /// \brief Code completion consumer that combines the cached code-completion
1998 /// results from an ASTUnit with the code-completion results provided to it,
1999 /// then passes the result on to
2000 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00002001 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002002 ASTUnit &AST;
2003 CodeCompleteConsumer &Next;
2004
2005 public:
2006 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00002007 bool IncludeMacros, bool IncludeCodePatterns,
2008 bool IncludeGlobals)
2009 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002010 Next.isOutputBinary()), AST(AST), Next(Next)
2011 {
2012 // Compute the set of contexts in which we will look when we don't have
2013 // any information about the specific context.
2014 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002015 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2016 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2017 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2018 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2019 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2020 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2021 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2022 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2023 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2024 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2025 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2026 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2027 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002028
Douglas Gregor87c08a52010-08-13 22:48:40 +00002029 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002030 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2031 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2032 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002033 }
2034
2035 virtual void ProcessCodeCompleteResults(Sema &S,
2036 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002037 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002038 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002039
2040 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2041 OverloadCandidate *Candidates,
2042 unsigned NumCandidates) {
2043 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2044 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002045
Douglas Gregordae68752011-02-01 22:57:45 +00002046 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002047 return Next.getAllocator();
2048 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002049 };
2050}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002051
Douglas Gregor5f808c22010-08-16 21:18:39 +00002052/// \brief Helper function that computes which global names are hidden by the
2053/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002054static void CalculateHiddenNames(const CodeCompletionContext &Context,
2055 CodeCompletionResult *Results,
2056 unsigned NumResults,
2057 ASTContext &Ctx,
2058 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002059 bool OnlyTagNames = false;
2060 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002061 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002062 case CodeCompletionContext::CCC_TopLevel:
2063 case CodeCompletionContext::CCC_ObjCInterface:
2064 case CodeCompletionContext::CCC_ObjCImplementation:
2065 case CodeCompletionContext::CCC_ObjCIvarList:
2066 case CodeCompletionContext::CCC_ClassStructUnion:
2067 case CodeCompletionContext::CCC_Statement:
2068 case CodeCompletionContext::CCC_Expression:
2069 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002070 case CodeCompletionContext::CCC_DotMemberAccess:
2071 case CodeCompletionContext::CCC_ArrowMemberAccess:
2072 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002073 case CodeCompletionContext::CCC_Namespace:
2074 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002075 case CodeCompletionContext::CCC_Name:
2076 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002077 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002078 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002079 break;
2080
2081 case CodeCompletionContext::CCC_EnumTag:
2082 case CodeCompletionContext::CCC_UnionTag:
2083 case CodeCompletionContext::CCC_ClassOrStructTag:
2084 OnlyTagNames = true;
2085 break;
2086
2087 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002088 case CodeCompletionContext::CCC_MacroName:
2089 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002090 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002091 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002092 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002093 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002094 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002095 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002096 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002097 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2098 case CodeCompletionContext::CCC_ObjCClassMessage:
2099 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002100 // We're looking for nothing, or we're looking for names that cannot
2101 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002102 return;
2103 }
2104
John McCall0a2c5e22010-08-25 06:19:51 +00002105 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002106 for (unsigned I = 0; I != NumResults; ++I) {
2107 if (Results[I].Kind != Result::RK_Declaration)
2108 continue;
2109
2110 unsigned IDNS
2111 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2112
2113 bool Hiding = false;
2114 if (OnlyTagNames)
2115 Hiding = (IDNS & Decl::IDNS_Tag);
2116 else {
2117 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002118 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2119 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002120 if (Ctx.getLangOptions().CPlusPlus)
2121 HiddenIDNS |= Decl::IDNS_Tag;
2122 Hiding = (IDNS & HiddenIDNS);
2123 }
2124
2125 if (!Hiding)
2126 continue;
2127
2128 DeclarationName Name = Results[I].Declaration->getDeclName();
2129 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2130 HiddenNames.insert(Identifier->getName());
2131 else
2132 HiddenNames.insert(Name.getAsString());
2133 }
2134}
2135
2136
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002137void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2138 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002139 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002140 unsigned NumResults) {
2141 // Merge the results we were given with the results we cached.
2142 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002143 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002144 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002145 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002146 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002147 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002148 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002149 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002150 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002151 C = AST.cached_completion_begin(),
2152 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002153 C != CEnd; ++C) {
2154 // If the context we are in matches any of the contexts we are
2155 // interested in, we'll add this result.
2156 if ((C->ShowInContexts & InContexts) == 0)
2157 continue;
2158
2159 // If we haven't added any results previously, do so now.
2160 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002161 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2162 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002163 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2164 AddedResult = true;
2165 }
2166
Douglas Gregor5f808c22010-08-16 21:18:39 +00002167 // Determine whether this global completion result is hidden by a local
2168 // completion result. If so, skip it.
2169 if (C->Kind != CXCursor_MacroDefinition &&
2170 HiddenNames.count(C->Completion->getTypedText()))
2171 continue;
2172
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002173 // Adjust priority based on similar type classes.
2174 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002175 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002176 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002177 if (!Context.getPreferredType().isNull()) {
2178 if (C->Kind == CXCursor_MacroDefinition) {
2179 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002180 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002181 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002182 } else if (C->Type) {
2183 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002184 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002185 Context.getPreferredType().getUnqualifiedType());
2186 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2187 if (ExpectedSTC == C->TypeClass) {
2188 // We know this type is similar; check for an exact match.
2189 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002190 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002191 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002192 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002193 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2194 Priority /= CCF_ExactTypeMatch;
2195 else
2196 Priority /= CCF_SimilarTypeMatch;
2197 }
2198 }
2199 }
2200
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002201 // Adjust the completion string, if required.
2202 if (C->Kind == CXCursor_MacroDefinition &&
2203 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2204 // Create a new code-completion string that just contains the
2205 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002206 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2207 C->Availability);
2208 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002209 CursorKind = CXCursor_NotImplemented;
2210 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002211 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002212 }
2213
Douglas Gregor4125c372010-08-25 18:03:13 +00002214 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002215 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002216 }
2217
2218 // If we did not add any cached completion results, just forward the
2219 // results we were given to the next consumer.
2220 if (!AddedResult) {
2221 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2222 return;
2223 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002224
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002225 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2226 AllResults.size());
2227}
2228
2229
2230
Chris Lattner5f9e2722011-07-23 10:55:15 +00002231void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002232 RemappedFile *RemappedFiles,
2233 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002234 bool IncludeMacros,
2235 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002236 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002237 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002238 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002239 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2240 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002241 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002242 return;
2243
Douglas Gregor213f18b2010-10-28 15:44:59 +00002244 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002245 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002246 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002247
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002248 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002249 CCInvocation(new CompilerInvocation(*Invocation));
2250
2251 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2252 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002253
Douglas Gregor87c08a52010-08-13 22:48:40 +00002254 FrontendOpts.ShowMacrosInCodeCompletion
2255 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002256 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002257 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2258 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002259 FrontendOpts.CodeCompletionAt.FileName = File;
2260 FrontendOpts.CodeCompletionAt.Line = Line;
2261 FrontendOpts.CodeCompletionAt.Column = Column;
2262
2263 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002264 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002265
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002266 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002267
2268 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002269 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2270 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002271
Ted Kremenek4f327862011-03-21 18:40:17 +00002272 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002273 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002274
2275 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002276 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002277 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002278 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002279 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002280 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002281
2282 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002283 Clang->getTargetOpts().Features = TargetFeatures;
2284 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2285 Clang->getTargetOpts()));
2286 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002287 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002288 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002289 }
2290
2291 // Inform the target of the language options.
2292 //
2293 // FIXME: We shouldn't need to do this, the target should be immutable once
2294 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002295 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002296
Ted Kremenek03201fb2011-03-21 18:40:07 +00002297 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002298 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002299 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002300 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002301 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002302 "IR inputs not support here!");
2303
2304
2305 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002306 Clang->setFileManager(&FileMgr);
2307 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002308
2309 // Remap files.
2310 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002311 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002312 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002313 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2314 if (const llvm::MemoryBuffer *
2315 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2316 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2317 OwnedBuffers.push_back(memBuf);
2318 } else {
2319 const char *fname = fileOrBuf.get<const char *>();
2320 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2321 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002322 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002323
Douglas Gregor87c08a52010-08-13 22:48:40 +00002324 // Use the code completion consumer we were given, but adding any cached
2325 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002326 AugmentedCodeCompleteConsumer *AugmentedConsumer
2327 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2328 FrontendOpts.ShowMacrosInCodeCompletion,
2329 FrontendOpts.ShowCodePatternsInCodeCompletion,
2330 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002331 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002332
Douglas Gregordf95a132010-08-09 20:45:32 +00002333 // If we have a precompiled preamble, try to use it. We only allow
2334 // the use of the precompiled preamble if we're if the completion
2335 // point is within the main file, after the end of the precompiled
2336 // preamble.
2337 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002338 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002339 using llvm::sys::FileStatus;
2340 llvm::sys::PathWithStatus CompleteFilePath(File);
2341 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2342 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2343 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002344 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2345 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002346 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002347 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002348 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002349 }
2350
2351 // If the main file has been overridden due to the use of a preamble,
2352 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002353 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002354 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002355 stored_diag_begin(),
2356 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002357 if (OverrideMainBuffer) {
2358 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2359 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2360 PreprocessorOpts.PrecompiledPreambleBytes.second
2361 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002362 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002363 PreprocessorOpts.DisablePCHValidation = true;
2364
Douglas Gregor2283d792010-08-20 00:59:43 +00002365 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002366 } else {
2367 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2368 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002369 }
2370
Douglas Gregordca8ee82011-05-06 16:33:08 +00002371 // Disable the preprocessing record
2372 PreprocessorOpts.DetailedRecord = false;
2373
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002374 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002375 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002376 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002377 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002378 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002379 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2380 getSourceManager(), PreambleDiagnostics,
2381 StoredDiagnostics);
2382 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002383 Act->Execute();
2384 Act->EndSourceFile();
2385 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002386
2387 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002388}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002389
Chris Lattner5f9e2722011-07-23 10:55:15 +00002390CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002391 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002392 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002393
2394 // Write to a temporary file and later rename it to the actual file, to avoid
2395 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002396 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002397 TempPath = File;
2398 TempPath += "-%%%%%%%%";
2399 int fd;
2400 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2401 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002402 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002403
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002404 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2405 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002406 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002407
2408 serialize(Out);
2409 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002410 if (Out.has_error())
2411 return CXSaveError_Unknown;
2412
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002413 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002414 bool exists;
2415 llvm::sys::fs::remove(TempPath.str(), exists);
2416 return CXSaveError_Unknown;
2417 }
2418
2419 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002420}
2421
Chris Lattner5f9e2722011-07-23 10:55:15 +00002422bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002423 if (getDiagnostics().hasErrorOccurred())
2424 return true;
2425
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002426 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002427 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002428 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002429 // FIXME: Handle modules
Douglas Gregora8cc6ce2011-11-30 04:39:39 +00002430 Writer.WriteAST(getSema(), 0, std::string(), 0, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002431
2432 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002433 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002434 OS.write((char *)&Buffer.front(), Buffer.size());
2435
2436 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002437}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002438
2439typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2440
2441static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2442 unsigned Raw = L.getRawEncoding();
2443 const unsigned MacroBit = 1U << 31;
2444 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2445 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2446}
2447
2448void ASTUnit::TranslateStoredDiagnostics(
2449 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002450 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002451 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002452 const SmallVectorImpl<StoredDiagnostic> &Diags,
2453 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002454 // The stored diagnostic has the old source manager in it; update
2455 // the locations to refer into the new source manager. We also need to remap
2456 // all the locations to the new view. This includes the diag location, any
2457 // associated source ranges, and the source ranges of associated fix-its.
2458 // FIXME: There should be a cleaner way to do this.
2459
Chris Lattner5f9e2722011-07-23 10:55:15 +00002460 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002461 Result.reserve(Diags.size());
2462 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002463 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002464 assert(Mod && "Don't have preamble module");
2465 SLocRemap &Remap = Mod->SLocRemap;
2466 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2467 // Rebuild the StoredDiagnostic.
2468 const StoredDiagnostic &SD = Diags[I];
2469 SourceLocation L = SD.getLocation();
2470 TranslateSLoc(L, Remap);
2471 FullSourceLoc Loc(L, SrcMgr);
2472
Chris Lattner5f9e2722011-07-23 10:55:15 +00002473 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002474 Ranges.reserve(SD.range_size());
2475 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2476 E = SD.range_end();
2477 I != E; ++I) {
2478 SourceLocation BL = I->getBegin();
2479 TranslateSLoc(BL, Remap);
2480 SourceLocation EL = I->getEnd();
2481 TranslateSLoc(EL, Remap);
2482 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2483 }
2484
Chris Lattner5f9e2722011-07-23 10:55:15 +00002485 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002486 FixIts.reserve(SD.fixit_size());
2487 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2488 E = SD.fixit_end();
2489 I != E; ++I) {
2490 FixIts.push_back(FixItHint());
2491 FixItHint &FH = FixIts.back();
2492 FH.CodeToInsert = I->CodeToInsert;
2493 SourceLocation BL = I->RemoveRange.getBegin();
2494 TranslateSLoc(BL, Remap);
2495 SourceLocation EL = I->RemoveRange.getEnd();
2496 TranslateSLoc(EL, Remap);
2497 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2498 I->RemoveRange.isTokenRange());
2499 }
2500
2501 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2502 SD.getMessage(), Loc, Ranges, FixIts));
2503 }
2504 Result.swap(Out);
2505}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002506
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002507static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2508 std::pair<unsigned, Decl *> R) {
2509 return L.first < R.first;
2510}
2511
2512void ASTUnit::addFileLevelDecl(Decl *D) {
2513 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002514
2515 // We only care about local declarations.
2516 if (D->isFromASTFile())
2517 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002518
2519 SourceManager &SM = *SourceMgr;
2520 SourceLocation Loc = D->getLocation();
2521 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2522 return;
2523
2524 // We only keep track of the file-level declarations of each file.
2525 if (!D->getLexicalDeclContext()->isFileContext())
2526 return;
2527
2528 SourceLocation FileLoc = SM.getFileLoc(Loc);
2529 assert(SM.isLocalSourceLocation(FileLoc));
2530 FileID FID;
2531 unsigned Offset;
2532 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2533 if (FID.isInvalid())
2534 return;
2535
2536 LocDeclsTy *&Decls = FileDecls[FID];
2537 if (!Decls)
2538 Decls = new LocDeclsTy();
2539
2540 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2541
2542 if (Decls->empty() || Decls->back().first <= Offset) {
2543 Decls->push_back(LocDecl);
2544 return;
2545 }
2546
2547 LocDeclsTy::iterator
2548 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2549
2550 Decls->insert(I, LocDecl);
2551}
2552
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002553void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2554 SmallVectorImpl<Decl *> &Decls) {
2555 if (File.isInvalid())
2556 return;
2557
2558 if (SourceMgr->isLoadedFileID(File)) {
2559 assert(Ctx->getExternalSource() && "No external source!");
2560 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2561 Decls);
2562 }
2563
2564 FileDeclsTy::iterator I = FileDecls.find(File);
2565 if (I == FileDecls.end())
2566 return;
2567
2568 LocDeclsTy &LocDecls = *I->second;
2569 if (LocDecls.empty())
2570 return;
2571
2572 LocDeclsTy::iterator
2573 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2574 std::make_pair(Offset, (Decl*)0), compLocDecl);
2575 if (BeginIt != LocDecls.begin())
2576 --BeginIt;
2577
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002578 // If we are pointing at a top-level decl inside an objc container, we need
2579 // to backtrack until we find it otherwise we will fail to report that the
2580 // region overlaps with an objc container.
2581 while (BeginIt != LocDecls.begin() &&
2582 BeginIt->second->isTopLevelDeclInObjCContainer())
2583 --BeginIt;
2584
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002585 LocDeclsTy::iterator
2586 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2587 std::make_pair(Offset+Length, (Decl*)0),
2588 compLocDecl);
2589 if (EndIt != LocDecls.end())
2590 ++EndIt;
2591
2592 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2593 Decls.push_back(DIt->second);
2594}
2595
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002596SourceLocation ASTUnit::getLocation(const FileEntry *File,
2597 unsigned Line, unsigned Col) const {
2598 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002599 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002600 return SM.getMacroArgExpandedLocation(Loc);
2601}
2602
2603SourceLocation ASTUnit::getLocation(const FileEntry *File,
2604 unsigned Offset) const {
2605 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002606 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002607 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2608}
2609
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002610/// \brief If \arg Loc is a loaded location from the preamble, returns
2611/// the corresponding local location of the main file, otherwise it returns
2612/// \arg Loc.
2613SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2614 FileID PreambleID;
2615 if (SourceMgr)
2616 PreambleID = SourceMgr->getPreambleFileID();
2617
2618 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2619 return Loc;
2620
2621 unsigned Offs;
2622 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2623 SourceLocation FileLoc
2624 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2625 return FileLoc.getLocWithOffset(Offs);
2626 }
2627
2628 return Loc;
2629}
2630
2631/// \brief If \arg Loc is a local location of the main file but inside the
2632/// preamble chunk, returns the corresponding loaded location from the
2633/// preamble, otherwise it returns \arg Loc.
2634SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2635 FileID PreambleID;
2636 if (SourceMgr)
2637 PreambleID = SourceMgr->getPreambleFileID();
2638
2639 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2640 return Loc;
2641
2642 unsigned Offs;
2643 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2644 Offs < Preamble.size()) {
2645 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2646 return FileLoc.getLocWithOffset(Offs);
2647 }
2648
2649 return Loc;
2650}
2651
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002652bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2653 FileID FID;
2654 if (SourceMgr)
2655 FID = SourceMgr->getPreambleFileID();
2656
2657 if (Loc.isInvalid() || FID.isInvalid())
2658 return false;
2659
2660 return SourceMgr->isInFileID(Loc, FID);
2661}
2662
2663bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2664 FileID FID;
2665 if (SourceMgr)
2666 FID = SourceMgr->getMainFileID();
2667
2668 if (Loc.isInvalid() || FID.isInvalid())
2669 return false;
2670
2671 return SourceMgr->isInFileID(Loc, FID);
2672}
2673
2674SourceLocation ASTUnit::getEndOfPreambleFileID() {
2675 FileID FID;
2676 if (SourceMgr)
2677 FID = SourceMgr->getPreambleFileID();
2678
2679 if (FID.isInvalid())
2680 return SourceLocation();
2681
2682 return SourceMgr->getLocForEndOfFile(FID);
2683}
2684
2685SourceLocation ASTUnit::getStartOfMainFileID() {
2686 FileID FID;
2687 if (SourceMgr)
2688 FID = SourceMgr->getMainFileID();
2689
2690 if (FID.isInvalid())
2691 return SourceLocation();
2692
2693 return SourceMgr->getLocForStartOfFile(FID);
2694}
2695
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002696void ASTUnit::PreambleData::countLines() const {
2697 NumLines = 0;
2698 if (empty())
2699 return;
2700
2701 for (std::vector<char>::const_iterator
2702 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2703 if (*I == '\n')
2704 ++NumLines;
2705 }
2706 if (Buffer.back() != '\n')
2707 ++NumLines;
2708}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002709
2710#ifndef NDEBUG
2711ASTUnit::ConcurrencyState::ConcurrencyState() {
2712 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2713}
2714
2715ASTUnit::ConcurrencyState::~ConcurrencyState() {
2716 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2717}
2718
2719void ASTUnit::ConcurrencyState::start() {
2720 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2721 assert(acquired && "Concurrent access to ASTUnit!");
2722}
2723
2724void ASTUnit::ConcurrencyState::finish() {
2725 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2726}
2727
2728#else // NDEBUG
2729
2730ASTUnit::ConcurrencyState::ConcurrencyState() {}
2731ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2732void ASTUnit::ConcurrencyState::start() {}
2733void ASTUnit::ConcurrencyState::finish() {}
2734
2735#endif