blob: 241a2c3296632203f19fad1d0f92de91be12d557 [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),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000223 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000224 CompletionCacheTopLevelHashValue(0),
225 PreambleTopLevelHashValue(0),
226 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000227 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000228 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000229 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000230 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
231 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000232}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000233
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000234ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000235 clearFileLevelDecls();
236
Ted Kremenek1872b312011-10-27 17:55:18 +0000237 // Clean up the temporary files and the preamble file.
238 removeOnDiskEntry(this);
239
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000240 // Free the buffers associated with remapped files. We are required to
241 // perform this operation here because we explicitly request that the
242 // compiler instance *not* free these buffers for each invocation of the
243 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000244 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000245 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
246 for (PreprocessorOptions::remapped_file_buffer_iterator
247 FB = PPOpts.remapped_file_buffer_begin(),
248 FBEnd = PPOpts.remapped_file_buffer_end();
249 FB != FBEnd;
250 ++FB)
251 delete FB->second;
252 }
Douglas Gregor28233422010-07-27 14:52:07 +0000253
254 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000255 delete PreambleBuffer;
256
Douglas Gregor213f18b2010-10-28 15:44:59 +0000257 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000258
259 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000260 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000261 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
262 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000263}
264
Douglas Gregor8071e422010-08-15 06:18:01 +0000265/// \brief Determine the set of code-completion contexts in which this
266/// declaration should be shown.
267static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000268 const LangOptions &LangOpts,
269 bool &IsNestedNameSpecifier) {
270 IsNestedNameSpecifier = false;
271
Douglas Gregor8071e422010-08-15 06:18:01 +0000272 if (isa<UsingShadowDecl>(ND))
273 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
274 if (!ND)
275 return 0;
276
277 unsigned Contexts = 0;
278 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
279 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
280 // Types can appear in these contexts.
281 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
282 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
283 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
284 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
285 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000286 | (1 << (CodeCompletionContext::CCC_Type - 1))
287 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000288
289 // In C++, types can appear in expressions contexts (for functional casts).
290 if (LangOpts.CPlusPlus)
291 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
292
293 // In Objective-C, message sends can send interfaces. In Objective-C++,
294 // all types are available due to functional casts.
295 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
296 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000297
298 // In Objective-C, you can only be a subclass of another Objective-C class
299 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000300 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000301
302 // Deal with tag names.
303 if (isa<EnumDecl>(ND)) {
304 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
305
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000306 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000307 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000308 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
310 if (Record->isUnion())
311 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
312 else
313 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
314
Douglas Gregor8071e422010-08-15 06:18:01 +0000315 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000316 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000317 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000318 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000319 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
320 // Values can appear in these contexts.
321 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
322 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000323 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000324 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
325 } else if (isa<ObjCProtocolDecl>(ND)) {
326 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000327 } else if (isa<ObjCCategoryDecl>(ND)) {
328 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000329 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000330 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000331
332 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000333 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000334 }
335
336 return Contexts;
337}
338
Douglas Gregor87c08a52010-08-13 22:48:40 +0000339void ASTUnit::CacheCodeCompletionResults() {
340 if (!TheSema)
341 return;
342
Douglas Gregor213f18b2010-10-28 15:44:59 +0000343 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000344 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345
346 // Clear out the previous results.
347 ClearCachedCompletionResults();
348
349 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000350 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000351 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000352 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
353 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000354
355 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000356 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
357
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
359 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000360 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000361 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000362 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000363 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000364 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000365 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000366 Ctx->getLangOptions(),
367 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedResult.Priority = Results[I].Priority;
369 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000370 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000371
Douglas Gregorf5586f62010-08-16 18:08:11 +0000372 // Keep track of the type of this completion in an ASTContext-agnostic
373 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000374 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000375 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000376 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000377 CachedResult.Type = 0;
378 } else {
379 CanQualType CanUsageType
380 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
381 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
382
383 // Determine whether we have already seen this type. If so, we save
384 // ourselves the work of formatting the type string by using the
385 // temporary, CanQualType-based hash table to find the associated value.
386 unsigned &TypeValue = CompletionTypes[CanUsageType];
387 if (TypeValue == 0) {
388 TypeValue = CompletionTypes.size();
389 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
390 = TypeValue;
391 }
392
393 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000394 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000395
Douglas Gregor8071e422010-08-15 06:18:01 +0000396 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000397
398 /// Handle nested-name-specifiers in C++.
399 if (TheSema->Context.getLangOptions().CPlusPlus &&
400 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
401 // The contexts in which a nested-name-specifier can appear in C++.
402 unsigned NNSContexts
403 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
404 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
405 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
406 | (1 << (CodeCompletionContext::CCC_Statement - 1))
407 | (1 << (CodeCompletionContext::CCC_Expression - 1))
408 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
409 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
410 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
411 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000412 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000413 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
414 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415
416 if (isa<NamespaceDecl>(Results[I].Declaration) ||
417 isa<NamespaceAliasDecl>(Results[I].Declaration))
418 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
419
420 if (unsigned RemainingContexts
421 = NNSContexts & ~CachedResult.ShowInContexts) {
422 // If there any contexts where this completion can be a
423 // nested-name-specifier but isn't already an option, create a
424 // nested-name-specifier completion.
425 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000426 CachedResult.Completion
427 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000428 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000429 CachedResult.ShowInContexts = RemainingContexts;
430 CachedResult.Priority = CCP_NestedNameSpecifier;
431 CachedResult.TypeClass = STC_Void;
432 CachedResult.Type = 0;
433 CachedCompletionResults.push_back(CachedResult);
434 }
435 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000436 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000437 }
438
Douglas Gregor87c08a52010-08-13 22:48:40 +0000439 case Result::RK_Keyword:
440 case Result::RK_Pattern:
441 // Ignore keywords and patterns; we don't care, since they are so
442 // easily regenerated.
443 break;
444
445 case Result::RK_Macro: {
446 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000447 CachedResult.Completion
448 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000449 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000450 CachedResult.ShowInContexts
451 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
452 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
453 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
454 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
455 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
456 | (1 << (CodeCompletionContext::CCC_Statement - 1))
457 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000458 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000459 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000460 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000461 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
462 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000463
Douglas Gregor87c08a52010-08-13 22:48:40 +0000464 CachedResult.Priority = Results[I].Priority;
465 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000466 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000467 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000468 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000469 CachedCompletionResults.push_back(CachedResult);
470 break;
471 }
472 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000473 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000474
475 // Save the current top-level hash value.
476 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000477}
478
479void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000480 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000481 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000482 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483}
484
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000485namespace {
486
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000487/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000488/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000489class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000490 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000491 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000492 LangOptions &LangOpt;
493 HeaderSearch &HSI;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000494 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000495 std::string &Predefines;
496 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000500 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000502 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
503 HeaderSearch &HSI,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000504 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
505 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000507 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000508 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000509 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000513 return false;
514
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000516
517 // Initialize the preprocessor.
518 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000519
520 // Initialize the ASTContext
521 Context.InitBuiltinTypes(*Target);
522
523 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000524 return false;
525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner5f9e2722011-07-23 10:55:15 +0000527 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000528 // If we've already initialized the target, don't do it again.
529 if (Target)
530 return false;
531
532 // FIXME: This is broken, we should store the TargetOptions in the AST file.
533 TargetOptions TargetOpts;
534 TargetOpts.ABI = "";
535 TargetOpts.CXXABI = "";
536 TargetOpts.CPU = "";
537 TargetOpts.Features.clear();
538 TargetOpts.Triple = Triple;
539 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000540 return false;
541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000543 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000544 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000545 std::string &SuggestedPredefines,
546 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000547 Predefines = Buffers[0].Data;
548 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
549 Predefines += Buffers[I].Data;
550 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000551 return false;
552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000554 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000555 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
556 }
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000558 virtual void ReadCounter(unsigned Value) {
559 Counter = Value;
560 }
561};
562
David Blaikie26e7a902011-09-26 00:01:39 +0000563class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000564 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000565
566public:
David Blaikie26e7a902011-09-26 00:01:39 +0000567 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000569 : StoredDiags(StoredDiags) { }
570
David Blaikied6471f72011-09-25 23:23:43 +0000571 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000572 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000573
574 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
575 // Just drop any diagnostics that come from cloned consumers; they'll
576 // have different source managers anyway.
577 return new IgnoringDiagConsumer();
578 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000579};
580
581/// \brief RAII object that optionally captures diagnostics, if
582/// there is no diagnostic client to capture them already.
583class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000584 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000585 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000586 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000587
588public:
David Blaikied6471f72011-09-25 23:23:43 +0000589 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000590 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000591 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000592 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000593 if (RequestCapture || Diags.getClient() == 0) {
594 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000595 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000596 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000597 }
598
599 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000600 if (Diags.getClient() == &Client) {
601 Diags.takeClient();
602 Diags.setClient(PreviousClient);
603 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000604 }
605};
606
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000607} // anonymous namespace
608
David Blaikie26e7a902011-09-26 00:01:39 +0000609void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000610 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000611 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000612 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000613
Douglas Gregora88084b2010-02-18 18:08:43 +0000614 StoredDiags.push_back(StoredDiagnostic(Level, Info));
615}
616
Steve Naroff77accc12009-09-03 18:19:54 +0000617const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000618 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000619}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000620
Chris Lattner5f9e2722011-07-23 10:55:15 +0000621llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000622 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000623 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000624 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000625}
626
Douglas Gregore47be3e2010-11-11 00:39:14 +0000627/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikied6471f72011-09-25 23:23:43 +0000628void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000629 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000630 ASTUnit &AST, bool CaptureDiagnostics) {
631 if (!Diags.getPtr()) {
632 // No diagnostics engine was provided, so create our own diagnostics object
633 // with the default options.
634 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000635 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000636 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000637 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000638 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
639 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000640 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000641 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000642 }
643}
644
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000645ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikied6471f72011-09-25 23:23:43 +0000646 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000647 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000648 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000649 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000650 unsigned NumRemappedFiles,
651 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000652 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000653
654 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000655 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
656 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000657 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
658 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000659 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000660
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000661 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000662
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000663 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000664 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000665 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000666 AST->FileMgr = new FileManager(FileSystemOpts);
667 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
668 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000669 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
670 AST->getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000671
Douglas Gregor4db64a42010-01-23 00:14:00 +0000672 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000673 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
674 if (const llvm::MemoryBuffer *
675 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
676 // Create the file entry for the file that we're mapping from.
677 const FileEntry *FromFile
678 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
679 memBuf->getBufferSize(),
680 0);
681 if (!FromFile) {
682 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
683 << RemappedFiles[I].first;
684 delete memBuf;
685 continue;
686 }
687
688 // Override the contents of the "from" file with the contents of
689 // the "to" file.
690 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
691
692 } else {
693 const char *fname = fileOrBuf.get<const char *>();
694 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
695 if (!ToFile) {
696 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
697 << RemappedFiles[I].first << fname;
698 continue;
699 }
700
701 // Create the file entry for the file that we're mapping from.
702 const FileEntry *FromFile
703 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
704 ToFile->getSize(),
705 0);
706 if (!FromFile) {
707 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
708 << RemappedFiles[I].first;
709 delete memBuf;
710 continue;
711 }
712
713 // Override the contents of the "from" file with the contents of
714 // the "to" file.
715 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000716 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000717 }
718
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000719 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000721 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000722 std::string Predefines;
723 unsigned Counter;
724
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000725 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000726
Douglas Gregor998b3d32011-09-01 23:39:15 +0000727 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
728 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
729 *AST,
730 /*IILookup=*/0,
731 /*OwnsHeaderSearch=*/false,
732 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000733 Preprocessor &PP = *AST->PP;
734
735 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
736 AST->getSourceManager(),
737 /*Target=*/0,
738 PP.getIdentifierTable(),
739 PP.getSelectorTable(),
740 PP.getBuiltinInfo(),
741 /* size_reserve = */0,
742 /*DelayInitialization=*/true);
743 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000744
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000745 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000746
747 // Recover resources if we crash before exiting this method.
748 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
749 ReaderCleanup(Reader.get());
750
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000751 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000752 AST->ASTFileLangOpts, HeaderInfo,
753 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000754
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000755 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000756 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000757 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000759 case ASTReader::Failure:
760 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000761 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000765 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
766
Daniel Dunbard5b61262009-09-21 03:03:47 +0000767 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000770 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000771 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000772 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000773 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000774 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000775
776 // Unregister the cleanup for ASTReader. It will get cleaned up
777 // by the ASTUnit cleanup.
778 ReaderCleanup.unregister();
779
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000780 Context.setExternalSource(Source);
781
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000782 // Create an AST consumer, even though it isn't used.
783 AST->Consumer.reset(new ASTConsumer);
784
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000785 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000786 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
787 AST->TheSema->Initialize();
788 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000789 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000790
Mike Stump1eb44332009-09-09 15:08:12 +0000791 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000792}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000793
794namespace {
795
Douglas Gregor9b7db622011-02-16 18:16:54 +0000796/// \brief Preprocessor callback class that updates a hash value with the names
797/// of all macros that have been defined by the translation unit.
798class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
799 unsigned &Hash;
800
801public:
802 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
803
804 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
805 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
806 }
807};
808
809/// \brief Add the given declaration to the hash of all top-level entities.
810void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
811 if (!D)
812 return;
813
814 DeclContext *DC = D->getDeclContext();
815 if (!DC)
816 return;
817
818 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
819 return;
820
821 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
822 if (ND->getIdentifier())
823 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
824 else if (DeclarationName Name = ND->getDeclName()) {
825 std::string NameStr = Name.getAsString();
826 Hash = llvm::HashString(NameStr, Hash);
827 }
828 return;
829 }
830
831 if (ObjCForwardProtocolDecl *Forward
832 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
833 for (ObjCForwardProtocolDecl::protocol_iterator
834 P = Forward->protocol_begin(),
835 PEnd = Forward->protocol_end();
836 P != PEnd; ++P)
837 AddTopLevelDeclarationToHash(*P, Hash);
838 return;
839 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000840}
841
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000842class TopLevelDeclTrackerConsumer : public ASTConsumer {
843 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000844 unsigned &Hash;
845
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000846public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000847 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
848 : Unit(_Unit), Hash(Hash) {
849 Hash = 0;
850 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000851
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000852 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000853 if (!D)
854 return;
855
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000856 // FIXME: Currently ObjC method declarations are incorrectly being
857 // reported as top-level declarations, even though their DeclContext
858 // is the containing ObjC @interface/@implementation. This is a
859 // fundamental problem in the parser right now.
860 if (isa<ObjCMethodDecl>(D))
861 return;
862
863 AddTopLevelDeclarationToHash(D, Hash);
864 Unit.addTopLevelDecl(D);
865
866 handleFileLevelDecl(D);
867 }
868
869 void handleFileLevelDecl(Decl *D) {
870 Unit.addFileLevelDecl(D);
871 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
872 for (NamespaceDecl::decl_iterator
873 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
874 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000875 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000876 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000877
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000878 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000879 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
880 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000881 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000882 }
883
Sebastian Redl27372b42010-08-11 18:52:41 +0000884 // We're not interested in "interesting" decls.
885 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000886
887 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
888 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
889 handleTopLevelDecl(*it);
890 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000891};
892
893class TopLevelDeclTrackerAction : public ASTFrontendAction {
894public:
895 ASTUnit &Unit;
896
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000897 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000898 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000899 CI.getPreprocessor().addPPCallbacks(
900 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
901 return new TopLevelDeclTrackerConsumer(Unit,
902 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000903 }
904
905public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000906 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
907
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000908 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000909 virtual TranslationUnitKind getTranslationUnitKind() {
910 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000911 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000912};
913
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000914class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000915 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000916 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000917 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000918
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000919public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000920 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000921 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000922 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000923 Hash(Unit.getCurrentTopLevelHashValue()) {
924 Hash = 0;
925 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000926
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000927 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000928 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
929 Decl *D = *it;
930 // FIXME: Currently ObjC method declarations are incorrectly being
931 // reported as top-level declarations, even though their DeclContext
932 // is the containing ObjC @interface/@implementation. This is a
933 // fundamental problem in the parser right now.
934 if (isa<ObjCMethodDecl>(D))
935 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000936 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000937 TopLevelDecls.push_back(D);
938 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000939 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000940 }
941
942 virtual void HandleTranslationUnit(ASTContext &Ctx) {
943 PCHGenerator::HandleTranslationUnit(Ctx);
944 if (!Unit.getDiagnostics().hasErrorOccurred()) {
945 // Translate the top-level declarations we captured during
946 // parsing into declaration IDs in the precompiled
947 // preamble. This will allow us to deserialize those top-level
948 // declarations when requested.
949 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
950 Unit.addTopLevelDeclFromPreamble(
951 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000952 }
953 }
954};
955
956class PrecompilePreambleAction : public ASTFrontendAction {
957 ASTUnit &Unit;
958
959public:
960 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
961
962 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000963 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000964 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000965 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000966 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000967 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
968 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000969 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000970 return 0;
971
Douglas Gregor832d6202011-07-22 16:35:34 +0000972 if (!CI.getFrontendOpts().RelocatablePCH)
973 Sysroot.clear();
974
Douglas Gregor9b7db622011-02-16 18:16:54 +0000975 CI.getPreprocessor().addPPCallbacks(
976 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000977 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
978 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000979 }
980
981 virtual bool hasCodeCompletionSupport() const { return false; }
982 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000983 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000984};
985
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000986}
987
Douglas Gregorabc563f2010-07-19 21:46:24 +0000988/// Parse the source file into a translation unit using the given compiler
989/// invocation, replacing the current translation unit.
990///
991/// \returns True if a failure occurred that causes the ASTUnit not to
992/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000993bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000994 delete SavedMainFileBuffer;
995 SavedMainFileBuffer = 0;
996
Ted Kremenek4f327862011-03-21 18:40:17 +0000997 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000998 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000999 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001000 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001001
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001002 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001003 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1004
1005 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001006 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1007 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001008
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001009 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1010 CCInvocation(new CompilerInvocation(*Invocation));
1011
1012 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001013 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001014
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001015 // Set up diagnostics, capturing any diagnostics that would
1016 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001017 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001018
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001019 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001020 Clang->getTargetOpts().Features = TargetFeatures;
1021 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001022 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001023 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001024 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001025 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001026 }
1027
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001028 // Inform the target of the language options.
1029 //
1030 // FIXME: We shouldn't need to do this, the target should be immutable once
1031 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001032 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001033
Ted Kremenek03201fb2011-03-21 18:40:07 +00001034 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001035 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001036 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001037 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001038 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001039 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001040
Douglas Gregorabc563f2010-07-19 21:46:24 +00001041 // Configure the various subsystems.
1042 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001043 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001044 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001045 FileMgr = new FileManager(FileSystemOpts);
1046 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001047 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001048 Ctx = 0;
1049 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001050 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001051
1052 // Clear out old caches and data.
1053 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001054 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001055 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001056
Douglas Gregorf128fed2010-08-20 00:02:33 +00001057 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001058 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf128fed2010-08-20 00:02:33 +00001059 TopLevelDeclsInPreamble.clear();
1060 }
1061
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001062 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001063 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001064
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001065 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001066 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001067
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001068 // If the main file has been overridden due to the use of a preamble,
1069 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001070 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +00001071 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1072 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001073 if (OverrideMainBuffer) {
1074 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1075 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1076 PreprocessorOpts.PrecompiledPreambleBytes.second
1077 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001078 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001079 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001080
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001081 // The stored diagnostic has the old source manager in it; update
1082 // the locations to refer into the new source manager. Since we've
1083 // been careful to make sure that the source manager's state
1084 // before and after are identical, so that we can reuse the source
1085 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001086 for (unsigned I = NumStoredDiagnosticsFromDriver,
1087 N = StoredDiagnostics.size();
1088 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001089 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1090 getSourceManager());
1091 StoredDiagnostics[I].setLocation(Loc);
1092 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001093
1094 // Keep track of the override buffer;
1095 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001096 }
1097
Ted Kremenek25a11e12011-03-22 01:15:24 +00001098 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1099 new TopLevelDeclTrackerAction(*this));
1100
1101 // Recover resources if we crash before exiting this method.
1102 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1103 ActCleanup(Act.get());
1104
Ted Kremenek03201fb2011-03-21 18:40:07 +00001105 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1106 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001107 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001108
1109 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001110 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001111 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1112 getSourceManager(), PreambleDiagnostics,
1113 StoredDiagnostics);
1114 }
1115
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001116 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001117
Ted Kremenek4f327862011-03-21 18:40:17 +00001118 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001119 TheSema.reset(Clang->takeSema());
1120 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +00001121 Ctx = &Clang->getASTContext();
1122 PP = &Clang->getPreprocessor();
1123 Clang->setSourceManager(0);
1124 Clang->setFileManager(0);
1125 Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001126 Reader = Clang->getModuleManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001127
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001128 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001129
Douglas Gregorabc563f2010-07-19 21:46:24 +00001130 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001131
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001132error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001133 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001134 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001135 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001136 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001137 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001138
Douglas Gregord54eb442010-10-12 16:25:54 +00001139 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001140 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001141 return true;
1142}
1143
Douglas Gregor44c181a2010-07-23 00:33:23 +00001144/// \brief Simple function to retrieve a path for a preamble precompiled header.
1145static std::string GetPreamblePCHPath() {
1146 // FIXME: This is lame; sys::Path should provide this function (in particular,
1147 // it should know how to find the temporary files dir).
1148 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001149 // FIXME: This is a hack so that we can override the preamble file during
1150 // crash-recovery testing, which is the only case where the preamble files
1151 // are not necessarily cleaned up.
1152 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1153 if (TmpFile)
1154 return TmpFile;
1155
Douglas Gregor44c181a2010-07-23 00:33:23 +00001156 std::string Error;
1157 const char *TmpDir = ::getenv("TMPDIR");
1158 if (!TmpDir)
1159 TmpDir = ::getenv("TEMP");
1160 if (!TmpDir)
1161 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001162#ifdef LLVM_ON_WIN32
1163 if (!TmpDir)
1164 TmpDir = ::getenv("USERPROFILE");
1165#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001166 if (!TmpDir)
1167 TmpDir = "/tmp";
1168 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001169 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001170 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001171 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001172 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001173 return std::string();
1174
Douglas Gregor44c181a2010-07-23 00:33:23 +00001175 return P.str();
1176}
1177
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001178/// \brief Compute the preamble for the main file, providing the source buffer
1179/// that corresponds to the main file along with a pair (bytes, start-of-line)
1180/// that describes the preamble.
1181std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001182ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1183 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001184 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001185 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001186 CreatedBuffer = false;
1187
Douglas Gregor44c181a2010-07-23 00:33:23 +00001188 // Try to determine if the main file has been remapped, either from the
1189 // command line (to another file) or directly through the compiler invocation
1190 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001191 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1193 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1194 // Check whether there is a file-file remapping of the main file
1195 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001196 M = PreprocessorOpts.remapped_file_begin(),
1197 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001198 M != E;
1199 ++M) {
1200 llvm::sys::PathWithStatus MPath(M->first);
1201 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1202 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1203 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001204 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001205 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001206 CreatedBuffer = false;
1207 }
1208
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001209 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001210 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001211 return std::make_pair((llvm::MemoryBuffer*)0,
1212 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001213 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214 }
1215 }
1216 }
1217
1218 // Check whether there is a file-buffer remapping. It supercedes the
1219 // file-file remapping.
1220 for (PreprocessorOptions::remapped_file_buffer_iterator
1221 M = PreprocessorOpts.remapped_file_buffer_begin(),
1222 E = PreprocessorOpts.remapped_file_buffer_end();
1223 M != E;
1224 ++M) {
1225 llvm::sys::PathWithStatus MPath(M->first);
1226 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1227 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1228 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001229 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001230 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001231 CreatedBuffer = false;
1232 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233
Douglas Gregor175c4a92010-07-23 23:58:40 +00001234 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001235 }
1236 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001237 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001238 }
1239
1240 // If the main source file was not remapped, load it now.
1241 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001242 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001243 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001244 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001245
1246 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001247 }
1248
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001249 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001250 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001251 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252}
1253
Douglas Gregor754f3492010-07-24 00:38:13 +00001254static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001255 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001256 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001257 llvm::MemoryBuffer *Result
1258 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1259 memcpy(const_cast<char*>(Result->getBufferStart()),
1260 Old->getBufferStart(), Old->getBufferSize());
1261 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001262 ' ', NewSize - Old->getBufferSize() - 1);
1263 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001264
Douglas Gregor754f3492010-07-24 00:38:13 +00001265 return Result;
1266}
1267
Douglas Gregor175c4a92010-07-23 23:58:40 +00001268/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1269/// the source file.
1270///
1271/// This routine will compute the preamble of the main source file. If a
1272/// non-trivial preamble is found, it will precompile that preamble into a
1273/// precompiled header so that the precompiled preamble can be used to reduce
1274/// reparsing time. If a precompiled preamble has already been constructed,
1275/// this routine will determine if it is still valid and, if so, avoid
1276/// rebuilding the precompiled preamble.
1277///
Douglas Gregordf95a132010-08-09 20:45:32 +00001278/// \param AllowRebuild When true (the default), this routine is
1279/// allowed to rebuild the precompiled preamble if it is found to be
1280/// out-of-date.
1281///
1282/// \param MaxLines When non-zero, the maximum number of lines that
1283/// can occur within the preamble.
1284///
Douglas Gregor754f3492010-07-24 00:38:13 +00001285/// \returns If the precompiled preamble can be used, returns a newly-allocated
1286/// buffer that should be used in place of the main file when doing so.
1287/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001288llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001289 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001290 bool AllowRebuild,
1291 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001292
1293 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1294 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1295 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001296 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001297 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001298
1299 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001300 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001301 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001302
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001303 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001304 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1305 if (CreatedPreambleBuffer)
1306 OwnedPreambleBuffer.reset(NewPreamble.first);
1307
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001308 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001309 // We couldn't find a preamble in the main source. Clear out the current
1310 // preamble, if we have one. It's obviously no good any more.
1311 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001312 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001313
1314 // The next time we actually see a preamble, precompile it.
1315 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001316 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001317 }
1318
1319 if (!Preamble.empty()) {
1320 // We've previously computed a preamble. Check whether we have the same
1321 // preamble now that we did before, and that there's enough space in
1322 // the main-file buffer within the precompiled preamble to fit the
1323 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001324 if (Preamble.size() == NewPreamble.second.first &&
1325 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001326 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001327 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001328 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001329 // The preamble has not changed. We may be able to re-use the precompiled
1330 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001331
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001332 // Check that none of the files used by the preamble have changed.
1333 bool AnyFileChanged = false;
1334
1335 // First, make a record of those files that have been overridden via
1336 // remapping or unsaved_files.
1337 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1338 for (PreprocessorOptions::remapped_file_iterator
1339 R = PreprocessorOpts.remapped_file_begin(),
1340 REnd = PreprocessorOpts.remapped_file_end();
1341 !AnyFileChanged && R != REnd;
1342 ++R) {
1343 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001344 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001345 // If we can't stat the file we're remapping to, assume that something
1346 // horrible happened.
1347 AnyFileChanged = true;
1348 break;
1349 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001350
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001351 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1352 StatBuf.st_mtime);
1353 }
1354 for (PreprocessorOptions::remapped_file_buffer_iterator
1355 R = PreprocessorOpts.remapped_file_buffer_begin(),
1356 REnd = PreprocessorOpts.remapped_file_buffer_end();
1357 !AnyFileChanged && R != REnd;
1358 ++R) {
1359 // FIXME: Should we actually compare the contents of file->buffer
1360 // remappings?
1361 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1362 0);
1363 }
1364
1365 // Check whether anything has changed.
1366 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1367 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1368 !AnyFileChanged && F != FEnd;
1369 ++F) {
1370 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1371 = OverriddenFiles.find(F->first());
1372 if (Overridden != OverriddenFiles.end()) {
1373 // This file was remapped; check whether the newly-mapped file
1374 // matches up with the previous mapping.
1375 if (Overridden->second != F->second)
1376 AnyFileChanged = true;
1377 continue;
1378 }
1379
1380 // The file was not remapped; check whether it has changed on disk.
1381 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001382 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001383 // If we can't stat the file, assume that something horrible happened.
1384 AnyFileChanged = true;
1385 } else if (StatBuf.st_size != F->second.first ||
1386 StatBuf.st_mtime != F->second.second)
1387 AnyFileChanged = true;
1388 }
1389
1390 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001391 // Okay! We can re-use the precompiled preamble.
1392
1393 // Set the state of the diagnostic object to mimic its state
1394 // after parsing the preamble.
1395 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001396 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001397 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001398 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001399
1400 // Create a version of the main file buffer that is padded to
1401 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001402 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001403 PreambleReservedSize,
1404 FrontendOpts.Inputs[0].second);
1405 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001406 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001407
1408 // If we aren't allowed to rebuild the precompiled preamble, just
1409 // return now.
1410 if (!AllowRebuild)
1411 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001412
Douglas Gregor175c4a92010-07-23 23:58:40 +00001413 // We can't reuse the previously-computed preamble. Build a new one.
1414 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001415 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001416 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001417 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001418 } else if (!AllowRebuild) {
1419 // We aren't allowed to rebuild the precompiled preamble; just
1420 // return now.
1421 return 0;
1422 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001423
1424 // If the preamble rebuild counter > 1, it's because we previously
1425 // failed to build a preamble and we're not yet ready to try
1426 // again. Decrement the counter and return a failure.
1427 if (PreambleRebuildCounter > 1) {
1428 --PreambleRebuildCounter;
1429 return 0;
1430 }
1431
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001432 // Create a temporary file for the precompiled preamble. In rare
1433 // circumstances, this can fail.
1434 std::string PreamblePCHPath = GetPreamblePCHPath();
1435 if (PreamblePCHPath.empty()) {
1436 // Try again next time.
1437 PreambleRebuildCounter = 1;
1438 return 0;
1439 }
1440
Douglas Gregor175c4a92010-07-23 23:58:40 +00001441 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001442 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001443 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001444
1445 // Create a new buffer that stores the preamble. The buffer also contains
1446 // extra space for the original contents of the file (which will be present
1447 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001448 // grows.
1449 PreambleReservedSize = NewPreamble.first->getBufferSize();
1450 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001451 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001452 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001453 PreambleReservedSize *= 2;
1454
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001455 // Save the preamble text for later; we'll need to compare against it for
1456 // subsequent reparses.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001457 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1458 Preamble.assign(FileMgr->getFile(MainFilename),
1459 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001460 NewPreamble.first->getBufferStart()
1461 + NewPreamble.second.first);
1462 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1463
Douglas Gregor671947b2010-08-19 01:33:06 +00001464 delete PreambleBuffer;
1465 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001466 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001467 FrontendOpts.Inputs[0].second);
1468 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001469 NewPreamble.first->getBufferStart(), Preamble.size());
1470 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001471 ' ', PreambleReservedSize - Preamble.size() - 1);
1472 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001473
1474 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001475 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001476 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1477
1478 // Tell the compiler invocation to generate a temporary precompiled header.
1479 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001480 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001481 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001482 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1483 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001484
1485 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001486 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1487
1488 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001489 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1490 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001491
Douglas Gregor01b6e312011-07-01 18:22:13 +00001492 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001493 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001494
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001495 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001496 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001497
1498 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001499 Clang->getTargetOpts().Features = TargetFeatures;
1500 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1501 Clang->getTargetOpts()));
1502 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001503 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1504 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001505 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001506 PreprocessorOpts.eraseRemappedFile(
1507 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001508 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001509 }
1510
1511 // Inform the target of the language options.
1512 //
1513 // FIXME: We shouldn't need to do this, the target should be immutable once
1514 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001515 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516
Ted Kremenek03201fb2011-03-21 18:40:07 +00001517 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001518 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001519 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001520 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001521 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 "IR inputs not support here!");
1523
1524 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001525 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001526 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001527 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001528 TopLevelDecls.clear();
1529 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001530
1531 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001532 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001533
1534 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001535 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001536 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001537
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001538 llvm::OwningPtr<PrecompilePreambleAction> Act;
1539 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001540 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1541 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001542 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1543 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001544 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001545 PreprocessorOpts.eraseRemappedFile(
1546 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001547 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548 }
1549
1550 Act->Execute();
1551 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001552
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001553 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001554 // There were errors parsing the preamble, so no precompiled header was
1555 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001556 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001557 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1558 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001559 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001560 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001561 PreprocessorOpts.eraseRemappedFile(
1562 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001563 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001564 }
1565
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001566 // Transfer any diagnostics generated when parsing the preamble into the set
1567 // of preamble diagnostics.
1568 PreambleDiagnostics.clear();
1569 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001570 stored_diag_afterDriver_begin(), stored_diag_end());
1571 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001572
Douglas Gregor175c4a92010-07-23 23:58:40 +00001573 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001574 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001575 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001576
1577 // Keep track of all of the files that the source manager knows about,
1578 // so we can verify whether they have changed or not.
1579 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001580 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001581 const llvm::MemoryBuffer *MainFileBuffer
1582 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1583 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1584 FEnd = SourceMgr.fileinfo_end();
1585 F != FEnd;
1586 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001587 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001588 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1589 continue;
1590
1591 FilesInPreamble[File->getName()]
1592 = std::make_pair(F->second->getSize(), File->getModificationTime());
1593 }
1594
Douglas Gregoreababfb2010-08-04 05:53:38 +00001595 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001596 PreprocessorOpts.eraseRemappedFile(
1597 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001598
1599 // If the hash of top-level entities differs from the hash of the top-level
1600 // entities the last time we rebuilt the preamble, clear out the completion
1601 // cache.
1602 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1603 CompletionCacheTopLevelHashValue = 0;
1604 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1605 }
1606
Douglas Gregor754f3492010-07-24 00:38:13 +00001607 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001608 PreambleReservedSize,
1609 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001610}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001611
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001612void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1613 std::vector<Decl *> Resolved;
1614 Resolved.reserve(TopLevelDeclsInPreamble.size());
1615 ExternalASTSource &Source = *getASTContext().getExternalSource();
1616 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1617 // Resolve the declaration ID to an actual declaration, possibly
1618 // deserializing the declaration in the process.
1619 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1620 if (D)
1621 Resolved.push_back(D);
1622 }
1623 TopLevelDeclsInPreamble.clear();
1624 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1625}
1626
Chris Lattner5f9e2722011-07-23 10:55:15 +00001627StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001628 return Invocation->getFrontendOpts().Inputs[0].second;
1629}
1630
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001631ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001632 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1633 bool CaptureDiagnostics) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001634 llvm::OwningPtr<ASTUnit> AST;
1635 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001636 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001637 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001638 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001639 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001640 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001641 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001642
1643 return AST.take();
1644}
1645
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001646ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001647 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001648 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001649 ASTUnit *Unit,
1650 bool Persistent,
1651 StringRef ResourceFilesPath,
1652 bool OnlyLocalDecls,
1653 bool CaptureDiagnostics,
1654 bool PrecompilePreamble,
1655 bool CacheCodeCompletionResults) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001656 assert(CI && "A CompilerInvocation is required");
1657
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001658 llvm::OwningPtr<ASTUnit> OwnAST;
1659 ASTUnit *AST = Unit;
1660 if (!AST) {
1661 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001662 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001663 AST = OwnAST.get();
1664 }
1665
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001666 if (!ResourceFilesPath.empty()) {
1667 // Override the resources path.
1668 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1669 }
1670 AST->OnlyLocalDecls = OnlyLocalDecls;
1671 AST->CaptureDiagnostics = CaptureDiagnostics;
1672 if (PrecompilePreamble)
1673 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001674 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001675 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001676
1677 // Recover resources if we crash before exiting this method.
1678 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001679 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001680 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1681 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001682 DiagCleanup(Diags.getPtr());
1683
1684 // We'll manage file buffers ourselves.
1685 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1686 CI->getFrontendOpts().DisableFree = false;
1687 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1688
1689 // Save the target features.
1690 AST->TargetFeatures = CI->getTargetOpts().Features;
1691
1692 // Create the compiler instance to use for building the AST.
1693 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1694
1695 // Recover resources if we crash before exiting this method.
1696 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1697 CICleanup(Clang.get());
1698
1699 Clang->setInvocation(CI);
1700 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1701
1702 // Set up diagnostics, capturing any diagnostics that would
1703 // otherwise be dropped.
1704 Clang->setDiagnostics(&AST->getDiagnostics());
1705
1706 // Create the target instance.
1707 Clang->getTargetOpts().Features = AST->TargetFeatures;
1708 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1709 Clang->getTargetOpts()));
1710 if (!Clang->hasTarget())
1711 return 0;
1712
1713 // Inform the target of the language options.
1714 //
1715 // FIXME: We shouldn't need to do this, the target should be immutable once
1716 // created. This complexity should be lifted elsewhere.
1717 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1718
1719 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1720 "Invocation must have exactly one source file!");
1721 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1722 "FIXME: AST inputs not yet supported here!");
1723 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1724 "IR inputs not supported here!");
1725
1726 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001727 AST->TheSema.reset();
1728 AST->Ctx = 0;
1729 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001730 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001731
1732 // Create a file manager object to provide access to and cache the filesystem.
1733 Clang->setFileManager(&AST->getFileManager());
1734
1735 // Create the source manager.
1736 Clang->setSourceManager(&AST->getSourceManager());
1737
1738 ASTFrontendAction *Act = Action;
1739
1740 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1741 if (!Act) {
1742 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1743 Act = TrackerAct.get();
1744 }
1745
1746 // Recover resources if we crash before exiting this method.
1747 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1748 ActCleanup(TrackerAct.get());
1749
1750 if (!Act->BeginSourceFile(*Clang.get(),
1751 Clang->getFrontendOpts().Inputs[0].second,
1752 Clang->getFrontendOpts().Inputs[0].first))
1753 return 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001754
1755 if (Persistent && !TrackerAct) {
1756 Clang->getPreprocessor().addPPCallbacks(
1757 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1758 std::vector<ASTConsumer*> Consumers;
1759 if (Clang->hasASTConsumer())
1760 Consumers.push_back(Clang->takeASTConsumer());
1761 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1762 AST->getCurrentTopLevelHashValue()));
1763 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1764 }
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001765 Act->Execute();
1766
1767 // Steal the created target, context, and preprocessor.
1768 AST->TheSema.reset(Clang->takeSema());
1769 AST->Consumer.reset(Clang->takeASTConsumer());
1770 AST->Ctx = &Clang->getASTContext();
1771 AST->PP = &Clang->getPreprocessor();
1772 Clang->setSourceManager(0);
1773 Clang->setFileManager(0);
1774 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001775 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001776
1777 Act->EndSourceFile();
1778
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001779 if (OwnAST)
1780 return OwnAST.take();
1781 else
1782 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001783}
1784
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001785bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1786 if (!Invocation)
1787 return true;
1788
1789 // We'll manage file buffers ourselves.
1790 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1791 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001792 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001793
Douglas Gregor1aa27302011-01-27 18:02:58 +00001794 // Save the target features.
1795 TargetFeatures = Invocation->getTargetOpts().Features;
1796
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001797 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001798 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001799 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001800 OverrideMainBuffer
1801 = getMainBufferWithPrecompiledPreamble(*Invocation);
1802 }
1803
Douglas Gregor213f18b2010-10-28 15:44:59 +00001804 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001805 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001806
Ted Kremenek25a11e12011-03-22 01:15:24 +00001807 // Recover resources if we crash before exiting this method.
1808 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1809 MemBufferCleanup(OverrideMainBuffer);
1810
Douglas Gregor213f18b2010-10-28 15:44:59 +00001811 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001812}
1813
Douglas Gregorabc563f2010-07-19 21:46:24 +00001814ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001815 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001816 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001817 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001818 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001819 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001820 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001821 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001822 // Create the AST unit.
1823 llvm::OwningPtr<ASTUnit> AST;
1824 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001825 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001826 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001827 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001828 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001829 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001830 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001831 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001832 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001833
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001834 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001835 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1836 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001837 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1838 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001839 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001840
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001841 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001842}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001843
1844ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1845 const char **ArgEnd,
David Blaikied6471f72011-09-25 23:23:43 +00001846 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001847 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001848 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001849 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001850 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001851 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001852 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001853 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001854 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001855 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001856 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001857 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001858 // No diagnostics engine was provided, so create our own diagnostics object
1859 // with the default options.
1860 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001861 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1862 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001863 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001864
Chris Lattner5f9e2722011-07-23 10:55:15 +00001865 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001866
Ted Kremenek4f327862011-03-21 18:40:17 +00001867 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001868
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001869 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001870
Douglas Gregore47be3e2010-11-11 00:39:14 +00001871 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001872 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001873
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001874 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001875 llvm::makeArrayRef(ArgBegin, ArgEnd),
1876 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001877 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001878 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001879 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001880
Douglas Gregor4db64a42010-01-23 00:14:00 +00001881 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001882 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1883 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1884 if (const llvm::MemoryBuffer *
1885 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1886 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1887 } else {
1888 const char *fname = fileOrBuf.get<const char *>();
1889 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1890 }
1891 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001892 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1893 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001894
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001895 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001896 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001897
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001898 // Create the AST unit.
1899 llvm::OwningPtr<ASTUnit> AST;
1900 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001901 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001902 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001903 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001904 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001905 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001906 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001907 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001908 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001909 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1910 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001911 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001912 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001913 CI = 0; // Zero out now to ease cleanup during crash recovery.
Chandler Carruthba7537f2011-07-14 09:02:10 +00001914 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001915
1916 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001917 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1918 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001919
Chris Lattner39b49bc2010-11-23 08:35:12 +00001920 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001921}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001922
1923bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001924 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001925 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001926
1927 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001928
Douglas Gregor213f18b2010-10-28 15:44:59 +00001929 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001930 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001931
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001932 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001933 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001934 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001935 for (PreprocessorOptions::remapped_file_buffer_iterator
1936 R = PPOpts.remapped_file_buffer_begin(),
1937 REnd = PPOpts.remapped_file_buffer_end();
1938 R != REnd;
1939 ++R) {
1940 delete R->second;
1941 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001942 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001943 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1944 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1945 if (const llvm::MemoryBuffer *
1946 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1947 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1948 memBuf);
1949 } else {
1950 const char *fname = fileOrBuf.get<const char *>();
1951 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1952 fname);
1953 }
1954 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001955
Douglas Gregoreababfb2010-08-04 05:53:38 +00001956 // If we have a preamble file lying around, or if we might try to
1957 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001958 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001959 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001960 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001961
Douglas Gregorabc563f2010-07-19 21:46:24 +00001962 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001963 getDiagnostics().Reset();
1964 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00001965 if (OverrideMainBuffer)
1966 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001967
Douglas Gregor175c4a92010-07-23 23:58:40 +00001968 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001969 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00001970
1971 // If we're caching global code-completion results, and the top-level
1972 // declarations have changed, clear out the code-completion cache.
1973 if (!Result && ShouldCacheCodeCompletionResults &&
1974 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1975 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00001976
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001977 // We now need to clear out the completion allocator for
1978 // clang_getCursorCompletionString; it'll be recreated if necessary.
1979 CursorCompletionAllocator = 0;
1980
Douglas Gregor175c4a92010-07-23 23:58:40 +00001981 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001982}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001983
Douglas Gregor87c08a52010-08-13 22:48:40 +00001984//----------------------------------------------------------------------------//
1985// Code completion
1986//----------------------------------------------------------------------------//
1987
1988namespace {
1989 /// \brief Code completion consumer that combines the cached code-completion
1990 /// results from an ASTUnit with the code-completion results provided to it,
1991 /// then passes the result on to
1992 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001993 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001994 ASTUnit &AST;
1995 CodeCompleteConsumer &Next;
1996
1997 public:
1998 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001999 bool IncludeMacros, bool IncludeCodePatterns,
2000 bool IncludeGlobals)
2001 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002002 Next.isOutputBinary()), AST(AST), Next(Next)
2003 {
2004 // Compute the set of contexts in which we will look when we don't have
2005 // any information about the specific context.
2006 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002007 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2008 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2009 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2010 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2011 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2012 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2013 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2014 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2015 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2016 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2017 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2018 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2019 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002020
Douglas Gregor87c08a52010-08-13 22:48:40 +00002021 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002022 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2023 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2024 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002025 }
2026
2027 virtual void ProcessCodeCompleteResults(Sema &S,
2028 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002029 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002030 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002031
2032 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2033 OverloadCandidate *Candidates,
2034 unsigned NumCandidates) {
2035 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2036 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002037
Douglas Gregordae68752011-02-01 22:57:45 +00002038 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002039 return Next.getAllocator();
2040 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002041 };
2042}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002043
Douglas Gregor5f808c22010-08-16 21:18:39 +00002044/// \brief Helper function that computes which global names are hidden by the
2045/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002046static void CalculateHiddenNames(const CodeCompletionContext &Context,
2047 CodeCompletionResult *Results,
2048 unsigned NumResults,
2049 ASTContext &Ctx,
2050 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002051 bool OnlyTagNames = false;
2052 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002053 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002054 case CodeCompletionContext::CCC_TopLevel:
2055 case CodeCompletionContext::CCC_ObjCInterface:
2056 case CodeCompletionContext::CCC_ObjCImplementation:
2057 case CodeCompletionContext::CCC_ObjCIvarList:
2058 case CodeCompletionContext::CCC_ClassStructUnion:
2059 case CodeCompletionContext::CCC_Statement:
2060 case CodeCompletionContext::CCC_Expression:
2061 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002062 case CodeCompletionContext::CCC_DotMemberAccess:
2063 case CodeCompletionContext::CCC_ArrowMemberAccess:
2064 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002065 case CodeCompletionContext::CCC_Namespace:
2066 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002067 case CodeCompletionContext::CCC_Name:
2068 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002069 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002070 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002071 break;
2072
2073 case CodeCompletionContext::CCC_EnumTag:
2074 case CodeCompletionContext::CCC_UnionTag:
2075 case CodeCompletionContext::CCC_ClassOrStructTag:
2076 OnlyTagNames = true;
2077 break;
2078
2079 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002080 case CodeCompletionContext::CCC_MacroName:
2081 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002082 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002083 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002084 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002085 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002086 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002087 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002088 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002089 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2090 case CodeCompletionContext::CCC_ObjCClassMessage:
2091 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002092 // We're looking for nothing, or we're looking for names that cannot
2093 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002094 return;
2095 }
2096
John McCall0a2c5e22010-08-25 06:19:51 +00002097 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002098 for (unsigned I = 0; I != NumResults; ++I) {
2099 if (Results[I].Kind != Result::RK_Declaration)
2100 continue;
2101
2102 unsigned IDNS
2103 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2104
2105 bool Hiding = false;
2106 if (OnlyTagNames)
2107 Hiding = (IDNS & Decl::IDNS_Tag);
2108 else {
2109 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002110 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2111 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002112 if (Ctx.getLangOptions().CPlusPlus)
2113 HiddenIDNS |= Decl::IDNS_Tag;
2114 Hiding = (IDNS & HiddenIDNS);
2115 }
2116
2117 if (!Hiding)
2118 continue;
2119
2120 DeclarationName Name = Results[I].Declaration->getDeclName();
2121 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2122 HiddenNames.insert(Identifier->getName());
2123 else
2124 HiddenNames.insert(Name.getAsString());
2125 }
2126}
2127
2128
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002129void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2130 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002131 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002132 unsigned NumResults) {
2133 // Merge the results we were given with the results we cached.
2134 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002135 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002136 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002137 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002138 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002139 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002140 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002141 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002142 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002143 C = AST.cached_completion_begin(),
2144 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002145 C != CEnd; ++C) {
2146 // If the context we are in matches any of the contexts we are
2147 // interested in, we'll add this result.
2148 if ((C->ShowInContexts & InContexts) == 0)
2149 continue;
2150
2151 // If we haven't added any results previously, do so now.
2152 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002153 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2154 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002155 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2156 AddedResult = true;
2157 }
2158
Douglas Gregor5f808c22010-08-16 21:18:39 +00002159 // Determine whether this global completion result is hidden by a local
2160 // completion result. If so, skip it.
2161 if (C->Kind != CXCursor_MacroDefinition &&
2162 HiddenNames.count(C->Completion->getTypedText()))
2163 continue;
2164
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002165 // Adjust priority based on similar type classes.
2166 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002167 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002168 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002169 if (!Context.getPreferredType().isNull()) {
2170 if (C->Kind == CXCursor_MacroDefinition) {
2171 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002172 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002173 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002174 } else if (C->Type) {
2175 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002176 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002177 Context.getPreferredType().getUnqualifiedType());
2178 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2179 if (ExpectedSTC == C->TypeClass) {
2180 // We know this type is similar; check for an exact match.
2181 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002182 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002183 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002184 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002185 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2186 Priority /= CCF_ExactTypeMatch;
2187 else
2188 Priority /= CCF_SimilarTypeMatch;
2189 }
2190 }
2191 }
2192
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002193 // Adjust the completion string, if required.
2194 if (C->Kind == CXCursor_MacroDefinition &&
2195 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2196 // Create a new code-completion string that just contains the
2197 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002198 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2199 C->Availability);
2200 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002201 CursorKind = CXCursor_NotImplemented;
2202 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002203 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002204 }
2205
Douglas Gregor4125c372010-08-25 18:03:13 +00002206 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002207 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002208 }
2209
2210 // If we did not add any cached completion results, just forward the
2211 // results we were given to the next consumer.
2212 if (!AddedResult) {
2213 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2214 return;
2215 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002216
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002217 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2218 AllResults.size());
2219}
2220
2221
2222
Chris Lattner5f9e2722011-07-23 10:55:15 +00002223void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002224 RemappedFile *RemappedFiles,
2225 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002226 bool IncludeMacros,
2227 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002228 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002229 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002230 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002231 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2232 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002233 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002234 return;
2235
Douglas Gregor213f18b2010-10-28 15:44:59 +00002236 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002237 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002238 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002239
Ted Kremenek4f327862011-03-21 18:40:17 +00002240 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2241 CCInvocation(new CompilerInvocation(*Invocation));
2242
2243 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2244 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002245
Douglas Gregor87c08a52010-08-13 22:48:40 +00002246 FrontendOpts.ShowMacrosInCodeCompletion
2247 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002248 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002249 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2250 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002251 FrontendOpts.CodeCompletionAt.FileName = File;
2252 FrontendOpts.CodeCompletionAt.Line = Line;
2253 FrontendOpts.CodeCompletionAt.Column = Column;
2254
2255 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002256 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002257
Ted Kremenek03201fb2011-03-21 18:40:07 +00002258 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2259
2260 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002261 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2262 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002263
Ted Kremenek4f327862011-03-21 18:40:17 +00002264 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002265 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002266
2267 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002268 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002269 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002270 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002271 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002272 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002273
2274 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002275 Clang->getTargetOpts().Features = TargetFeatures;
2276 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2277 Clang->getTargetOpts()));
2278 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002279 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002280 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002281 }
2282
2283 // Inform the target of the language options.
2284 //
2285 // FIXME: We shouldn't need to do this, the target should be immutable once
2286 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002287 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002288
Ted Kremenek03201fb2011-03-21 18:40:07 +00002289 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002290 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002291 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002292 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002293 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002294 "IR inputs not support here!");
2295
2296
2297 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002298 Clang->setFileManager(&FileMgr);
2299 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002300
2301 // Remap files.
2302 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002303 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002304 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002305 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2306 if (const llvm::MemoryBuffer *
2307 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2308 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2309 OwnedBuffers.push_back(memBuf);
2310 } else {
2311 const char *fname = fileOrBuf.get<const char *>();
2312 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2313 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002314 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002315
Douglas Gregor87c08a52010-08-13 22:48:40 +00002316 // Use the code completion consumer we were given, but adding any cached
2317 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002318 AugmentedCodeCompleteConsumer *AugmentedConsumer
2319 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2320 FrontendOpts.ShowMacrosInCodeCompletion,
2321 FrontendOpts.ShowCodePatternsInCodeCompletion,
2322 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002323 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002324
Douglas Gregordf95a132010-08-09 20:45:32 +00002325 // If we have a precompiled preamble, try to use it. We only allow
2326 // the use of the precompiled preamble if we're if the completion
2327 // point is within the main file, after the end of the precompiled
2328 // preamble.
2329 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002330 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002331 using llvm::sys::FileStatus;
2332 llvm::sys::PathWithStatus CompleteFilePath(File);
2333 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2334 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2335 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002336 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2337 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002338 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002339 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002340 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002341 }
2342
2343 // If the main file has been overridden due to the use of a preamble,
2344 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002345 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002346 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002347 stored_diag_begin(),
2348 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002349 if (OverrideMainBuffer) {
2350 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2351 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2352 PreprocessorOpts.PrecompiledPreambleBytes.second
2353 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002354 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002355 PreprocessorOpts.DisablePCHValidation = true;
2356
Douglas Gregor2283d792010-08-20 00:59:43 +00002357 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002358 } else {
2359 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2360 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002361 }
2362
Douglas Gregordca8ee82011-05-06 16:33:08 +00002363 // Disable the preprocessing record
2364 PreprocessorOpts.DetailedRecord = false;
2365
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002366 llvm::OwningPtr<SyntaxOnlyAction> Act;
2367 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002368 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2369 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002370 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002371 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002372 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2373 getSourceManager(), PreambleDiagnostics,
2374 StoredDiagnostics);
2375 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002376 Act->Execute();
2377 Act->EndSourceFile();
2378 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002379}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002380
Chris Lattner5f9e2722011-07-23 10:55:15 +00002381CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002382 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002383 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002384
2385 // Write to a temporary file and later rename it to the actual file, to avoid
2386 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002387 llvm::SmallString<128> TempPath;
2388 TempPath = File;
2389 TempPath += "-%%%%%%%%";
2390 int fd;
2391 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2392 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002393 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002394
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002395 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2396 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002397 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002398
2399 serialize(Out);
2400 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002401 if (Out.has_error())
2402 return CXSaveError_Unknown;
2403
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002404 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002405 bool exists;
2406 llvm::sys::fs::remove(TempPath.str(), exists);
2407 return CXSaveError_Unknown;
2408 }
2409
2410 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002411}
2412
Chris Lattner5f9e2722011-07-23 10:55:15 +00002413bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002414 if (getDiagnostics().hasErrorOccurred())
2415 return true;
2416
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002417 std::vector<unsigned char> Buffer;
2418 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002419 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002420 // FIXME: Handle modules
Douglas Gregora8cc6ce2011-11-30 04:39:39 +00002421 Writer.WriteAST(getSema(), 0, std::string(), 0, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002422
2423 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002424 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002425 OS.write((char *)&Buffer.front(), Buffer.size());
2426
2427 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002428}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002429
2430typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2431
2432static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2433 unsigned Raw = L.getRawEncoding();
2434 const unsigned MacroBit = 1U << 31;
2435 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2436 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2437}
2438
2439void ASTUnit::TranslateStoredDiagnostics(
2440 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002441 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002442 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002443 const SmallVectorImpl<StoredDiagnostic> &Diags,
2444 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002445 // The stored diagnostic has the old source manager in it; update
2446 // the locations to refer into the new source manager. We also need to remap
2447 // all the locations to the new view. This includes the diag location, any
2448 // associated source ranges, and the source ranges of associated fix-its.
2449 // FIXME: There should be a cleaner way to do this.
2450
Chris Lattner5f9e2722011-07-23 10:55:15 +00002451 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002452 Result.reserve(Diags.size());
2453 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002454 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002455 assert(Mod && "Don't have preamble module");
2456 SLocRemap &Remap = Mod->SLocRemap;
2457 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2458 // Rebuild the StoredDiagnostic.
2459 const StoredDiagnostic &SD = Diags[I];
2460 SourceLocation L = SD.getLocation();
2461 TranslateSLoc(L, Remap);
2462 FullSourceLoc Loc(L, SrcMgr);
2463
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002465 Ranges.reserve(SD.range_size());
2466 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2467 E = SD.range_end();
2468 I != E; ++I) {
2469 SourceLocation BL = I->getBegin();
2470 TranslateSLoc(BL, Remap);
2471 SourceLocation EL = I->getEnd();
2472 TranslateSLoc(EL, Remap);
2473 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2474 }
2475
Chris Lattner5f9e2722011-07-23 10:55:15 +00002476 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002477 FixIts.reserve(SD.fixit_size());
2478 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2479 E = SD.fixit_end();
2480 I != E; ++I) {
2481 FixIts.push_back(FixItHint());
2482 FixItHint &FH = FixIts.back();
2483 FH.CodeToInsert = I->CodeToInsert;
2484 SourceLocation BL = I->RemoveRange.getBegin();
2485 TranslateSLoc(BL, Remap);
2486 SourceLocation EL = I->RemoveRange.getEnd();
2487 TranslateSLoc(EL, Remap);
2488 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2489 I->RemoveRange.isTokenRange());
2490 }
2491
2492 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2493 SD.getMessage(), Loc, Ranges, FixIts));
2494 }
2495 Result.swap(Out);
2496}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002497
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002498static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2499 std::pair<unsigned, Decl *> R) {
2500 return L.first < R.first;
2501}
2502
2503void ASTUnit::addFileLevelDecl(Decl *D) {
2504 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002505
2506 // We only care about local declarations.
2507 if (D->isFromASTFile())
2508 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002509
2510 SourceManager &SM = *SourceMgr;
2511 SourceLocation Loc = D->getLocation();
2512 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2513 return;
2514
2515 // We only keep track of the file-level declarations of each file.
2516 if (!D->getLexicalDeclContext()->isFileContext())
2517 return;
2518
2519 SourceLocation FileLoc = SM.getFileLoc(Loc);
2520 assert(SM.isLocalSourceLocation(FileLoc));
2521 FileID FID;
2522 unsigned Offset;
2523 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2524 if (FID.isInvalid())
2525 return;
2526
2527 LocDeclsTy *&Decls = FileDecls[FID];
2528 if (!Decls)
2529 Decls = new LocDeclsTy();
2530
2531 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2532
2533 if (Decls->empty() || Decls->back().first <= Offset) {
2534 Decls->push_back(LocDecl);
2535 return;
2536 }
2537
2538 LocDeclsTy::iterator
2539 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2540
2541 Decls->insert(I, LocDecl);
2542}
2543
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002544void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2545 SmallVectorImpl<Decl *> &Decls) {
2546 if (File.isInvalid())
2547 return;
2548
2549 if (SourceMgr->isLoadedFileID(File)) {
2550 assert(Ctx->getExternalSource() && "No external source!");
2551 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2552 Decls);
2553 }
2554
2555 FileDeclsTy::iterator I = FileDecls.find(File);
2556 if (I == FileDecls.end())
2557 return;
2558
2559 LocDeclsTy &LocDecls = *I->second;
2560 if (LocDecls.empty())
2561 return;
2562
2563 LocDeclsTy::iterator
2564 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2565 std::make_pair(Offset, (Decl*)0), compLocDecl);
2566 if (BeginIt != LocDecls.begin())
2567 --BeginIt;
2568
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002569 // If we are pointing at a top-level decl inside an objc container, we need
2570 // to backtrack until we find it otherwise we will fail to report that the
2571 // region overlaps with an objc container.
2572 while (BeginIt != LocDecls.begin() &&
2573 BeginIt->second->isTopLevelDeclInObjCContainer())
2574 --BeginIt;
2575
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002576 LocDeclsTy::iterator
2577 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2578 std::make_pair(Offset+Length, (Decl*)0),
2579 compLocDecl);
2580 if (EndIt != LocDecls.end())
2581 ++EndIt;
2582
2583 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2584 Decls.push_back(DIt->second);
2585}
2586
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002587SourceLocation ASTUnit::getLocation(const FileEntry *File,
2588 unsigned Line, unsigned Col) const {
2589 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002590 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002591 return SM.getMacroArgExpandedLocation(Loc);
2592}
2593
2594SourceLocation ASTUnit::getLocation(const FileEntry *File,
2595 unsigned Offset) const {
2596 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002597 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002598 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2599}
2600
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002601/// \brief If \arg Loc is a loaded location from the preamble, returns
2602/// the corresponding local location of the main file, otherwise it returns
2603/// \arg Loc.
2604SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2605 FileID PreambleID;
2606 if (SourceMgr)
2607 PreambleID = SourceMgr->getPreambleFileID();
2608
2609 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2610 return Loc;
2611
2612 unsigned Offs;
2613 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2614 SourceLocation FileLoc
2615 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2616 return FileLoc.getLocWithOffset(Offs);
2617 }
2618
2619 return Loc;
2620}
2621
2622/// \brief If \arg Loc is a local location of the main file but inside the
2623/// preamble chunk, returns the corresponding loaded location from the
2624/// preamble, otherwise it returns \arg Loc.
2625SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2626 FileID PreambleID;
2627 if (SourceMgr)
2628 PreambleID = SourceMgr->getPreambleFileID();
2629
2630 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2631 return Loc;
2632
2633 unsigned Offs;
2634 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2635 Offs < Preamble.size()) {
2636 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2637 return FileLoc.getLocWithOffset(Offs);
2638 }
2639
2640 return Loc;
2641}
2642
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002643bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2644 FileID FID;
2645 if (SourceMgr)
2646 FID = SourceMgr->getPreambleFileID();
2647
2648 if (Loc.isInvalid() || FID.isInvalid())
2649 return false;
2650
2651 return SourceMgr->isInFileID(Loc, FID);
2652}
2653
2654bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2655 FileID FID;
2656 if (SourceMgr)
2657 FID = SourceMgr->getMainFileID();
2658
2659 if (Loc.isInvalid() || FID.isInvalid())
2660 return false;
2661
2662 return SourceMgr->isInFileID(Loc, FID);
2663}
2664
2665SourceLocation ASTUnit::getEndOfPreambleFileID() {
2666 FileID FID;
2667 if (SourceMgr)
2668 FID = SourceMgr->getPreambleFileID();
2669
2670 if (FID.isInvalid())
2671 return SourceLocation();
2672
2673 return SourceMgr->getLocForEndOfFile(FID);
2674}
2675
2676SourceLocation ASTUnit::getStartOfMainFileID() {
2677 FileID FID;
2678 if (SourceMgr)
2679 FID = SourceMgr->getMainFileID();
2680
2681 if (FID.isInvalid())
2682 return SourceLocation();
2683
2684 return SourceMgr->getLocForStartOfFile(FID);
2685}
2686
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002687void ASTUnit::PreambleData::countLines() const {
2688 NumLines = 0;
2689 if (empty())
2690 return;
2691
2692 for (std::vector<char>::const_iterator
2693 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2694 if (*I == '\n')
2695 ++NumLines;
2696 }
2697 if (Buffer.back() != '\n')
2698 ++NumLines;
2699}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002700
2701#ifndef NDEBUG
2702ASTUnit::ConcurrencyState::ConcurrencyState() {
2703 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2704}
2705
2706ASTUnit::ConcurrencyState::~ConcurrencyState() {
2707 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2708}
2709
2710void ASTUnit::ConcurrencyState::start() {
2711 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2712 assert(acquired && "Concurrent access to ASTUnit!");
2713}
2714
2715void ASTUnit::ConcurrencyState::finish() {
2716 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2717}
2718
2719#else // NDEBUG
2720
2721ASTUnit::ConcurrencyState::ConcurrencyState() {}
2722ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2723void ASTUnit::ConcurrencyState::start() {}
2724void ASTUnit::ConcurrencyState::finish() {}
2725
2726#endif