blob: e31bf5500ba7b55efee91aaf97401cbbea73b1d9 [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
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000265void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
266
Douglas Gregor8071e422010-08-15 06:18:01 +0000267/// \brief Determine the set of code-completion contexts in which this
268/// declaration should be shown.
269static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000270 const LangOptions &LangOpts,
271 bool &IsNestedNameSpecifier) {
272 IsNestedNameSpecifier = false;
273
Douglas Gregor8071e422010-08-15 06:18:01 +0000274 if (isa<UsingShadowDecl>(ND))
275 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
276 if (!ND)
277 return 0;
278
279 unsigned Contexts = 0;
280 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
281 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
282 // Types can appear in these contexts.
283 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
284 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
285 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
286 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
287 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000288 | (1 << (CodeCompletionContext::CCC_Type - 1))
289 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000290
291 // In C++, types can appear in expressions contexts (for functional casts).
292 if (LangOpts.CPlusPlus)
293 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
294
295 // In Objective-C, message sends can send interfaces. In Objective-C++,
296 // all types are available due to functional casts.
297 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
298 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000299
300 // In Objective-C, you can only be a subclass of another Objective-C class
301 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000302 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000303
304 // Deal with tag names.
305 if (isa<EnumDecl>(ND)) {
306 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
307
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000308 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000310 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000311 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
312 if (Record->isUnion())
313 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
314 else
315 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
316
Douglas Gregor8071e422010-08-15 06:18:01 +0000317 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000318 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000319 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000320 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
322 // Values can appear in these contexts.
323 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
324 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000325 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
327 } else if (isa<ObjCProtocolDecl>(ND)) {
328 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000329 } else if (isa<ObjCCategoryDecl>(ND)) {
330 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000331 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000332 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000333
334 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000335 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000336 }
337
338 return Contexts;
339}
340
Douglas Gregor87c08a52010-08-13 22:48:40 +0000341void ASTUnit::CacheCodeCompletionResults() {
342 if (!TheSema)
343 return;
344
Douglas Gregor213f18b2010-10-28 15:44:59 +0000345 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000346 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000347
348 // Clear out the previous results.
349 ClearCachedCompletionResults();
350
351 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000352 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000353 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000354 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
355 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356
357 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000358 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
359
Douglas Gregor87c08a52010-08-13 22:48:40 +0000360 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
361 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000362 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000363 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000364 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000365 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000366 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000368 Ctx->getLangOptions(),
369 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000370 CachedResult.Priority = Results[I].Priority;
371 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000372 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000373
Douglas Gregorf5586f62010-08-16 18:08:11 +0000374 // Keep track of the type of this completion in an ASTContext-agnostic
375 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000376 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000377 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000378 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000379 CachedResult.Type = 0;
380 } else {
381 CanQualType CanUsageType
382 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
383 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
384
385 // Determine whether we have already seen this type. If so, we save
386 // ourselves the work of formatting the type string by using the
387 // temporary, CanQualType-based hash table to find the associated value.
388 unsigned &TypeValue = CompletionTypes[CanUsageType];
389 if (TypeValue == 0) {
390 TypeValue = CompletionTypes.size();
391 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
392 = TypeValue;
393 }
394
395 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000396 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000397
Douglas Gregor8071e422010-08-15 06:18:01 +0000398 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000399
400 /// Handle nested-name-specifiers in C++.
401 if (TheSema->Context.getLangOptions().CPlusPlus &&
402 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
403 // The contexts in which a nested-name-specifier can appear in C++.
404 unsigned NNSContexts
405 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
406 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
407 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
408 | (1 << (CodeCompletionContext::CCC_Statement - 1))
409 | (1 << (CodeCompletionContext::CCC_Expression - 1))
410 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
411 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
412 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
413 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000414 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000415 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
416 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000417
418 if (isa<NamespaceDecl>(Results[I].Declaration) ||
419 isa<NamespaceAliasDecl>(Results[I].Declaration))
420 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
421
422 if (unsigned RemainingContexts
423 = NNSContexts & ~CachedResult.ShowInContexts) {
424 // If there any contexts where this completion can be a
425 // nested-name-specifier but isn't already an option, create a
426 // nested-name-specifier completion.
427 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000428 CachedResult.Completion
429 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000430 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000431 CachedResult.ShowInContexts = RemainingContexts;
432 CachedResult.Priority = CCP_NestedNameSpecifier;
433 CachedResult.TypeClass = STC_Void;
434 CachedResult.Type = 0;
435 CachedCompletionResults.push_back(CachedResult);
436 }
437 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000438 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000439 }
440
Douglas Gregor87c08a52010-08-13 22:48:40 +0000441 case Result::RK_Keyword:
442 case Result::RK_Pattern:
443 // Ignore keywords and patterns; we don't care, since they are so
444 // easily regenerated.
445 break;
446
447 case Result::RK_Macro: {
448 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000449 CachedResult.Completion
450 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000451 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000452 CachedResult.ShowInContexts
453 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
454 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
455 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
456 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
457 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
458 | (1 << (CodeCompletionContext::CCC_Statement - 1))
459 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000460 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000461 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000462 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000463 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
464 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000465
Douglas Gregor87c08a52010-08-13 22:48:40 +0000466 CachedResult.Priority = Results[I].Priority;
467 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000468 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000469 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000470 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000471 CachedCompletionResults.push_back(CachedResult);
472 break;
473 }
474 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000475 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000476
477 // Save the current top-level hash value.
478 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000479}
480
481void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000483 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000484 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485}
486
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000487namespace {
488
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000489/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000490/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000491class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000492 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000493 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494 LangOptions &LangOpt;
495 HeaderSearch &HSI;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000496 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497 std::string &Predefines;
498 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000502 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000503public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000504 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
505 HeaderSearch &HSI,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000506 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
507 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000508 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000509 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000510 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000511 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000514 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000515 return false;
516
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000517 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000518
519 // Initialize the preprocessor.
520 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000521
522 // Initialize the ASTContext
523 Context.InitBuiltinTypes(*Target);
524
525 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000526 return false;
527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattner5f9e2722011-07-23 10:55:15 +0000529 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000530 // If we've already initialized the target, don't do it again.
531 if (Target)
532 return false;
533
534 // FIXME: This is broken, we should store the TargetOptions in the AST file.
535 TargetOptions TargetOpts;
536 TargetOpts.ABI = "";
537 TargetOpts.CXXABI = "";
538 TargetOpts.CPU = "";
539 TargetOpts.Features.clear();
540 TargetOpts.Triple = Triple;
541 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000542 return false;
543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000545 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000546 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000547 std::string &SuggestedPredefines,
548 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000549 Predefines = Buffers[0].Data;
550 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
551 Predefines += Buffers[I].Data;
552 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000553 return false;
554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000556 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000557 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
558 }
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000560 virtual void ReadCounter(unsigned Value) {
561 Counter = Value;
562 }
563};
564
David Blaikie26e7a902011-09-26 00:01:39 +0000565class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000566 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000567
568public:
David Blaikie26e7a902011-09-26 00:01:39 +0000569 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000570 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000571 : StoredDiags(StoredDiags) { }
572
David Blaikied6471f72011-09-25 23:23:43 +0000573 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000574 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000575
576 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
577 // Just drop any diagnostics that come from cloned consumers; they'll
578 // have different source managers anyway.
579 return new IgnoringDiagConsumer();
580 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000581};
582
583/// \brief RAII object that optionally captures diagnostics, if
584/// there is no diagnostic client to capture them already.
585class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000586 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000587 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000588 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000589
590public:
David Blaikied6471f72011-09-25 23:23:43 +0000591 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000592 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000593 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000594 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000595 if (RequestCapture || Diags.getClient() == 0) {
596 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000597 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000598 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000599 }
600
601 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000602 if (Diags.getClient() == &Client) {
603 Diags.takeClient();
604 Diags.setClient(PreviousClient);
605 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000606 }
607};
608
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000609} // anonymous namespace
610
David Blaikie26e7a902011-09-26 00:01:39 +0000611void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000612 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000613 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000614 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000615
Douglas Gregora88084b2010-02-18 18:08:43 +0000616 StoredDiags.push_back(StoredDiagnostic(Level, Info));
617}
618
Steve Naroff77accc12009-09-03 18:19:54 +0000619const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000620 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000621}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000622
Chris Lattner5f9e2722011-07-23 10:55:15 +0000623llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000624 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000625 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000626 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000627}
628
Douglas Gregore47be3e2010-11-11 00:39:14 +0000629/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikied6471f72011-09-25 23:23:43 +0000630void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000631 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000632 ASTUnit &AST, bool CaptureDiagnostics) {
633 if (!Diags.getPtr()) {
634 // No diagnostics engine was provided, so create our own diagnostics object
635 // with the default options.
636 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000637 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000638 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000639 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000640 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
641 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000642 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000643 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000644 }
645}
646
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000647ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikied6471f72011-09-25 23:23:43 +0000648 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000649 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000650 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000651 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000652 unsigned NumRemappedFiles,
653 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000654 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000655
656 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000657 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
658 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000659 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
660 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000661 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000662
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000663 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000664
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000665 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000666 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000667 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000668 AST->FileMgr = new FileManager(FileSystemOpts);
669 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
670 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000671 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000672 AST->getDiagnostics(),
673 AST->ASTFileLangOpts));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000674
Douglas Gregor4db64a42010-01-23 00:14:00 +0000675 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000676 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
677 if (const llvm::MemoryBuffer *
678 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
679 // Create the file entry for the file that we're mapping from.
680 const FileEntry *FromFile
681 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
682 memBuf->getBufferSize(),
683 0);
684 if (!FromFile) {
685 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
686 << RemappedFiles[I].first;
687 delete memBuf;
688 continue;
689 }
690
691 // Override the contents of the "from" file with the contents of
692 // the "to" file.
693 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
694
695 } else {
696 const char *fname = fileOrBuf.get<const char *>();
697 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
698 if (!ToFile) {
699 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
700 << RemappedFiles[I].first << fname;
701 continue;
702 }
703
704 // Create the file entry for the file that we're mapping from.
705 const FileEntry *FromFile
706 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
707 ToFile->getSize(),
708 0);
709 if (!FromFile) {
710 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
711 << RemappedFiles[I].first;
712 delete memBuf;
713 continue;
714 }
715
716 // Override the contents of the "from" file with the contents of
717 // the "to" file.
718 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000719 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000720 }
721
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000722 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000724 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000725 std::string Predefines;
726 unsigned Counter;
727
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000728 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000729
Douglas Gregor998b3d32011-09-01 23:39:15 +0000730 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
731 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
732 *AST,
733 /*IILookup=*/0,
734 /*OwnsHeaderSearch=*/false,
735 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000736 Preprocessor &PP = *AST->PP;
737
738 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
739 AST->getSourceManager(),
740 /*Target=*/0,
741 PP.getIdentifierTable(),
742 PP.getSelectorTable(),
743 PP.getBuiltinInfo(),
744 /* size_reserve = */0,
745 /*DelayInitialization=*/true);
746 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000747
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000748 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000749
750 // Recover resources if we crash before exiting this method.
751 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
752 ReaderCleanup(Reader.get());
753
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000754 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000755 AST->ASTFileLangOpts, HeaderInfo,
756 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000757
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000758 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000759 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000760 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000762 case ASTReader::Failure:
763 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000764 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000765 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000768 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
769
Daniel Dunbard5b61262009-09-21 03:03:47 +0000770 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000771 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000773 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000774 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000775 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000776 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000777 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000778
779 // Unregister the cleanup for ASTReader. It will get cleaned up
780 // by the ASTUnit cleanup.
781 ReaderCleanup.unregister();
782
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000783 Context.setExternalSource(Source);
784
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000785 // Create an AST consumer, even though it isn't used.
786 AST->Consumer.reset(new ASTConsumer);
787
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000788 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000789 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
790 AST->TheSema->Initialize();
791 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000792 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000793
Mike Stump1eb44332009-09-09 15:08:12 +0000794 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000795}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000796
797namespace {
798
Douglas Gregor9b7db622011-02-16 18:16:54 +0000799/// \brief Preprocessor callback class that updates a hash value with the names
800/// of all macros that have been defined by the translation unit.
801class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
802 unsigned &Hash;
803
804public:
805 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
806
807 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
808 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
809 }
810};
811
812/// \brief Add the given declaration to the hash of all top-level entities.
813void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
814 if (!D)
815 return;
816
817 DeclContext *DC = D->getDeclContext();
818 if (!DC)
819 return;
820
821 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
822 return;
823
824 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
825 if (ND->getIdentifier())
826 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
827 else if (DeclarationName Name = ND->getDeclName()) {
828 std::string NameStr = Name.getAsString();
829 Hash = llvm::HashString(NameStr, Hash);
830 }
831 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000832 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000833}
834
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000835class TopLevelDeclTrackerConsumer : public ASTConsumer {
836 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000837 unsigned &Hash;
838
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000839public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000840 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
841 : Unit(_Unit), Hash(Hash) {
842 Hash = 0;
843 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000844
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000845 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000846 if (!D)
847 return;
848
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000849 // FIXME: Currently ObjC method declarations are incorrectly being
850 // reported as top-level declarations, even though their DeclContext
851 // is the containing ObjC @interface/@implementation. This is a
852 // fundamental problem in the parser right now.
853 if (isa<ObjCMethodDecl>(D))
854 return;
855
856 AddTopLevelDeclarationToHash(D, Hash);
857 Unit.addTopLevelDecl(D);
858
859 handleFileLevelDecl(D);
860 }
861
862 void handleFileLevelDecl(Decl *D) {
863 Unit.addFileLevelDecl(D);
864 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
865 for (NamespaceDecl::decl_iterator
866 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
867 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000868 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000869 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000870
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000871 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000872 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
873 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000874 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000875 }
876
Sebastian Redl27372b42010-08-11 18:52:41 +0000877 // We're not interested in "interesting" decls.
878 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000879
880 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
881 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
882 handleTopLevelDecl(*it);
883 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000884};
885
886class TopLevelDeclTrackerAction : public ASTFrontendAction {
887public:
888 ASTUnit &Unit;
889
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000890 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000891 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000892 CI.getPreprocessor().addPPCallbacks(
893 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
894 return new TopLevelDeclTrackerConsumer(Unit,
895 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000896 }
897
898public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000899 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
900
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000901 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000902 virtual TranslationUnitKind getTranslationUnitKind() {
903 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000904 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000905};
906
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000907class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000908 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000909 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000910 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000911
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000912public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000913 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000914 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000915 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000916 Hash(Unit.getCurrentTopLevelHashValue()) {
917 Hash = 0;
918 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000919
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000920 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000921 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
922 Decl *D = *it;
923 // FIXME: Currently ObjC method declarations are incorrectly being
924 // reported as top-level declarations, even though their DeclContext
925 // is the containing ObjC @interface/@implementation. This is a
926 // fundamental problem in the parser right now.
927 if (isa<ObjCMethodDecl>(D))
928 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000929 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000930 TopLevelDecls.push_back(D);
931 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000932 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000933 }
934
935 virtual void HandleTranslationUnit(ASTContext &Ctx) {
936 PCHGenerator::HandleTranslationUnit(Ctx);
937 if (!Unit.getDiagnostics().hasErrorOccurred()) {
938 // Translate the top-level declarations we captured during
939 // parsing into declaration IDs in the precompiled
940 // preamble. This will allow us to deserialize those top-level
941 // declarations when requested.
942 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
943 Unit.addTopLevelDeclFromPreamble(
944 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000945 }
946 }
947};
948
949class PrecompilePreambleAction : public ASTFrontendAction {
950 ASTUnit &Unit;
951
952public:
953 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
954
955 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000956 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000957 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000958 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000959 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000960 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
961 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000962 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000963 return 0;
964
Douglas Gregor832d6202011-07-22 16:35:34 +0000965 if (!CI.getFrontendOpts().RelocatablePCH)
966 Sysroot.clear();
967
Douglas Gregor9b7db622011-02-16 18:16:54 +0000968 CI.getPreprocessor().addPPCallbacks(
969 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000970 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
971 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000972 }
973
974 virtual bool hasCodeCompletionSupport() const { return false; }
975 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000976 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000977};
978
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000979}
980
Douglas Gregorabc563f2010-07-19 21:46:24 +0000981/// Parse the source file into a translation unit using the given compiler
982/// invocation, replacing the current translation unit.
983///
984/// \returns True if a failure occurred that causes the ASTUnit not to
985/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000986bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000987 delete SavedMainFileBuffer;
988 SavedMainFileBuffer = 0;
989
Ted Kremenek4f327862011-03-21 18:40:17 +0000990 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000991 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000992 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000993 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000994
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000995 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000996 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
997
998 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000999 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1000 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001001
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001002 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1003 CCInvocation(new CompilerInvocation(*Invocation));
1004
1005 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001006 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001007
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001008 // Set up diagnostics, capturing any diagnostics that would
1009 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001010 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001011
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001012 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001013 Clang->getTargetOpts().Features = TargetFeatures;
1014 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001015 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001016 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001017 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001018 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001019 }
1020
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001021 // Inform the target of the language options.
1022 //
1023 // FIXME: We shouldn't need to do this, the target should be immutable once
1024 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001025 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001026
Ted Kremenek03201fb2011-03-21 18:40:07 +00001027 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001028 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001029 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001030 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001031 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001032 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001033
Douglas Gregorabc563f2010-07-19 21:46:24 +00001034 // Configure the various subsystems.
1035 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001036 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001037 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001038 FileMgr = new FileManager(FileSystemOpts);
1039 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001040 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001041 Ctx = 0;
1042 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001043 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001044
1045 // Clear out old caches and data.
1046 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001047 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001048 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001049
Douglas Gregorf128fed2010-08-20 00:02:33 +00001050 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001051 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf128fed2010-08-20 00:02:33 +00001052 TopLevelDeclsInPreamble.clear();
1053 }
1054
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001055 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001056 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001057
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001058 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001059 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001060
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001061 // If the main file has been overridden due to the use of a preamble,
1062 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001063 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +00001064 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1065 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001066 if (OverrideMainBuffer) {
1067 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1068 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1069 PreprocessorOpts.PrecompiledPreambleBytes.second
1070 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001071 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001072 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001073
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001074 // The stored diagnostic has the old source manager in it; update
1075 // the locations to refer into the new source manager. Since we've
1076 // been careful to make sure that the source manager's state
1077 // before and after are identical, so that we can reuse the source
1078 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001079 for (unsigned I = NumStoredDiagnosticsFromDriver,
1080 N = StoredDiagnostics.size();
1081 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001082 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1083 getSourceManager());
1084 StoredDiagnostics[I].setLocation(Loc);
1085 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001086
1087 // Keep track of the override buffer;
1088 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001089 }
1090
Ted Kremenek25a11e12011-03-22 01:15:24 +00001091 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1092 new TopLevelDeclTrackerAction(*this));
1093
1094 // Recover resources if we crash before exiting this method.
1095 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1096 ActCleanup(Act.get());
1097
Ted Kremenek03201fb2011-03-21 18:40:07 +00001098 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1099 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001100 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001101
1102 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001103 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001104 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1105 getSourceManager(), PreambleDiagnostics,
1106 StoredDiagnostics);
1107 }
1108
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001109 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001110
Ted Kremenek4f327862011-03-21 18:40:17 +00001111 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001112 TheSema.reset(Clang->takeSema());
1113 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +00001114 Ctx = &Clang->getASTContext();
1115 PP = &Clang->getPreprocessor();
1116 Clang->setSourceManager(0);
1117 Clang->setFileManager(0);
1118 Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001119 Reader = Clang->getModuleManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001120
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001121 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001122
Douglas Gregorabc563f2010-07-19 21:46:24 +00001123 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001124
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001125error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001126 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001127 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001128 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001129 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001130 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001131
Douglas Gregord54eb442010-10-12 16:25:54 +00001132 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001133 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001134 return true;
1135}
1136
Douglas Gregor44c181a2010-07-23 00:33:23 +00001137/// \brief Simple function to retrieve a path for a preamble precompiled header.
1138static std::string GetPreamblePCHPath() {
1139 // FIXME: This is lame; sys::Path should provide this function (in particular,
1140 // it should know how to find the temporary files dir).
1141 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001142 // FIXME: This is a hack so that we can override the preamble file during
1143 // crash-recovery testing, which is the only case where the preamble files
1144 // are not necessarily cleaned up.
1145 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1146 if (TmpFile)
1147 return TmpFile;
1148
Douglas Gregor44c181a2010-07-23 00:33:23 +00001149 std::string Error;
1150 const char *TmpDir = ::getenv("TMPDIR");
1151 if (!TmpDir)
1152 TmpDir = ::getenv("TEMP");
1153 if (!TmpDir)
1154 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001155#ifdef LLVM_ON_WIN32
1156 if (!TmpDir)
1157 TmpDir = ::getenv("USERPROFILE");
1158#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001159 if (!TmpDir)
1160 TmpDir = "/tmp";
1161 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001162 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001163 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001164 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001165 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001166 return std::string();
1167
Douglas Gregor44c181a2010-07-23 00:33:23 +00001168 return P.str();
1169}
1170
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001171/// \brief Compute the preamble for the main file, providing the source buffer
1172/// that corresponds to the main file along with a pair (bytes, start-of-line)
1173/// that describes the preamble.
1174std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001175ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1176 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001177 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001178 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001179 CreatedBuffer = false;
1180
Douglas Gregor44c181a2010-07-23 00:33:23 +00001181 // Try to determine if the main file has been remapped, either from the
1182 // command line (to another file) or directly through the compiler invocation
1183 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001184 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001185 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1186 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1187 // Check whether there is a file-file remapping of the main file
1188 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001189 M = PreprocessorOpts.remapped_file_begin(),
1190 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001191 M != E;
1192 ++M) {
1193 llvm::sys::PathWithStatus MPath(M->first);
1194 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1195 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1196 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001197 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001198 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001199 CreatedBuffer = false;
1200 }
1201
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001202 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001203 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001204 return std::make_pair((llvm::MemoryBuffer*)0,
1205 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001206 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001207 }
1208 }
1209 }
1210
1211 // Check whether there is a file-buffer remapping. It supercedes the
1212 // file-file remapping.
1213 for (PreprocessorOptions::remapped_file_buffer_iterator
1214 M = PreprocessorOpts.remapped_file_buffer_begin(),
1215 E = PreprocessorOpts.remapped_file_buffer_end();
1216 M != E;
1217 ++M) {
1218 llvm::sys::PathWithStatus MPath(M->first);
1219 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1220 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1221 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001222 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001223 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001224 CreatedBuffer = false;
1225 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226
Douglas Gregor175c4a92010-07-23 23:58:40 +00001227 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 }
1229 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001230 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231 }
1232
1233 // If the main source file was not remapped, load it now.
1234 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001235 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001236 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001237 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001238
1239 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001240 }
1241
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001242 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001243 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001244 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001245}
1246
Douglas Gregor754f3492010-07-24 00:38:13 +00001247static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001248 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001249 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001250 llvm::MemoryBuffer *Result
1251 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1252 memcpy(const_cast<char*>(Result->getBufferStart()),
1253 Old->getBufferStart(), Old->getBufferSize());
1254 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001255 ' ', NewSize - Old->getBufferSize() - 1);
1256 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001257
Douglas Gregor754f3492010-07-24 00:38:13 +00001258 return Result;
1259}
1260
Douglas Gregor175c4a92010-07-23 23:58:40 +00001261/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1262/// the source file.
1263///
1264/// This routine will compute the preamble of the main source file. If a
1265/// non-trivial preamble is found, it will precompile that preamble into a
1266/// precompiled header so that the precompiled preamble can be used to reduce
1267/// reparsing time. If a precompiled preamble has already been constructed,
1268/// this routine will determine if it is still valid and, if so, avoid
1269/// rebuilding the precompiled preamble.
1270///
Douglas Gregordf95a132010-08-09 20:45:32 +00001271/// \param AllowRebuild When true (the default), this routine is
1272/// allowed to rebuild the precompiled preamble if it is found to be
1273/// out-of-date.
1274///
1275/// \param MaxLines When non-zero, the maximum number of lines that
1276/// can occur within the preamble.
1277///
Douglas Gregor754f3492010-07-24 00:38:13 +00001278/// \returns If the precompiled preamble can be used, returns a newly-allocated
1279/// buffer that should be used in place of the main file when doing so.
1280/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001281llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001282 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001283 bool AllowRebuild,
1284 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001285
1286 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1287 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1288 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001289 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001290 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001291
1292 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001293 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001294 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001295
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001296 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001297 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1298 if (CreatedPreambleBuffer)
1299 OwnedPreambleBuffer.reset(NewPreamble.first);
1300
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001301 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001302 // We couldn't find a preamble in the main source. Clear out the current
1303 // preamble, if we have one. It's obviously no good any more.
1304 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001305 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001306
1307 // The next time we actually see a preamble, precompile it.
1308 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001309 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001310 }
1311
1312 if (!Preamble.empty()) {
1313 // We've previously computed a preamble. Check whether we have the same
1314 // preamble now that we did before, and that there's enough space in
1315 // the main-file buffer within the precompiled preamble to fit the
1316 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001317 if (Preamble.size() == NewPreamble.second.first &&
1318 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001319 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001320 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001321 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001322 // The preamble has not changed. We may be able to re-use the precompiled
1323 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001324
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001325 // Check that none of the files used by the preamble have changed.
1326 bool AnyFileChanged = false;
1327
1328 // First, make a record of those files that have been overridden via
1329 // remapping or unsaved_files.
1330 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1331 for (PreprocessorOptions::remapped_file_iterator
1332 R = PreprocessorOpts.remapped_file_begin(),
1333 REnd = PreprocessorOpts.remapped_file_end();
1334 !AnyFileChanged && R != REnd;
1335 ++R) {
1336 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001337 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001338 // If we can't stat the file we're remapping to, assume that something
1339 // horrible happened.
1340 AnyFileChanged = true;
1341 break;
1342 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001343
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001344 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1345 StatBuf.st_mtime);
1346 }
1347 for (PreprocessorOptions::remapped_file_buffer_iterator
1348 R = PreprocessorOpts.remapped_file_buffer_begin(),
1349 REnd = PreprocessorOpts.remapped_file_buffer_end();
1350 !AnyFileChanged && R != REnd;
1351 ++R) {
1352 // FIXME: Should we actually compare the contents of file->buffer
1353 // remappings?
1354 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1355 0);
1356 }
1357
1358 // Check whether anything has changed.
1359 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1360 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1361 !AnyFileChanged && F != FEnd;
1362 ++F) {
1363 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1364 = OverriddenFiles.find(F->first());
1365 if (Overridden != OverriddenFiles.end()) {
1366 // This file was remapped; check whether the newly-mapped file
1367 // matches up with the previous mapping.
1368 if (Overridden->second != F->second)
1369 AnyFileChanged = true;
1370 continue;
1371 }
1372
1373 // The file was not remapped; check whether it has changed on disk.
1374 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001375 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001376 // If we can't stat the file, assume that something horrible happened.
1377 AnyFileChanged = true;
1378 } else if (StatBuf.st_size != F->second.first ||
1379 StatBuf.st_mtime != F->second.second)
1380 AnyFileChanged = true;
1381 }
1382
1383 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001384 // Okay! We can re-use the precompiled preamble.
1385
1386 // Set the state of the diagnostic object to mimic its state
1387 // after parsing the preamble.
1388 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001389 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001390 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001391 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001392
1393 // Create a version of the main file buffer that is padded to
1394 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001395 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001396 PreambleReservedSize,
1397 FrontendOpts.Inputs[0].second);
1398 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001399 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001400
1401 // If we aren't allowed to rebuild the precompiled preamble, just
1402 // return now.
1403 if (!AllowRebuild)
1404 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001405
Douglas Gregor175c4a92010-07-23 23:58:40 +00001406 // We can't reuse the previously-computed preamble. Build a new one.
1407 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001408 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001409 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001410 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001411 } else if (!AllowRebuild) {
1412 // We aren't allowed to rebuild the precompiled preamble; just
1413 // return now.
1414 return 0;
1415 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001416
1417 // If the preamble rebuild counter > 1, it's because we previously
1418 // failed to build a preamble and we're not yet ready to try
1419 // again. Decrement the counter and return a failure.
1420 if (PreambleRebuildCounter > 1) {
1421 --PreambleRebuildCounter;
1422 return 0;
1423 }
1424
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001425 // Create a temporary file for the precompiled preamble. In rare
1426 // circumstances, this can fail.
1427 std::string PreamblePCHPath = GetPreamblePCHPath();
1428 if (PreamblePCHPath.empty()) {
1429 // Try again next time.
1430 PreambleRebuildCounter = 1;
1431 return 0;
1432 }
1433
Douglas Gregor175c4a92010-07-23 23:58:40 +00001434 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001435 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001436 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001437
1438 // Create a new buffer that stores the preamble. The buffer also contains
1439 // extra space for the original contents of the file (which will be present
1440 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001441 // grows.
1442 PreambleReservedSize = NewPreamble.first->getBufferSize();
1443 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001444 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001445 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001446 PreambleReservedSize *= 2;
1447
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001448 // Save the preamble text for later; we'll need to compare against it for
1449 // subsequent reparses.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001450 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1451 Preamble.assign(FileMgr->getFile(MainFilename),
1452 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001453 NewPreamble.first->getBufferStart()
1454 + NewPreamble.second.first);
1455 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1456
Douglas Gregor671947b2010-08-19 01:33:06 +00001457 delete PreambleBuffer;
1458 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001459 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001460 FrontendOpts.Inputs[0].second);
1461 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001462 NewPreamble.first->getBufferStart(), Preamble.size());
1463 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001464 ' ', PreambleReservedSize - Preamble.size() - 1);
1465 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001466
1467 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001468 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001469 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1470
1471 // Tell the compiler invocation to generate a temporary precompiled header.
1472 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001473 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001474 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001475 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1476 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001477
1478 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001479 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1480
1481 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001482 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1483 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001484
Douglas Gregor01b6e312011-07-01 18:22:13 +00001485 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001486 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001487
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001488 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001489 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001490
1491 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001492 Clang->getTargetOpts().Features = TargetFeatures;
1493 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1494 Clang->getTargetOpts()));
1495 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001496 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1497 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001498 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001499 PreprocessorOpts.eraseRemappedFile(
1500 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001501 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001502 }
1503
1504 // Inform the target of the language options.
1505 //
1506 // FIXME: We shouldn't need to do this, the target should be immutable once
1507 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001508 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001509
Ted Kremenek03201fb2011-03-21 18:40:07 +00001510 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001511 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001512 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001513 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001514 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001515 "IR inputs not support here!");
1516
1517 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001518 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001519 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001520 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001521 TopLevelDecls.clear();
1522 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001523
1524 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001525 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001526
1527 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001528 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001529 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001530
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001531 llvm::OwningPtr<PrecompilePreambleAction> Act;
1532 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001533 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1534 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001535 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1536 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001537 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001538 PreprocessorOpts.eraseRemappedFile(
1539 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001540 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001541 }
1542
1543 Act->Execute();
1544 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001545
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001546 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001547 // There were errors parsing the preamble, so no precompiled header was
1548 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001549 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001550 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1551 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001552 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001553 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001554 PreprocessorOpts.eraseRemappedFile(
1555 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001556 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001557 }
1558
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001559 // Transfer any diagnostics generated when parsing the preamble into the set
1560 // of preamble diagnostics.
1561 PreambleDiagnostics.clear();
1562 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001563 stored_diag_afterDriver_begin(), stored_diag_end());
1564 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001565
Douglas Gregor175c4a92010-07-23 23:58:40 +00001566 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001567 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001568 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001569
1570 // Keep track of all of the files that the source manager knows about,
1571 // so we can verify whether they have changed or not.
1572 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001573 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001574 const llvm::MemoryBuffer *MainFileBuffer
1575 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1576 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1577 FEnd = SourceMgr.fileinfo_end();
1578 F != FEnd;
1579 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001580 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001581 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1582 continue;
1583
1584 FilesInPreamble[File->getName()]
1585 = std::make_pair(F->second->getSize(), File->getModificationTime());
1586 }
1587
Douglas Gregoreababfb2010-08-04 05:53:38 +00001588 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001589 PreprocessorOpts.eraseRemappedFile(
1590 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001591
1592 // If the hash of top-level entities differs from the hash of the top-level
1593 // entities the last time we rebuilt the preamble, clear out the completion
1594 // cache.
1595 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1596 CompletionCacheTopLevelHashValue = 0;
1597 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1598 }
1599
Douglas Gregor754f3492010-07-24 00:38:13 +00001600 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001601 PreambleReservedSize,
1602 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001603}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001604
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001605void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1606 std::vector<Decl *> Resolved;
1607 Resolved.reserve(TopLevelDeclsInPreamble.size());
1608 ExternalASTSource &Source = *getASTContext().getExternalSource();
1609 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1610 // Resolve the declaration ID to an actual declaration, possibly
1611 // deserializing the declaration in the process.
1612 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1613 if (D)
1614 Resolved.push_back(D);
1615 }
1616 TopLevelDeclsInPreamble.clear();
1617 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1618}
1619
Chris Lattner5f9e2722011-07-23 10:55:15 +00001620StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001621 return Invocation->getFrontendOpts().Inputs[0].second;
1622}
1623
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001624ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001625 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1626 bool CaptureDiagnostics) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001627 llvm::OwningPtr<ASTUnit> AST;
1628 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001629 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001630 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001631 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001632 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001633 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001634 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001635
1636 return AST.take();
1637}
1638
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001639ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001640 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001641 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001642 ASTUnit *Unit,
1643 bool Persistent,
1644 StringRef ResourceFilesPath,
1645 bool OnlyLocalDecls,
1646 bool CaptureDiagnostics,
1647 bool PrecompilePreamble,
1648 bool CacheCodeCompletionResults) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001649 assert(CI && "A CompilerInvocation is required");
1650
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001651 llvm::OwningPtr<ASTUnit> OwnAST;
1652 ASTUnit *AST = Unit;
1653 if (!AST) {
1654 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001655 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001656 AST = OwnAST.get();
1657 }
1658
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001659 if (!ResourceFilesPath.empty()) {
1660 // Override the resources path.
1661 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1662 }
1663 AST->OnlyLocalDecls = OnlyLocalDecls;
1664 AST->CaptureDiagnostics = CaptureDiagnostics;
1665 if (PrecompilePreamble)
1666 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001667 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001668 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001669
1670 // Recover resources if we crash before exiting this method.
1671 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001672 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001673 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1674 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001675 DiagCleanup(Diags.getPtr());
1676
1677 // We'll manage file buffers ourselves.
1678 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1679 CI->getFrontendOpts().DisableFree = false;
1680 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1681
1682 // Save the target features.
1683 AST->TargetFeatures = CI->getTargetOpts().Features;
1684
1685 // Create the compiler instance to use for building the AST.
1686 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1687
1688 // Recover resources if we crash before exiting this method.
1689 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1690 CICleanup(Clang.get());
1691
1692 Clang->setInvocation(CI);
1693 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1694
1695 // Set up diagnostics, capturing any diagnostics that would
1696 // otherwise be dropped.
1697 Clang->setDiagnostics(&AST->getDiagnostics());
1698
1699 // Create the target instance.
1700 Clang->getTargetOpts().Features = AST->TargetFeatures;
1701 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1702 Clang->getTargetOpts()));
1703 if (!Clang->hasTarget())
1704 return 0;
1705
1706 // Inform the target of the language options.
1707 //
1708 // FIXME: We shouldn't need to do this, the target should be immutable once
1709 // created. This complexity should be lifted elsewhere.
1710 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1711
1712 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1713 "Invocation must have exactly one source file!");
1714 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1715 "FIXME: AST inputs not yet supported here!");
1716 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1717 "IR inputs not supported here!");
1718
1719 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001720 AST->TheSema.reset();
1721 AST->Ctx = 0;
1722 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001723 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001724
1725 // Create a file manager object to provide access to and cache the filesystem.
1726 Clang->setFileManager(&AST->getFileManager());
1727
1728 // Create the source manager.
1729 Clang->setSourceManager(&AST->getSourceManager());
1730
1731 ASTFrontendAction *Act = Action;
1732
1733 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1734 if (!Act) {
1735 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1736 Act = TrackerAct.get();
1737 }
1738
1739 // Recover resources if we crash before exiting this method.
1740 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1741 ActCleanup(TrackerAct.get());
1742
1743 if (!Act->BeginSourceFile(*Clang.get(),
1744 Clang->getFrontendOpts().Inputs[0].second,
1745 Clang->getFrontendOpts().Inputs[0].first))
1746 return 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001747
1748 if (Persistent && !TrackerAct) {
1749 Clang->getPreprocessor().addPPCallbacks(
1750 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1751 std::vector<ASTConsumer*> Consumers;
1752 if (Clang->hasASTConsumer())
1753 Consumers.push_back(Clang->takeASTConsumer());
1754 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1755 AST->getCurrentTopLevelHashValue()));
1756 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1757 }
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758 Act->Execute();
1759
1760 // Steal the created target, context, and preprocessor.
1761 AST->TheSema.reset(Clang->takeSema());
1762 AST->Consumer.reset(Clang->takeASTConsumer());
1763 AST->Ctx = &Clang->getASTContext();
1764 AST->PP = &Clang->getPreprocessor();
1765 Clang->setSourceManager(0);
1766 Clang->setFileManager(0);
1767 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001768 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001769
1770 Act->EndSourceFile();
1771
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001772 if (OwnAST)
1773 return OwnAST.take();
1774 else
1775 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001776}
1777
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001778bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1779 if (!Invocation)
1780 return true;
1781
1782 // We'll manage file buffers ourselves.
1783 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1784 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001785 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001786
Douglas Gregor1aa27302011-01-27 18:02:58 +00001787 // Save the target features.
1788 TargetFeatures = Invocation->getTargetOpts().Features;
1789
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001790 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001791 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001792 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001793 OverrideMainBuffer
1794 = getMainBufferWithPrecompiledPreamble(*Invocation);
1795 }
1796
Douglas Gregor213f18b2010-10-28 15:44:59 +00001797 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001798 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001799
Ted Kremenek25a11e12011-03-22 01:15:24 +00001800 // Recover resources if we crash before exiting this method.
1801 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1802 MemBufferCleanup(OverrideMainBuffer);
1803
Douglas Gregor213f18b2010-10-28 15:44:59 +00001804 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001805}
1806
Douglas Gregorabc563f2010-07-19 21:46:24 +00001807ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001808 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001809 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001810 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001811 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001812 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001813 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001814 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001815 // Create the AST unit.
1816 llvm::OwningPtr<ASTUnit> AST;
1817 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001818 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001819 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001820 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001821 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001822 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001823 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001824 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001825 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001826
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001827 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001828 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1829 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001830 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1831 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001832 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001833
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001834 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001835}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001836
1837ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1838 const char **ArgEnd,
David Blaikied6471f72011-09-25 23:23:43 +00001839 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001840 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001841 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001842 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001843 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001844 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001845 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001846 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001847 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001848 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001849 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001850 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001851 // No diagnostics engine was provided, so create our own diagnostics object
1852 // with the default options.
1853 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001854 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1855 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001856 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001857
Chris Lattner5f9e2722011-07-23 10:55:15 +00001858 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001859
Ted Kremenek4f327862011-03-21 18:40:17 +00001860 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001861
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001862 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001863
Douglas Gregore47be3e2010-11-11 00:39:14 +00001864 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001865 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001866
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001867 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001868 llvm::makeArrayRef(ArgBegin, ArgEnd),
1869 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001870 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001871 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001872 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001873
Douglas Gregor4db64a42010-01-23 00:14:00 +00001874 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001875 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1876 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1877 if (const llvm::MemoryBuffer *
1878 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1879 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1880 } else {
1881 const char *fname = fileOrBuf.get<const char *>();
1882 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1883 }
1884 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001885 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1886 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001887
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001888 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001889 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001890
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001891 // Create the AST unit.
1892 llvm::OwningPtr<ASTUnit> AST;
1893 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001894 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001895 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001896 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001897 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001898 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001899 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001900 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001901 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001902 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1903 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001904 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001905 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001906 CI = 0; // Zero out now to ease cleanup during crash recovery.
Chandler Carruthba7537f2011-07-14 09:02:10 +00001907 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001908
1909 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001910 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1911 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001912
Chris Lattner39b49bc2010-11-23 08:35:12 +00001913 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001914}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001915
1916bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001917 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001918 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001919
1920 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001921
Douglas Gregor213f18b2010-10-28 15:44:59 +00001922 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001923 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001924
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001925 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001926 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001927 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001928 for (PreprocessorOptions::remapped_file_buffer_iterator
1929 R = PPOpts.remapped_file_buffer_begin(),
1930 REnd = PPOpts.remapped_file_buffer_end();
1931 R != REnd;
1932 ++R) {
1933 delete R->second;
1934 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001935 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001936 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1937 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1938 if (const llvm::MemoryBuffer *
1939 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1940 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1941 memBuf);
1942 } else {
1943 const char *fname = fileOrBuf.get<const char *>();
1944 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1945 fname);
1946 }
1947 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001948
Douglas Gregoreababfb2010-08-04 05:53:38 +00001949 // If we have a preamble file lying around, or if we might try to
1950 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001951 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001952 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001953 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001954
Douglas Gregorabc563f2010-07-19 21:46:24 +00001955 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001956 getDiagnostics().Reset();
1957 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00001958 if (OverrideMainBuffer)
1959 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001960
Douglas Gregor175c4a92010-07-23 23:58:40 +00001961 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001962 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00001963
1964 // If we're caching global code-completion results, and the top-level
1965 // declarations have changed, clear out the code-completion cache.
1966 if (!Result && ShouldCacheCodeCompletionResults &&
1967 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1968 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00001969
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001970 // We now need to clear out the completion allocator for
1971 // clang_getCursorCompletionString; it'll be recreated if necessary.
1972 CursorCompletionAllocator = 0;
1973
Douglas Gregor175c4a92010-07-23 23:58:40 +00001974 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001975}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001976
Douglas Gregor87c08a52010-08-13 22:48:40 +00001977//----------------------------------------------------------------------------//
1978// Code completion
1979//----------------------------------------------------------------------------//
1980
1981namespace {
1982 /// \brief Code completion consumer that combines the cached code-completion
1983 /// results from an ASTUnit with the code-completion results provided to it,
1984 /// then passes the result on to
1985 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001986 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001987 ASTUnit &AST;
1988 CodeCompleteConsumer &Next;
1989
1990 public:
1991 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001992 bool IncludeMacros, bool IncludeCodePatterns,
1993 bool IncludeGlobals)
1994 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001995 Next.isOutputBinary()), AST(AST), Next(Next)
1996 {
1997 // Compute the set of contexts in which we will look when we don't have
1998 // any information about the specific context.
1999 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002000 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2001 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2002 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2003 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2004 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2005 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2006 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2007 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2008 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2009 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2010 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2011 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2012 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002013
Douglas Gregor87c08a52010-08-13 22:48:40 +00002014 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002015 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2016 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2017 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002018 }
2019
2020 virtual void ProcessCodeCompleteResults(Sema &S,
2021 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002022 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002023 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002024
2025 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2026 OverloadCandidate *Candidates,
2027 unsigned NumCandidates) {
2028 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2029 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002030
Douglas Gregordae68752011-02-01 22:57:45 +00002031 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002032 return Next.getAllocator();
2033 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002034 };
2035}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002036
Douglas Gregor5f808c22010-08-16 21:18:39 +00002037/// \brief Helper function that computes which global names are hidden by the
2038/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002039static void CalculateHiddenNames(const CodeCompletionContext &Context,
2040 CodeCompletionResult *Results,
2041 unsigned NumResults,
2042 ASTContext &Ctx,
2043 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002044 bool OnlyTagNames = false;
2045 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002046 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002047 case CodeCompletionContext::CCC_TopLevel:
2048 case CodeCompletionContext::CCC_ObjCInterface:
2049 case CodeCompletionContext::CCC_ObjCImplementation:
2050 case CodeCompletionContext::CCC_ObjCIvarList:
2051 case CodeCompletionContext::CCC_ClassStructUnion:
2052 case CodeCompletionContext::CCC_Statement:
2053 case CodeCompletionContext::CCC_Expression:
2054 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002055 case CodeCompletionContext::CCC_DotMemberAccess:
2056 case CodeCompletionContext::CCC_ArrowMemberAccess:
2057 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002058 case CodeCompletionContext::CCC_Namespace:
2059 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002060 case CodeCompletionContext::CCC_Name:
2061 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002062 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002063 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002064 break;
2065
2066 case CodeCompletionContext::CCC_EnumTag:
2067 case CodeCompletionContext::CCC_UnionTag:
2068 case CodeCompletionContext::CCC_ClassOrStructTag:
2069 OnlyTagNames = true;
2070 break;
2071
2072 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002073 case CodeCompletionContext::CCC_MacroName:
2074 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002075 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002076 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002077 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002078 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002079 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002080 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002081 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002082 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2083 case CodeCompletionContext::CCC_ObjCClassMessage:
2084 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002085 // We're looking for nothing, or we're looking for names that cannot
2086 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002087 return;
2088 }
2089
John McCall0a2c5e22010-08-25 06:19:51 +00002090 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002091 for (unsigned I = 0; I != NumResults; ++I) {
2092 if (Results[I].Kind != Result::RK_Declaration)
2093 continue;
2094
2095 unsigned IDNS
2096 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2097
2098 bool Hiding = false;
2099 if (OnlyTagNames)
2100 Hiding = (IDNS & Decl::IDNS_Tag);
2101 else {
2102 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002103 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2104 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002105 if (Ctx.getLangOptions().CPlusPlus)
2106 HiddenIDNS |= Decl::IDNS_Tag;
2107 Hiding = (IDNS & HiddenIDNS);
2108 }
2109
2110 if (!Hiding)
2111 continue;
2112
2113 DeclarationName Name = Results[I].Declaration->getDeclName();
2114 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2115 HiddenNames.insert(Identifier->getName());
2116 else
2117 HiddenNames.insert(Name.getAsString());
2118 }
2119}
2120
2121
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002122void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2123 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002124 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002125 unsigned NumResults) {
2126 // Merge the results we were given with the results we cached.
2127 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002128 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002129 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002130 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002131 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002132 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002133 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002134 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002135 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002136 C = AST.cached_completion_begin(),
2137 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002138 C != CEnd; ++C) {
2139 // If the context we are in matches any of the contexts we are
2140 // interested in, we'll add this result.
2141 if ((C->ShowInContexts & InContexts) == 0)
2142 continue;
2143
2144 // If we haven't added any results previously, do so now.
2145 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002146 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2147 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002148 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2149 AddedResult = true;
2150 }
2151
Douglas Gregor5f808c22010-08-16 21:18:39 +00002152 // Determine whether this global completion result is hidden by a local
2153 // completion result. If so, skip it.
2154 if (C->Kind != CXCursor_MacroDefinition &&
2155 HiddenNames.count(C->Completion->getTypedText()))
2156 continue;
2157
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002158 // Adjust priority based on similar type classes.
2159 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002160 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002161 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002162 if (!Context.getPreferredType().isNull()) {
2163 if (C->Kind == CXCursor_MacroDefinition) {
2164 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002165 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002166 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002167 } else if (C->Type) {
2168 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002169 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002170 Context.getPreferredType().getUnqualifiedType());
2171 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2172 if (ExpectedSTC == C->TypeClass) {
2173 // We know this type is similar; check for an exact match.
2174 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002175 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002176 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002177 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002178 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2179 Priority /= CCF_ExactTypeMatch;
2180 else
2181 Priority /= CCF_SimilarTypeMatch;
2182 }
2183 }
2184 }
2185
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002186 // Adjust the completion string, if required.
2187 if (C->Kind == CXCursor_MacroDefinition &&
2188 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2189 // Create a new code-completion string that just contains the
2190 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002191 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2192 C->Availability);
2193 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002194 CursorKind = CXCursor_NotImplemented;
2195 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002196 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002197 }
2198
Douglas Gregor4125c372010-08-25 18:03:13 +00002199 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002200 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002201 }
2202
2203 // If we did not add any cached completion results, just forward the
2204 // results we were given to the next consumer.
2205 if (!AddedResult) {
2206 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2207 return;
2208 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002209
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002210 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2211 AllResults.size());
2212}
2213
2214
2215
Chris Lattner5f9e2722011-07-23 10:55:15 +00002216void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002217 RemappedFile *RemappedFiles,
2218 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002219 bool IncludeMacros,
2220 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002221 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002222 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002223 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002224 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2225 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002226 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002227 return;
2228
Douglas Gregor213f18b2010-10-28 15:44:59 +00002229 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002230 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002231 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002232
Ted Kremenek4f327862011-03-21 18:40:17 +00002233 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2234 CCInvocation(new CompilerInvocation(*Invocation));
2235
2236 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2237 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002238
Douglas Gregor87c08a52010-08-13 22:48:40 +00002239 FrontendOpts.ShowMacrosInCodeCompletion
2240 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002241 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002242 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2243 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002244 FrontendOpts.CodeCompletionAt.FileName = File;
2245 FrontendOpts.CodeCompletionAt.Line = Line;
2246 FrontendOpts.CodeCompletionAt.Column = Column;
2247
2248 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002249 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002250
Ted Kremenek03201fb2011-03-21 18:40:07 +00002251 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2252
2253 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002254 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2255 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002256
Ted Kremenek4f327862011-03-21 18:40:17 +00002257 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002258 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002259
2260 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002261 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002262 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002263 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002264 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002265 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002266
2267 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002268 Clang->getTargetOpts().Features = TargetFeatures;
2269 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2270 Clang->getTargetOpts()));
2271 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002272 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002273 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002274 }
2275
2276 // Inform the target of the language options.
2277 //
2278 // FIXME: We shouldn't need to do this, the target should be immutable once
2279 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002280 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002281
Ted Kremenek03201fb2011-03-21 18:40:07 +00002282 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002283 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002284 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002285 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002286 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002287 "IR inputs not support here!");
2288
2289
2290 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002291 Clang->setFileManager(&FileMgr);
2292 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002293
2294 // Remap files.
2295 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002296 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002297 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002298 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2299 if (const llvm::MemoryBuffer *
2300 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2301 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2302 OwnedBuffers.push_back(memBuf);
2303 } else {
2304 const char *fname = fileOrBuf.get<const char *>();
2305 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2306 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002307 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002308
Douglas Gregor87c08a52010-08-13 22:48:40 +00002309 // Use the code completion consumer we were given, but adding any cached
2310 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002311 AugmentedCodeCompleteConsumer *AugmentedConsumer
2312 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2313 FrontendOpts.ShowMacrosInCodeCompletion,
2314 FrontendOpts.ShowCodePatternsInCodeCompletion,
2315 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002316 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002317
Douglas Gregordf95a132010-08-09 20:45:32 +00002318 // If we have a precompiled preamble, try to use it. We only allow
2319 // the use of the precompiled preamble if we're if the completion
2320 // point is within the main file, after the end of the precompiled
2321 // preamble.
2322 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002323 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002324 using llvm::sys::FileStatus;
2325 llvm::sys::PathWithStatus CompleteFilePath(File);
2326 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2327 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2328 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002329 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2330 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002331 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002332 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002333 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002334 }
2335
2336 // If the main file has been overridden due to the use of a preamble,
2337 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002338 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002339 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002340 stored_diag_begin(),
2341 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002342 if (OverrideMainBuffer) {
2343 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2344 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2345 PreprocessorOpts.PrecompiledPreambleBytes.second
2346 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002347 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002348 PreprocessorOpts.DisablePCHValidation = true;
2349
Douglas Gregor2283d792010-08-20 00:59:43 +00002350 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002351 } else {
2352 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2353 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002354 }
2355
Douglas Gregordca8ee82011-05-06 16:33:08 +00002356 // Disable the preprocessing record
2357 PreprocessorOpts.DetailedRecord = false;
2358
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002359 llvm::OwningPtr<SyntaxOnlyAction> Act;
2360 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002361 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2362 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002363 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002364 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002365 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2366 getSourceManager(), PreambleDiagnostics,
2367 StoredDiagnostics);
2368 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002369 Act->Execute();
2370 Act->EndSourceFile();
2371 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002372}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002373
Chris Lattner5f9e2722011-07-23 10:55:15 +00002374CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002375 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002376 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002377
2378 // Write to a temporary file and later rename it to the actual file, to avoid
2379 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002380 llvm::SmallString<128> TempPath;
2381 TempPath = File;
2382 TempPath += "-%%%%%%%%";
2383 int fd;
2384 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2385 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002386 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002387
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002388 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2389 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002390 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002391
2392 serialize(Out);
2393 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002394 if (Out.has_error())
2395 return CXSaveError_Unknown;
2396
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002397 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002398 bool exists;
2399 llvm::sys::fs::remove(TempPath.str(), exists);
2400 return CXSaveError_Unknown;
2401 }
2402
2403 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002404}
2405
Chris Lattner5f9e2722011-07-23 10:55:15 +00002406bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002407 if (getDiagnostics().hasErrorOccurred())
2408 return true;
2409
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002410 std::vector<unsigned char> Buffer;
2411 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002412 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002413 // FIXME: Handle modules
Douglas Gregora8cc6ce2011-11-30 04:39:39 +00002414 Writer.WriteAST(getSema(), 0, std::string(), 0, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002415
2416 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002417 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002418 OS.write((char *)&Buffer.front(), Buffer.size());
2419
2420 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002421}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002422
2423typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2424
2425static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2426 unsigned Raw = L.getRawEncoding();
2427 const unsigned MacroBit = 1U << 31;
2428 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2429 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2430}
2431
2432void ASTUnit::TranslateStoredDiagnostics(
2433 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002434 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002435 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002436 const SmallVectorImpl<StoredDiagnostic> &Diags,
2437 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002438 // The stored diagnostic has the old source manager in it; update
2439 // the locations to refer into the new source manager. We also need to remap
2440 // all the locations to the new view. This includes the diag location, any
2441 // associated source ranges, and the source ranges of associated fix-its.
2442 // FIXME: There should be a cleaner way to do this.
2443
Chris Lattner5f9e2722011-07-23 10:55:15 +00002444 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002445 Result.reserve(Diags.size());
2446 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002447 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002448 assert(Mod && "Don't have preamble module");
2449 SLocRemap &Remap = Mod->SLocRemap;
2450 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2451 // Rebuild the StoredDiagnostic.
2452 const StoredDiagnostic &SD = Diags[I];
2453 SourceLocation L = SD.getLocation();
2454 TranslateSLoc(L, Remap);
2455 FullSourceLoc Loc(L, SrcMgr);
2456
Chris Lattner5f9e2722011-07-23 10:55:15 +00002457 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002458 Ranges.reserve(SD.range_size());
2459 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2460 E = SD.range_end();
2461 I != E; ++I) {
2462 SourceLocation BL = I->getBegin();
2463 TranslateSLoc(BL, Remap);
2464 SourceLocation EL = I->getEnd();
2465 TranslateSLoc(EL, Remap);
2466 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2467 }
2468
Chris Lattner5f9e2722011-07-23 10:55:15 +00002469 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002470 FixIts.reserve(SD.fixit_size());
2471 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2472 E = SD.fixit_end();
2473 I != E; ++I) {
2474 FixIts.push_back(FixItHint());
2475 FixItHint &FH = FixIts.back();
2476 FH.CodeToInsert = I->CodeToInsert;
2477 SourceLocation BL = I->RemoveRange.getBegin();
2478 TranslateSLoc(BL, Remap);
2479 SourceLocation EL = I->RemoveRange.getEnd();
2480 TranslateSLoc(EL, Remap);
2481 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2482 I->RemoveRange.isTokenRange());
2483 }
2484
2485 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2486 SD.getMessage(), Loc, Ranges, FixIts));
2487 }
2488 Result.swap(Out);
2489}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002490
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002491static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2492 std::pair<unsigned, Decl *> R) {
2493 return L.first < R.first;
2494}
2495
2496void ASTUnit::addFileLevelDecl(Decl *D) {
2497 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002498
2499 // We only care about local declarations.
2500 if (D->isFromASTFile())
2501 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002502
2503 SourceManager &SM = *SourceMgr;
2504 SourceLocation Loc = D->getLocation();
2505 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2506 return;
2507
2508 // We only keep track of the file-level declarations of each file.
2509 if (!D->getLexicalDeclContext()->isFileContext())
2510 return;
2511
2512 SourceLocation FileLoc = SM.getFileLoc(Loc);
2513 assert(SM.isLocalSourceLocation(FileLoc));
2514 FileID FID;
2515 unsigned Offset;
2516 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2517 if (FID.isInvalid())
2518 return;
2519
2520 LocDeclsTy *&Decls = FileDecls[FID];
2521 if (!Decls)
2522 Decls = new LocDeclsTy();
2523
2524 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2525
2526 if (Decls->empty() || Decls->back().first <= Offset) {
2527 Decls->push_back(LocDecl);
2528 return;
2529 }
2530
2531 LocDeclsTy::iterator
2532 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2533
2534 Decls->insert(I, LocDecl);
2535}
2536
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002537void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2538 SmallVectorImpl<Decl *> &Decls) {
2539 if (File.isInvalid())
2540 return;
2541
2542 if (SourceMgr->isLoadedFileID(File)) {
2543 assert(Ctx->getExternalSource() && "No external source!");
2544 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2545 Decls);
2546 }
2547
2548 FileDeclsTy::iterator I = FileDecls.find(File);
2549 if (I == FileDecls.end())
2550 return;
2551
2552 LocDeclsTy &LocDecls = *I->second;
2553 if (LocDecls.empty())
2554 return;
2555
2556 LocDeclsTy::iterator
2557 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2558 std::make_pair(Offset, (Decl*)0), compLocDecl);
2559 if (BeginIt != LocDecls.begin())
2560 --BeginIt;
2561
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002562 // If we are pointing at a top-level decl inside an objc container, we need
2563 // to backtrack until we find it otherwise we will fail to report that the
2564 // region overlaps with an objc container.
2565 while (BeginIt != LocDecls.begin() &&
2566 BeginIt->second->isTopLevelDeclInObjCContainer())
2567 --BeginIt;
2568
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002569 LocDeclsTy::iterator
2570 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2571 std::make_pair(Offset+Length, (Decl*)0),
2572 compLocDecl);
2573 if (EndIt != LocDecls.end())
2574 ++EndIt;
2575
2576 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2577 Decls.push_back(DIt->second);
2578}
2579
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002580SourceLocation ASTUnit::getLocation(const FileEntry *File,
2581 unsigned Line, unsigned Col) const {
2582 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002583 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002584 return SM.getMacroArgExpandedLocation(Loc);
2585}
2586
2587SourceLocation ASTUnit::getLocation(const FileEntry *File,
2588 unsigned Offset) const {
2589 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002590 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002591 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2592}
2593
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002594/// \brief If \arg Loc is a loaded location from the preamble, returns
2595/// the corresponding local location of the main file, otherwise it returns
2596/// \arg Loc.
2597SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2598 FileID PreambleID;
2599 if (SourceMgr)
2600 PreambleID = SourceMgr->getPreambleFileID();
2601
2602 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2603 return Loc;
2604
2605 unsigned Offs;
2606 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2607 SourceLocation FileLoc
2608 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2609 return FileLoc.getLocWithOffset(Offs);
2610 }
2611
2612 return Loc;
2613}
2614
2615/// \brief If \arg Loc is a local location of the main file but inside the
2616/// preamble chunk, returns the corresponding loaded location from the
2617/// preamble, otherwise it returns \arg Loc.
2618SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2619 FileID PreambleID;
2620 if (SourceMgr)
2621 PreambleID = SourceMgr->getPreambleFileID();
2622
2623 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2624 return Loc;
2625
2626 unsigned Offs;
2627 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2628 Offs < Preamble.size()) {
2629 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2630 return FileLoc.getLocWithOffset(Offs);
2631 }
2632
2633 return Loc;
2634}
2635
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002636bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2637 FileID FID;
2638 if (SourceMgr)
2639 FID = SourceMgr->getPreambleFileID();
2640
2641 if (Loc.isInvalid() || FID.isInvalid())
2642 return false;
2643
2644 return SourceMgr->isInFileID(Loc, FID);
2645}
2646
2647bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2648 FileID FID;
2649 if (SourceMgr)
2650 FID = SourceMgr->getMainFileID();
2651
2652 if (Loc.isInvalid() || FID.isInvalid())
2653 return false;
2654
2655 return SourceMgr->isInFileID(Loc, FID);
2656}
2657
2658SourceLocation ASTUnit::getEndOfPreambleFileID() {
2659 FileID FID;
2660 if (SourceMgr)
2661 FID = SourceMgr->getPreambleFileID();
2662
2663 if (FID.isInvalid())
2664 return SourceLocation();
2665
2666 return SourceMgr->getLocForEndOfFile(FID);
2667}
2668
2669SourceLocation ASTUnit::getStartOfMainFileID() {
2670 FileID FID;
2671 if (SourceMgr)
2672 FID = SourceMgr->getMainFileID();
2673
2674 if (FID.isInvalid())
2675 return SourceLocation();
2676
2677 return SourceMgr->getLocForStartOfFile(FID);
2678}
2679
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002680void ASTUnit::PreambleData::countLines() const {
2681 NumLines = 0;
2682 if (empty())
2683 return;
2684
2685 for (std::vector<char>::const_iterator
2686 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2687 if (*I == '\n')
2688 ++NumLines;
2689 }
2690 if (Buffer.back() != '\n')
2691 ++NumLines;
2692}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002693
2694#ifndef NDEBUG
2695ASTUnit::ConcurrencyState::ConcurrencyState() {
2696 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2697}
2698
2699ASTUnit::ConcurrencyState::~ConcurrencyState() {
2700 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2701}
2702
2703void ASTUnit::ConcurrencyState::start() {
2704 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2705 assert(acquired && "Concurrent access to ASTUnit!");
2706}
2707
2708void ASTUnit::ConcurrencyState::finish() {
2709 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2710}
2711
2712#else // NDEBUG
2713
2714ASTUnit::ConcurrencyState::ConcurrencyState() {}
2715ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2716void ASTUnit::ConcurrencyState::start() {}
2717void ASTUnit::ConcurrencyState::finish() {}
2718
2719#endif