blob: fce28b7488f8111b8da9e0121f6de68ac4ebc39f [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.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000579 // FIXME: We'd like to be able to capture these somehow, even if it's just
580 // file/line/column, because they could occur when parsing module maps or
581 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000582 return new IgnoringDiagConsumer();
583 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000584};
585
586/// \brief RAII object that optionally captures diagnostics, if
587/// there is no diagnostic client to capture them already.
588class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000589 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000590 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000591 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000592
593public:
David Blaikied6471f72011-09-25 23:23:43 +0000594 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000595 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000596 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000597 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000598 if (RequestCapture || Diags.getClient() == 0) {
599 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000600 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000601 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000602 }
603
604 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000605 if (Diags.getClient() == &Client) {
606 Diags.takeClient();
607 Diags.setClient(PreviousClient);
608 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000609 }
610};
611
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000612} // anonymous namespace
613
David Blaikie26e7a902011-09-26 00:01:39 +0000614void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000615 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000616 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000617 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000618
Douglas Gregora88084b2010-02-18 18:08:43 +0000619 StoredDiags.push_back(StoredDiagnostic(Level, Info));
620}
621
Steve Naroff77accc12009-09-03 18:19:54 +0000622const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000623 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000624}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000625
Chris Lattner5f9e2722011-07-23 10:55:15 +0000626llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000627 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000628 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000629 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000630}
631
Douglas Gregore47be3e2010-11-11 00:39:14 +0000632/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikied6471f72011-09-25 23:23:43 +0000633void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000634 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000635 ASTUnit &AST, bool CaptureDiagnostics) {
636 if (!Diags.getPtr()) {
637 // No diagnostics engine was provided, so create our own diagnostics object
638 // with the default options.
639 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000640 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000641 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000642 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000643 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
644 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000645 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000646 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000647 }
648}
649
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000650ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikied6471f72011-09-25 23:23:43 +0000651 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000652 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000653 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000654 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000655 unsigned NumRemappedFiles,
656 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000657 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000658
659 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000660 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
661 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000662 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
663 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000664 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000665
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000666 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000667
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000668 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000669 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000670 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000671 AST->FileMgr = new FileManager(FileSystemOpts);
672 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
673 AST->getFileManager());
Douglas Gregor8e238062011-11-11 00:35:06 +0000674 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000675 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000676 AST->ASTFileLangOpts,
677 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000678
Douglas Gregor4db64a42010-01-23 00:14:00 +0000679 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000680 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
681 if (const llvm::MemoryBuffer *
682 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
683 // Create the file entry for the file that we're mapping from.
684 const FileEntry *FromFile
685 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
686 memBuf->getBufferSize(),
687 0);
688 if (!FromFile) {
689 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
690 << RemappedFiles[I].first;
691 delete memBuf;
692 continue;
693 }
694
695 // Override the contents of the "from" file with the contents of
696 // the "to" file.
697 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
698
699 } else {
700 const char *fname = fileOrBuf.get<const char *>();
701 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
702 if (!ToFile) {
703 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
704 << RemappedFiles[I].first << fname;
705 continue;
706 }
707
708 // Create the file entry for the file that we're mapping from.
709 const FileEntry *FromFile
710 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
711 ToFile->getSize(),
712 0);
713 if (!FromFile) {
714 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
715 << RemappedFiles[I].first;
716 delete memBuf;
717 continue;
718 }
719
720 // Override the contents of the "from" file with the contents of
721 // the "to" file.
722 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000723 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000724 }
725
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000726 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000728 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000729 std::string Predefines;
730 unsigned Counter;
731
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000732 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000733
Douglas Gregor998b3d32011-09-01 23:39:15 +0000734 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
735 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
736 *AST,
737 /*IILookup=*/0,
738 /*OwnsHeaderSearch=*/false,
739 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000740 Preprocessor &PP = *AST->PP;
741
742 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
743 AST->getSourceManager(),
744 /*Target=*/0,
745 PP.getIdentifierTable(),
746 PP.getSelectorTable(),
747 PP.getBuiltinInfo(),
748 /* size_reserve = */0,
749 /*DelayInitialization=*/true);
750 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000751
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000752 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000753
754 // Recover resources if we crash before exiting this method.
755 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
756 ReaderCleanup(Reader.get());
757
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000758 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000759 AST->ASTFileLangOpts, HeaderInfo,
760 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000761
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000762 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000763 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000764 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000766 case ASTReader::Failure:
767 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000768 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000769 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000772 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
773
Daniel Dunbard5b61262009-09-21 03:03:47 +0000774 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000775 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000777 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000778 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000779 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000780 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000781 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000782
783 // Unregister the cleanup for ASTReader. It will get cleaned up
784 // by the ASTUnit cleanup.
785 ReaderCleanup.unregister();
786
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000787 Context.setExternalSource(Source);
788
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000789 // Create an AST consumer, even though it isn't used.
790 AST->Consumer.reset(new ASTConsumer);
791
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000792 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000793 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
794 AST->TheSema->Initialize();
795 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000796 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000797
Mike Stump1eb44332009-09-09 15:08:12 +0000798 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000799}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000800
801namespace {
802
Douglas Gregor9b7db622011-02-16 18:16:54 +0000803/// \brief Preprocessor callback class that updates a hash value with the names
804/// of all macros that have been defined by the translation unit.
805class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
806 unsigned &Hash;
807
808public:
809 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
810
811 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
812 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
813 }
814};
815
816/// \brief Add the given declaration to the hash of all top-level entities.
817void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
818 if (!D)
819 return;
820
821 DeclContext *DC = D->getDeclContext();
822 if (!DC)
823 return;
824
825 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
826 return;
827
828 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
829 if (ND->getIdentifier())
830 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
831 else if (DeclarationName Name = ND->getDeclName()) {
832 std::string NameStr = Name.getAsString();
833 Hash = llvm::HashString(NameStr, Hash);
834 }
835 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000836 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000837}
838
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000839class TopLevelDeclTrackerConsumer : public ASTConsumer {
840 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000841 unsigned &Hash;
842
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000843public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000844 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
845 : Unit(_Unit), Hash(Hash) {
846 Hash = 0;
847 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000848
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000849 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000850 if (!D)
851 return;
852
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000853 // FIXME: Currently ObjC method declarations are incorrectly being
854 // reported as top-level declarations, even though their DeclContext
855 // is the containing ObjC @interface/@implementation. This is a
856 // fundamental problem in the parser right now.
857 if (isa<ObjCMethodDecl>(D))
858 return;
859
860 AddTopLevelDeclarationToHash(D, Hash);
861 Unit.addTopLevelDecl(D);
862
863 handleFileLevelDecl(D);
864 }
865
866 void handleFileLevelDecl(Decl *D) {
867 Unit.addFileLevelDecl(D);
868 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
869 for (NamespaceDecl::decl_iterator
870 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
871 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000872 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000873 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000874
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000875 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000876 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
877 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000878 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000879 }
880
Sebastian Redl27372b42010-08-11 18:52:41 +0000881 // We're not interested in "interesting" decls.
882 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000883
884 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
885 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
886 handleTopLevelDecl(*it);
887 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000888};
889
890class TopLevelDeclTrackerAction : public ASTFrontendAction {
891public:
892 ASTUnit &Unit;
893
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000894 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000895 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000896 CI.getPreprocessor().addPPCallbacks(
897 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
898 return new TopLevelDeclTrackerConsumer(Unit,
899 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000900 }
901
902public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000903 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
904
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000905 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000906 virtual TranslationUnitKind getTranslationUnitKind() {
907 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000908 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000909};
910
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000911class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000912 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000913 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000914 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000915
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000916public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000917 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000918 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000919 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000920 Hash(Unit.getCurrentTopLevelHashValue()) {
921 Hash = 0;
922 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000923
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000924 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000925 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
926 Decl *D = *it;
927 // FIXME: Currently ObjC method declarations are incorrectly being
928 // reported as top-level declarations, even though their DeclContext
929 // is the containing ObjC @interface/@implementation. This is a
930 // fundamental problem in the parser right now.
931 if (isa<ObjCMethodDecl>(D))
932 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000933 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000934 TopLevelDecls.push_back(D);
935 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000936 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000937 }
938
939 virtual void HandleTranslationUnit(ASTContext &Ctx) {
940 PCHGenerator::HandleTranslationUnit(Ctx);
941 if (!Unit.getDiagnostics().hasErrorOccurred()) {
942 // Translate the top-level declarations we captured during
943 // parsing into declaration IDs in the precompiled
944 // preamble. This will allow us to deserialize those top-level
945 // declarations when requested.
946 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
947 Unit.addTopLevelDeclFromPreamble(
948 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000949 }
950 }
951};
952
953class PrecompilePreambleAction : public ASTFrontendAction {
954 ASTUnit &Unit;
955
956public:
957 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
958
959 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000960 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000961 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000962 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000963 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000964 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
965 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000966 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000967 return 0;
968
Douglas Gregor832d6202011-07-22 16:35:34 +0000969 if (!CI.getFrontendOpts().RelocatablePCH)
970 Sysroot.clear();
971
Douglas Gregor9b7db622011-02-16 18:16:54 +0000972 CI.getPreprocessor().addPPCallbacks(
973 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000974 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
975 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000976 }
977
978 virtual bool hasCodeCompletionSupport() const { return false; }
979 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000980 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000981};
982
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000983}
984
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000985static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
986 StoredDiagnostics) {
987 // Get rid of stored diagnostics except the ones from the driver which do not
988 // have a source location.
989 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
990 if (StoredDiagnostics[I].getLocation().isValid()) {
991 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
992 --I;
993 }
994 }
995}
996
997static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
998 StoredDiagnostics,
999 SourceManager &SM) {
1000 // The stored diagnostic has the old source manager in it; update
1001 // the locations to refer into the new source manager. Since we've
1002 // been careful to make sure that the source manager's state
1003 // before and after are identical, so that we can reuse the source
1004 // location itself.
1005 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1006 if (StoredDiagnostics[I].getLocation().isValid()) {
1007 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1008 StoredDiagnostics[I].setLocation(Loc);
1009 }
1010 }
1011}
1012
Douglas Gregorabc563f2010-07-19 21:46:24 +00001013/// Parse the source file into a translation unit using the given compiler
1014/// invocation, replacing the current translation unit.
1015///
1016/// \returns True if a failure occurred that causes the ASTUnit not to
1017/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001018bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001019 delete SavedMainFileBuffer;
1020 SavedMainFileBuffer = 0;
1021
Ted Kremenek4f327862011-03-21 18:40:17 +00001022 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001023 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001024 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001025 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001026
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001027 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001028 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001029
1030 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001031 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1032 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001033
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001034 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1035 CCInvocation(new CompilerInvocation(*Invocation));
1036
1037 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001038 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001039
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001040 // Set up diagnostics, capturing any diagnostics that would
1041 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001042 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001043
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001044 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001045 Clang->getTargetOpts().Features = TargetFeatures;
1046 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001047 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001048 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001049 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001050 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001051 }
1052
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001053 // Inform the target of the language options.
1054 //
1055 // FIXME: We shouldn't need to do this, the target should be immutable once
1056 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001057 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001058
Ted Kremenek03201fb2011-03-21 18:40:07 +00001059 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001060 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001061 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001062 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001063 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001064 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001065
Douglas Gregorabc563f2010-07-19 21:46:24 +00001066 // Configure the various subsystems.
1067 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001068 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001069 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001070 FileMgr = new FileManager(FileSystemOpts);
1071 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001072 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001073 Ctx = 0;
1074 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001075 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001076
1077 // Clear out old caches and data.
1078 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001079 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001080 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001081
Douglas Gregorf128fed2010-08-20 00:02:33 +00001082 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001083 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001084 TopLevelDeclsInPreamble.clear();
1085 }
1086
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001087 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001088 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001089
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001090 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001091 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001092
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001093 // If the main file has been overridden due to the use of a preamble,
1094 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001095 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +00001096 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1097 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001098 if (OverrideMainBuffer) {
1099 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1100 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1101 PreprocessorOpts.PrecompiledPreambleBytes.second
1102 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001103 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001104 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001105
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001106 // The stored diagnostic has the old source manager in it; update
1107 // the locations to refer into the new source manager. Since we've
1108 // been careful to make sure that the source manager's state
1109 // before and after are identical, so that we can reuse the source
1110 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001111 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001112
1113 // Keep track of the override buffer;
1114 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001115 }
1116
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001117 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001118 new TopLevelDeclTrackerAction(*this));
1119
1120 // Recover resources if we crash before exiting this method.
1121 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1122 ActCleanup(Act.get());
1123
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001124 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001125 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001126
1127 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001128 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001129 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1130 getSourceManager(), PreambleDiagnostics,
1131 StoredDiagnostics);
1132 }
1133
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001134 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001135
Ted Kremenek4f327862011-03-21 18:40:17 +00001136 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001137 TheSema.reset(Clang->takeSema());
1138 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +00001139 Ctx = &Clang->getASTContext();
1140 PP = &Clang->getPreprocessor();
1141 Clang->setSourceManager(0);
1142 Clang->setFileManager(0);
1143 Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001144 Reader = Clang->getModuleManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001146 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001147
Douglas Gregorabc563f2010-07-19 21:46:24 +00001148 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001149
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001150error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001151 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001152 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001153 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001154 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001155 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001156
Douglas Gregord54eb442010-10-12 16:25:54 +00001157 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001158 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001159 return true;
1160}
1161
Douglas Gregor44c181a2010-07-23 00:33:23 +00001162/// \brief Simple function to retrieve a path for a preamble precompiled header.
1163static std::string GetPreamblePCHPath() {
1164 // FIXME: This is lame; sys::Path should provide this function (in particular,
1165 // it should know how to find the temporary files dir).
1166 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001167 // FIXME: This is a hack so that we can override the preamble file during
1168 // crash-recovery testing, which is the only case where the preamble files
1169 // are not necessarily cleaned up.
1170 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1171 if (TmpFile)
1172 return TmpFile;
1173
Douglas Gregor44c181a2010-07-23 00:33:23 +00001174 std::string Error;
1175 const char *TmpDir = ::getenv("TMPDIR");
1176 if (!TmpDir)
1177 TmpDir = ::getenv("TEMP");
1178 if (!TmpDir)
1179 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001180#ifdef LLVM_ON_WIN32
1181 if (!TmpDir)
1182 TmpDir = ::getenv("USERPROFILE");
1183#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001184 if (!TmpDir)
1185 TmpDir = "/tmp";
1186 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001187 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001188 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001189 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001190 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001191 return std::string();
1192
Douglas Gregor44c181a2010-07-23 00:33:23 +00001193 return P.str();
1194}
1195
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001196/// \brief Compute the preamble for the main file, providing the source buffer
1197/// that corresponds to the main file along with a pair (bytes, start-of-line)
1198/// that describes the preamble.
1199std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001200ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1201 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001202 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001203 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001204 CreatedBuffer = false;
1205
Douglas Gregor44c181a2010-07-23 00:33:23 +00001206 // Try to determine if the main file has been remapped, either from the
1207 // command line (to another file) or directly through the compiler invocation
1208 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001209 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001210 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001211 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1212 // Check whether there is a file-file remapping of the main file
1213 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001214 M = PreprocessorOpts.remapped_file_begin(),
1215 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216 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. Try to load the resulting, remapped source.
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 }
1226
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001227 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001229 return std::make_pair((llvm::MemoryBuffer*)0,
1230 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001231 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001232 }
1233 }
1234 }
1235
1236 // Check whether there is a file-buffer remapping. It supercedes the
1237 // file-file remapping.
1238 for (PreprocessorOptions::remapped_file_buffer_iterator
1239 M = PreprocessorOpts.remapped_file_buffer_begin(),
1240 E = PreprocessorOpts.remapped_file_buffer_end();
1241 M != E;
1242 ++M) {
1243 llvm::sys::PathWithStatus MPath(M->first);
1244 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1245 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1246 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001247 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001248 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001249 CreatedBuffer = false;
1250 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 }
1254 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001255 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001256 }
1257
1258 // If the main source file was not remapped, load it now.
1259 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001260 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001262 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001263
1264 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001265 }
1266
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001267 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001268 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001269 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001270}
1271
Douglas Gregor754f3492010-07-24 00:38:13 +00001272static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001273 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001274 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001275 llvm::MemoryBuffer *Result
1276 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1277 memcpy(const_cast<char*>(Result->getBufferStart()),
1278 Old->getBufferStart(), Old->getBufferSize());
1279 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001280 ' ', NewSize - Old->getBufferSize() - 1);
1281 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001282
Douglas Gregor754f3492010-07-24 00:38:13 +00001283 return Result;
1284}
1285
Douglas Gregor175c4a92010-07-23 23:58:40 +00001286/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1287/// the source file.
1288///
1289/// This routine will compute the preamble of the main source file. If a
1290/// non-trivial preamble is found, it will precompile that preamble into a
1291/// precompiled header so that the precompiled preamble can be used to reduce
1292/// reparsing time. If a precompiled preamble has already been constructed,
1293/// this routine will determine if it is still valid and, if so, avoid
1294/// rebuilding the precompiled preamble.
1295///
Douglas Gregordf95a132010-08-09 20:45:32 +00001296/// \param AllowRebuild When true (the default), this routine is
1297/// allowed to rebuild the precompiled preamble if it is found to be
1298/// out-of-date.
1299///
1300/// \param MaxLines When non-zero, the maximum number of lines that
1301/// can occur within the preamble.
1302///
Douglas Gregor754f3492010-07-24 00:38:13 +00001303/// \returns If the precompiled preamble can be used, returns a newly-allocated
1304/// buffer that should be used in place of the main file when doing so.
1305/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001306llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001307 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001308 bool AllowRebuild,
1309 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001310
1311 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1312 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1313 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001314 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001315 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001316
1317 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001318 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001319 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001320
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001321 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001322 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001323 if (CreatedPreambleBuffer)
1324 OwnedPreambleBuffer.reset(NewPreamble.first);
1325
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001326 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001327 // We couldn't find a preamble in the main source. Clear out the current
1328 // preamble, if we have one. It's obviously no good any more.
1329 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001330 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001331
1332 // The next time we actually see a preamble, precompile it.
1333 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001334 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001335 }
1336
1337 if (!Preamble.empty()) {
1338 // We've previously computed a preamble. Check whether we have the same
1339 // preamble now that we did before, and that there's enough space in
1340 // the main-file buffer within the precompiled preamble to fit the
1341 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001342 if (Preamble.size() == NewPreamble.second.first &&
1343 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001344 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001345 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001346 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001347 // The preamble has not changed. We may be able to re-use the precompiled
1348 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001349
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001350 // Check that none of the files used by the preamble have changed.
1351 bool AnyFileChanged = false;
1352
1353 // First, make a record of those files that have been overridden via
1354 // remapping or unsaved_files.
1355 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1356 for (PreprocessorOptions::remapped_file_iterator
1357 R = PreprocessorOpts.remapped_file_begin(),
1358 REnd = PreprocessorOpts.remapped_file_end();
1359 !AnyFileChanged && R != REnd;
1360 ++R) {
1361 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001362 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001363 // If we can't stat the file we're remapping to, assume that something
1364 // horrible happened.
1365 AnyFileChanged = true;
1366 break;
1367 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001368
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001369 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1370 StatBuf.st_mtime);
1371 }
1372 for (PreprocessorOptions::remapped_file_buffer_iterator
1373 R = PreprocessorOpts.remapped_file_buffer_begin(),
1374 REnd = PreprocessorOpts.remapped_file_buffer_end();
1375 !AnyFileChanged && R != REnd;
1376 ++R) {
1377 // FIXME: Should we actually compare the contents of file->buffer
1378 // remappings?
1379 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1380 0);
1381 }
1382
1383 // Check whether anything has changed.
1384 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1385 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1386 !AnyFileChanged && F != FEnd;
1387 ++F) {
1388 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1389 = OverriddenFiles.find(F->first());
1390 if (Overridden != OverriddenFiles.end()) {
1391 // This file was remapped; check whether the newly-mapped file
1392 // matches up with the previous mapping.
1393 if (Overridden->second != F->second)
1394 AnyFileChanged = true;
1395 continue;
1396 }
1397
1398 // The file was not remapped; check whether it has changed on disk.
1399 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001400 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001401 // If we can't stat the file, assume that something horrible happened.
1402 AnyFileChanged = true;
1403 } else if (StatBuf.st_size != F->second.first ||
1404 StatBuf.st_mtime != F->second.second)
1405 AnyFileChanged = true;
1406 }
1407
1408 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001409 // Okay! We can re-use the precompiled preamble.
1410
1411 // Set the state of the diagnostic object to mimic its state
1412 // after parsing the preamble.
1413 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001414 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001415 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001416 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001417
1418 // Create a version of the main file buffer that is padded to
1419 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001420 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001421 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001422 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001423 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001424 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001425
1426 // If we aren't allowed to rebuild the precompiled preamble, just
1427 // return now.
1428 if (!AllowRebuild)
1429 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001430
Douglas Gregor175c4a92010-07-23 23:58:40 +00001431 // We can't reuse the previously-computed preamble. Build a new one.
1432 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001433 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001434 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001435 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001436 } else if (!AllowRebuild) {
1437 // We aren't allowed to rebuild the precompiled preamble; just
1438 // return now.
1439 return 0;
1440 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001441
1442 // If the preamble rebuild counter > 1, it's because we previously
1443 // failed to build a preamble and we're not yet ready to try
1444 // again. Decrement the counter and return a failure.
1445 if (PreambleRebuildCounter > 1) {
1446 --PreambleRebuildCounter;
1447 return 0;
1448 }
1449
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001450 // Create a temporary file for the precompiled preamble. In rare
1451 // circumstances, this can fail.
1452 std::string PreamblePCHPath = GetPreamblePCHPath();
1453 if (PreamblePCHPath.empty()) {
1454 // Try again next time.
1455 PreambleRebuildCounter = 1;
1456 return 0;
1457 }
1458
Douglas Gregor175c4a92010-07-23 23:58:40 +00001459 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001460 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001461 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001462
1463 // Create a new buffer that stores the preamble. The buffer also contains
1464 // extra space for the original contents of the file (which will be present
1465 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001466 // grows.
1467 PreambleReservedSize = NewPreamble.first->getBufferSize();
1468 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001469 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001470 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001471 PreambleReservedSize *= 2;
1472
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001473 // Save the preamble text for later; we'll need to compare against it for
1474 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001475 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001476 Preamble.assign(FileMgr->getFile(MainFilename),
1477 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001478 NewPreamble.first->getBufferStart()
1479 + NewPreamble.second.first);
1480 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1481
Douglas Gregor671947b2010-08-19 01:33:06 +00001482 delete PreambleBuffer;
1483 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001484 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001485 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001486 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001487 NewPreamble.first->getBufferStart(), Preamble.size());
1488 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001489 ' ', PreambleReservedSize - Preamble.size() - 1);
1490 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001491
1492 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001493 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001494 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1495
1496 // Tell the compiler invocation to generate a temporary precompiled header.
1497 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001498 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001499 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001500 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1501 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001502
1503 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001504 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001505
1506 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001507 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1508 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001509
Douglas Gregor01b6e312011-07-01 18:22:13 +00001510 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001511 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001512
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001513 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001514 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001515
1516 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001517 Clang->getTargetOpts().Features = TargetFeatures;
1518 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1519 Clang->getTargetOpts()));
1520 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001521 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1522 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001523 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001524 PreprocessorOpts.eraseRemappedFile(
1525 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001526 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001527 }
1528
1529 // Inform the target of the language options.
1530 //
1531 // FIXME: We shouldn't need to do this, the target should be immutable once
1532 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001533 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001534
Ted Kremenek03201fb2011-03-21 18:40:07 +00001535 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001536 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001537 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001538 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001539 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001540 "IR inputs not support here!");
1541
1542 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001543 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001544 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001545 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001546 TopLevelDecls.clear();
1547 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548
1549 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001550 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001551
1552 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001553 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001554 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001555
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001556 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001557 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001558 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001559 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1560 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001561 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001562 PreprocessorOpts.eraseRemappedFile(
1563 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001564 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001565 }
1566
1567 Act->Execute();
1568 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001569
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001570 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001571 // There were errors parsing the preamble, so no precompiled header was
1572 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001573 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001574 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1575 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001576 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001577 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001578 PreprocessorOpts.eraseRemappedFile(
1579 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001580 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001581 }
1582
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001583 // Transfer any diagnostics generated when parsing the preamble into the set
1584 // of preamble diagnostics.
1585 PreambleDiagnostics.clear();
1586 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001587 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001588 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001589
Douglas Gregor175c4a92010-07-23 23:58:40 +00001590 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001591 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001592 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001593
1594 // Keep track of all of the files that the source manager knows about,
1595 // so we can verify whether they have changed or not.
1596 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001597 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001598 const llvm::MemoryBuffer *MainFileBuffer
1599 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1600 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1601 FEnd = SourceMgr.fileinfo_end();
1602 F != FEnd;
1603 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001604 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001605 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1606 continue;
1607
1608 FilesInPreamble[File->getName()]
1609 = std::make_pair(F->second->getSize(), File->getModificationTime());
1610 }
1611
Douglas Gregoreababfb2010-08-04 05:53:38 +00001612 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001613 PreprocessorOpts.eraseRemappedFile(
1614 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001615
1616 // If the hash of top-level entities differs from the hash of the top-level
1617 // entities the last time we rebuilt the preamble, clear out the completion
1618 // cache.
1619 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1620 CompletionCacheTopLevelHashValue = 0;
1621 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1622 }
1623
Douglas Gregor754f3492010-07-24 00:38:13 +00001624 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001625 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001626 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001627}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001628
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001629void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1630 std::vector<Decl *> Resolved;
1631 Resolved.reserve(TopLevelDeclsInPreamble.size());
1632 ExternalASTSource &Source = *getASTContext().getExternalSource();
1633 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1634 // Resolve the declaration ID to an actual declaration, possibly
1635 // deserializing the declaration in the process.
1636 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1637 if (D)
1638 Resolved.push_back(D);
1639 }
1640 TopLevelDeclsInPreamble.clear();
1641 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1642}
1643
Chris Lattner5f9e2722011-07-23 10:55:15 +00001644StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001645 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001646}
1647
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001648ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001649 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1650 bool CaptureDiagnostics) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001651 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001652 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001653 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001654 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001655 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001656 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001657 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001658 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001659
1660 return AST.take();
1661}
1662
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001663ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001664 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001665 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001666 ASTUnit *Unit,
1667 bool Persistent,
1668 StringRef ResourceFilesPath,
1669 bool OnlyLocalDecls,
1670 bool CaptureDiagnostics,
1671 bool PrecompilePreamble,
1672 bool CacheCodeCompletionResults) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001673 assert(CI && "A CompilerInvocation is required");
1674
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001675 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001676 ASTUnit *AST = Unit;
1677 if (!AST) {
1678 // Create the AST unit.
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001679 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001680 AST = OwnAST.get();
1681 }
1682
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001683 if (!ResourceFilesPath.empty()) {
1684 // Override the resources path.
1685 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1686 }
1687 AST->OnlyLocalDecls = OnlyLocalDecls;
1688 AST->CaptureDiagnostics = CaptureDiagnostics;
1689 if (PrecompilePreamble)
1690 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001691 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001692 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001693
1694 // Recover resources if we crash before exiting this method.
1695 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001696 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001697 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1698 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001699 DiagCleanup(Diags.getPtr());
1700
1701 // We'll manage file buffers ourselves.
1702 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1703 CI->getFrontendOpts().DisableFree = false;
1704 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1705
1706 // Save the target features.
1707 AST->TargetFeatures = CI->getTargetOpts().Features;
1708
1709 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001710 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001711
1712 // Recover resources if we crash before exiting this method.
1713 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1714 CICleanup(Clang.get());
1715
1716 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001717 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001718
1719 // Set up diagnostics, capturing any diagnostics that would
1720 // otherwise be dropped.
1721 Clang->setDiagnostics(&AST->getDiagnostics());
1722
1723 // Create the target instance.
1724 Clang->getTargetOpts().Features = AST->TargetFeatures;
1725 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1726 Clang->getTargetOpts()));
1727 if (!Clang->hasTarget())
1728 return 0;
1729
1730 // Inform the target of the language options.
1731 //
1732 // FIXME: We shouldn't need to do this, the target should be immutable once
1733 // created. This complexity should be lifted elsewhere.
1734 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1735
1736 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1737 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001738 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001739 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001740 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001741 "IR inputs not supported here!");
1742
1743 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001744 AST->TheSema.reset();
1745 AST->Ctx = 0;
1746 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001747 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001748
1749 // Create a file manager object to provide access to and cache the filesystem.
1750 Clang->setFileManager(&AST->getFileManager());
1751
1752 // Create the source manager.
1753 Clang->setSourceManager(&AST->getSourceManager());
1754
1755 ASTFrontendAction *Act = Action;
1756
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001757 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758 if (!Act) {
1759 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1760 Act = TrackerAct.get();
1761 }
1762
1763 // Recover resources if we crash before exiting this method.
1764 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1765 ActCleanup(TrackerAct.get());
1766
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001767 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001768 return 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001769
1770 if (Persistent && !TrackerAct) {
1771 Clang->getPreprocessor().addPPCallbacks(
1772 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1773 std::vector<ASTConsumer*> Consumers;
1774 if (Clang->hasASTConsumer())
1775 Consumers.push_back(Clang->takeASTConsumer());
1776 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1777 AST->getCurrentTopLevelHashValue()));
1778 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1779 }
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001780 Act->Execute();
1781
1782 // Steal the created target, context, and preprocessor.
1783 AST->TheSema.reset(Clang->takeSema());
1784 AST->Consumer.reset(Clang->takeASTConsumer());
1785 AST->Ctx = &Clang->getASTContext();
1786 AST->PP = &Clang->getPreprocessor();
1787 Clang->setSourceManager(0);
1788 Clang->setFileManager(0);
1789 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001790 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001791
1792 Act->EndSourceFile();
1793
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001794 if (OwnAST)
1795 return OwnAST.take();
1796 else
1797 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001798}
1799
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001800bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1801 if (!Invocation)
1802 return true;
1803
1804 // We'll manage file buffers ourselves.
1805 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1806 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001807 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001808
Douglas Gregor1aa27302011-01-27 18:02:58 +00001809 // Save the target features.
1810 TargetFeatures = Invocation->getTargetOpts().Features;
1811
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001812 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001813 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001814 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001815 OverrideMainBuffer
1816 = getMainBufferWithPrecompiledPreamble(*Invocation);
1817 }
1818
Douglas Gregor213f18b2010-10-28 15:44:59 +00001819 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001820 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001821
Ted Kremenek25a11e12011-03-22 01:15:24 +00001822 // Recover resources if we crash before exiting this method.
1823 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1824 MemBufferCleanup(OverrideMainBuffer);
1825
Douglas Gregor213f18b2010-10-28 15:44:59 +00001826 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001827}
1828
Douglas Gregorabc563f2010-07-19 21:46:24 +00001829ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001830 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001831 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001832 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001833 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001834 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001835 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001836 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001837 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001838 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001839 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001840 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001841 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001842 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001843 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001844 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001845 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001846 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001847 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001848
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001849 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001850 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1851 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001852 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1853 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001854 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001855
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001856 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001857}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001858
1859ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1860 const char **ArgEnd,
David Blaikied6471f72011-09-25 23:23:43 +00001861 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001862 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001863 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001864 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001865 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001866 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001867 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001868 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001869 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001870 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001871 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001872 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001873 // No diagnostics engine was provided, so create our own diagnostics object
1874 // with the default options.
1875 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001876 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1877 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001878 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001879
Chris Lattner5f9e2722011-07-23 10:55:15 +00001880 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001881
Ted Kremenek4f327862011-03-21 18:40:17 +00001882 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001883
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001884 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001885
Douglas Gregore47be3e2010-11-11 00:39:14 +00001886 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001887 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001888
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001889 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001890 llvm::makeArrayRef(ArgBegin, ArgEnd),
1891 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001892 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001893 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001894 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001895
Douglas Gregor4db64a42010-01-23 00:14:00 +00001896 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001897 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1898 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1899 if (const llvm::MemoryBuffer *
1900 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1901 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1902 } else {
1903 const char *fname = fileOrBuf.get<const char *>();
1904 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1905 }
1906 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001907 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1908 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001909
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001910 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001911 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001912
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001913 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001914 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001915 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001916 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001917 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001918 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001919 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001920 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001921 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001922 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001923 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001924 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1925 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001926 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001927 AST->Invocation = CI;
Ted Kremenekd04a9822011-11-17 23:01:17 +00001928 CI = 0; // Zero out now to ease cleanup during crash recovery.
Chandler Carruthba7537f2011-07-14 09:02:10 +00001929 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001930
1931 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001932 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1933 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001934
Chris Lattner39b49bc2010-11-23 08:35:12 +00001935 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001936}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001937
1938bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001939 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001940 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001941
1942 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001943
Douglas Gregor213f18b2010-10-28 15:44:59 +00001944 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001945 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001946
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001947 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001948 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001949 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001950 for (PreprocessorOptions::remapped_file_buffer_iterator
1951 R = PPOpts.remapped_file_buffer_begin(),
1952 REnd = PPOpts.remapped_file_buffer_end();
1953 R != REnd;
1954 ++R) {
1955 delete R->second;
1956 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001957 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001958 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1959 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1960 if (const llvm::MemoryBuffer *
1961 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1962 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1963 memBuf);
1964 } else {
1965 const char *fname = fileOrBuf.get<const char *>();
1966 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1967 fname);
1968 }
1969 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001970
Douglas Gregoreababfb2010-08-04 05:53:38 +00001971 // If we have a preamble file lying around, or if we might try to
1972 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001973 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001974 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001975 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001976
Douglas Gregorabc563f2010-07-19 21:46:24 +00001977 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001978 getDiagnostics().Reset();
1979 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00001980 if (OverrideMainBuffer)
1981 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00001982
Douglas Gregor175c4a92010-07-23 23:58:40 +00001983 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001984 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00001985
1986 // If we're caching global code-completion results, and the top-level
1987 // declarations have changed, clear out the code-completion cache.
1988 if (!Result && ShouldCacheCodeCompletionResults &&
1989 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1990 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00001991
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001992 // We now need to clear out the completion allocator for
1993 // clang_getCursorCompletionString; it'll be recreated if necessary.
1994 CursorCompletionAllocator = 0;
1995
Douglas Gregor175c4a92010-07-23 23:58:40 +00001996 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001997}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001998
Douglas Gregor87c08a52010-08-13 22:48:40 +00001999//----------------------------------------------------------------------------//
2000// Code completion
2001//----------------------------------------------------------------------------//
2002
2003namespace {
2004 /// \brief Code completion consumer that combines the cached code-completion
2005 /// results from an ASTUnit with the code-completion results provided to it,
2006 /// then passes the result on to
2007 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00002008 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002009 ASTUnit &AST;
2010 CodeCompleteConsumer &Next;
2011
2012 public:
2013 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00002014 bool IncludeMacros, bool IncludeCodePatterns,
2015 bool IncludeGlobals)
2016 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00002017 Next.isOutputBinary()), AST(AST), Next(Next)
2018 {
2019 // Compute the set of contexts in which we will look when we don't have
2020 // any information about the specific context.
2021 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00002022 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2023 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2024 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2025 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2026 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2027 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2028 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2029 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2030 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2031 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2032 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2033 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2034 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002035
Douglas Gregor87c08a52010-08-13 22:48:40 +00002036 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002037 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2038 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2039 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002040 }
2041
2042 virtual void ProcessCodeCompleteResults(Sema &S,
2043 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002044 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002045 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002046
2047 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2048 OverloadCandidate *Candidates,
2049 unsigned NumCandidates) {
2050 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2051 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002052
Douglas Gregordae68752011-02-01 22:57:45 +00002053 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002054 return Next.getAllocator();
2055 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002056 };
2057}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002058
Douglas Gregor5f808c22010-08-16 21:18:39 +00002059/// \brief Helper function that computes which global names are hidden by the
2060/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002061static void CalculateHiddenNames(const CodeCompletionContext &Context,
2062 CodeCompletionResult *Results,
2063 unsigned NumResults,
2064 ASTContext &Ctx,
2065 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002066 bool OnlyTagNames = false;
2067 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002068 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002069 case CodeCompletionContext::CCC_TopLevel:
2070 case CodeCompletionContext::CCC_ObjCInterface:
2071 case CodeCompletionContext::CCC_ObjCImplementation:
2072 case CodeCompletionContext::CCC_ObjCIvarList:
2073 case CodeCompletionContext::CCC_ClassStructUnion:
2074 case CodeCompletionContext::CCC_Statement:
2075 case CodeCompletionContext::CCC_Expression:
2076 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002077 case CodeCompletionContext::CCC_DotMemberAccess:
2078 case CodeCompletionContext::CCC_ArrowMemberAccess:
2079 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002080 case CodeCompletionContext::CCC_Namespace:
2081 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002082 case CodeCompletionContext::CCC_Name:
2083 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002084 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002085 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002086 break;
2087
2088 case CodeCompletionContext::CCC_EnumTag:
2089 case CodeCompletionContext::CCC_UnionTag:
2090 case CodeCompletionContext::CCC_ClassOrStructTag:
2091 OnlyTagNames = true;
2092 break;
2093
2094 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002095 case CodeCompletionContext::CCC_MacroName:
2096 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002097 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002098 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002099 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002100 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002101 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002102 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002103 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002104 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2105 case CodeCompletionContext::CCC_ObjCClassMessage:
2106 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002107 // We're looking for nothing, or we're looking for names that cannot
2108 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002109 return;
2110 }
2111
John McCall0a2c5e22010-08-25 06:19:51 +00002112 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002113 for (unsigned I = 0; I != NumResults; ++I) {
2114 if (Results[I].Kind != Result::RK_Declaration)
2115 continue;
2116
2117 unsigned IDNS
2118 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2119
2120 bool Hiding = false;
2121 if (OnlyTagNames)
2122 Hiding = (IDNS & Decl::IDNS_Tag);
2123 else {
2124 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002125 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2126 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002127 if (Ctx.getLangOptions().CPlusPlus)
2128 HiddenIDNS |= Decl::IDNS_Tag;
2129 Hiding = (IDNS & HiddenIDNS);
2130 }
2131
2132 if (!Hiding)
2133 continue;
2134
2135 DeclarationName Name = Results[I].Declaration->getDeclName();
2136 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2137 HiddenNames.insert(Identifier->getName());
2138 else
2139 HiddenNames.insert(Name.getAsString());
2140 }
2141}
2142
2143
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002144void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2145 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002146 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002147 unsigned NumResults) {
2148 // Merge the results we were given with the results we cached.
2149 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002150 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002151 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002152 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002153 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002154 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002155 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002156 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002157 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002158 C = AST.cached_completion_begin(),
2159 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002160 C != CEnd; ++C) {
2161 // If the context we are in matches any of the contexts we are
2162 // interested in, we'll add this result.
2163 if ((C->ShowInContexts & InContexts) == 0)
2164 continue;
2165
2166 // If we haven't added any results previously, do so now.
2167 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002168 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2169 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002170 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2171 AddedResult = true;
2172 }
2173
Douglas Gregor5f808c22010-08-16 21:18:39 +00002174 // Determine whether this global completion result is hidden by a local
2175 // completion result. If so, skip it.
2176 if (C->Kind != CXCursor_MacroDefinition &&
2177 HiddenNames.count(C->Completion->getTypedText()))
2178 continue;
2179
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002180 // Adjust priority based on similar type classes.
2181 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002182 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002183 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002184 if (!Context.getPreferredType().isNull()) {
2185 if (C->Kind == CXCursor_MacroDefinition) {
2186 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002187 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002188 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002189 } else if (C->Type) {
2190 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002191 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002192 Context.getPreferredType().getUnqualifiedType());
2193 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2194 if (ExpectedSTC == C->TypeClass) {
2195 // We know this type is similar; check for an exact match.
2196 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002197 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002198 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002199 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002200 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2201 Priority /= CCF_ExactTypeMatch;
2202 else
2203 Priority /= CCF_SimilarTypeMatch;
2204 }
2205 }
2206 }
2207
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002208 // Adjust the completion string, if required.
2209 if (C->Kind == CXCursor_MacroDefinition &&
2210 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2211 // Create a new code-completion string that just contains the
2212 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002213 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2214 C->Availability);
2215 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002216 CursorKind = CXCursor_NotImplemented;
2217 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002218 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002219 }
2220
Douglas Gregor4125c372010-08-25 18:03:13 +00002221 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002222 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002223 }
2224
2225 // If we did not add any cached completion results, just forward the
2226 // results we were given to the next consumer.
2227 if (!AddedResult) {
2228 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2229 return;
2230 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002231
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002232 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2233 AllResults.size());
2234}
2235
2236
2237
Chris Lattner5f9e2722011-07-23 10:55:15 +00002238void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002239 RemappedFile *RemappedFiles,
2240 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002241 bool IncludeMacros,
2242 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002243 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002244 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002245 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002246 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2247 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002248 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002249 return;
2250
Douglas Gregor213f18b2010-10-28 15:44:59 +00002251 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002252 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002253 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002254
Ted Kremenek4f327862011-03-21 18:40:17 +00002255 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2256 CCInvocation(new CompilerInvocation(*Invocation));
2257
2258 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2259 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002260
Douglas Gregor87c08a52010-08-13 22:48:40 +00002261 FrontendOpts.ShowMacrosInCodeCompletion
2262 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002263 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002264 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2265 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002266 FrontendOpts.CodeCompletionAt.FileName = File;
2267 FrontendOpts.CodeCompletionAt.Line = Line;
2268 FrontendOpts.CodeCompletionAt.Column = Column;
2269
2270 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002271 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002272
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002273 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002274
2275 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002276 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2277 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002278
Ted Kremenek4f327862011-03-21 18:40:17 +00002279 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002280 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002281
2282 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002283 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002284 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002285 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002286 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002287 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002288
2289 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002290 Clang->getTargetOpts().Features = TargetFeatures;
2291 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2292 Clang->getTargetOpts()));
2293 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002294 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002295 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002296 }
2297
2298 // Inform the target of the language options.
2299 //
2300 // FIXME: We shouldn't need to do this, the target should be immutable once
2301 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002302 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002303
Ted Kremenek03201fb2011-03-21 18:40:07 +00002304 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002305 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002306 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002307 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002308 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002309 "IR inputs not support here!");
2310
2311
2312 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002313 Clang->setFileManager(&FileMgr);
2314 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002315
2316 // Remap files.
2317 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002318 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002319 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002320 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2321 if (const llvm::MemoryBuffer *
2322 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2323 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2324 OwnedBuffers.push_back(memBuf);
2325 } else {
2326 const char *fname = fileOrBuf.get<const char *>();
2327 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2328 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002329 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002330
Douglas Gregor87c08a52010-08-13 22:48:40 +00002331 // Use the code completion consumer we were given, but adding any cached
2332 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002333 AugmentedCodeCompleteConsumer *AugmentedConsumer
2334 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2335 FrontendOpts.ShowMacrosInCodeCompletion,
2336 FrontendOpts.ShowCodePatternsInCodeCompletion,
2337 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002338 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002339
Douglas Gregordf95a132010-08-09 20:45:32 +00002340 // If we have a precompiled preamble, try to use it. We only allow
2341 // the use of the precompiled preamble if we're if the completion
2342 // point is within the main file, after the end of the precompiled
2343 // preamble.
2344 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002345 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002346 using llvm::sys::FileStatus;
2347 llvm::sys::PathWithStatus CompleteFilePath(File);
2348 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2349 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2350 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002351 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2352 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002353 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002354 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002355 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002356 }
2357
2358 // If the main file has been overridden due to the use of a preamble,
2359 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002360 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002361 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002362 stored_diag_begin(),
2363 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002364 if (OverrideMainBuffer) {
2365 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2366 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2367 PreprocessorOpts.PrecompiledPreambleBytes.second
2368 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002369 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002370 PreprocessorOpts.DisablePCHValidation = true;
2371
Douglas Gregor2283d792010-08-20 00:59:43 +00002372 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002373 } else {
2374 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2375 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002376 }
2377
Douglas Gregordca8ee82011-05-06 16:33:08 +00002378 // Disable the preprocessing record
2379 PreprocessorOpts.DetailedRecord = false;
2380
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002381 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002383 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002384 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002385 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002386 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2387 getSourceManager(), PreambleDiagnostics,
2388 StoredDiagnostics);
2389 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390 Act->Execute();
2391 Act->EndSourceFile();
2392 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002393
2394 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002395}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002396
Chris Lattner5f9e2722011-07-23 10:55:15 +00002397CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002398 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002399 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002400
2401 // Write to a temporary file and later rename it to the actual file, to avoid
2402 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002403 llvm::SmallString<128> TempPath;
2404 TempPath = File;
2405 TempPath += "-%%%%%%%%";
2406 int fd;
2407 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2408 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002409 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002410
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002411 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2412 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002413 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002414
2415 serialize(Out);
2416 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002417 if (Out.has_error())
2418 return CXSaveError_Unknown;
2419
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002420 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002421 bool exists;
2422 llvm::sys::fs::remove(TempPath.str(), exists);
2423 return CXSaveError_Unknown;
2424 }
2425
2426 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002427}
2428
Chris Lattner5f9e2722011-07-23 10:55:15 +00002429bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002430 if (getDiagnostics().hasErrorOccurred())
2431 return true;
2432
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002433 std::vector<unsigned char> Buffer;
2434 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002435 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002436 // FIXME: Handle modules
Douglas Gregora8cc6ce2011-11-30 04:39:39 +00002437 Writer.WriteAST(getSema(), 0, std::string(), 0, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002438
2439 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002440 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002441 OS.write((char *)&Buffer.front(), Buffer.size());
2442
2443 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002444}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002445
2446typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2447
2448static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2449 unsigned Raw = L.getRawEncoding();
2450 const unsigned MacroBit = 1U << 31;
2451 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2452 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2453}
2454
2455void ASTUnit::TranslateStoredDiagnostics(
2456 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002457 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002458 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002459 const SmallVectorImpl<StoredDiagnostic> &Diags,
2460 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002461 // The stored diagnostic has the old source manager in it; update
2462 // the locations to refer into the new source manager. We also need to remap
2463 // all the locations to the new view. This includes the diag location, any
2464 // associated source ranges, and the source ranges of associated fix-its.
2465 // FIXME: There should be a cleaner way to do this.
2466
Chris Lattner5f9e2722011-07-23 10:55:15 +00002467 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002468 Result.reserve(Diags.size());
2469 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002470 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002471 assert(Mod && "Don't have preamble module");
2472 SLocRemap &Remap = Mod->SLocRemap;
2473 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2474 // Rebuild the StoredDiagnostic.
2475 const StoredDiagnostic &SD = Diags[I];
2476 SourceLocation L = SD.getLocation();
2477 TranslateSLoc(L, Remap);
2478 FullSourceLoc Loc(L, SrcMgr);
2479
Chris Lattner5f9e2722011-07-23 10:55:15 +00002480 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002481 Ranges.reserve(SD.range_size());
2482 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2483 E = SD.range_end();
2484 I != E; ++I) {
2485 SourceLocation BL = I->getBegin();
2486 TranslateSLoc(BL, Remap);
2487 SourceLocation EL = I->getEnd();
2488 TranslateSLoc(EL, Remap);
2489 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2490 }
2491
Chris Lattner5f9e2722011-07-23 10:55:15 +00002492 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002493 FixIts.reserve(SD.fixit_size());
2494 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2495 E = SD.fixit_end();
2496 I != E; ++I) {
2497 FixIts.push_back(FixItHint());
2498 FixItHint &FH = FixIts.back();
2499 FH.CodeToInsert = I->CodeToInsert;
2500 SourceLocation BL = I->RemoveRange.getBegin();
2501 TranslateSLoc(BL, Remap);
2502 SourceLocation EL = I->RemoveRange.getEnd();
2503 TranslateSLoc(EL, Remap);
2504 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2505 I->RemoveRange.isTokenRange());
2506 }
2507
2508 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2509 SD.getMessage(), Loc, Ranges, FixIts));
2510 }
2511 Result.swap(Out);
2512}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002513
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002514static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2515 std::pair<unsigned, Decl *> R) {
2516 return L.first < R.first;
2517}
2518
2519void ASTUnit::addFileLevelDecl(Decl *D) {
2520 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002521
2522 // We only care about local declarations.
2523 if (D->isFromASTFile())
2524 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002525
2526 SourceManager &SM = *SourceMgr;
2527 SourceLocation Loc = D->getLocation();
2528 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2529 return;
2530
2531 // We only keep track of the file-level declarations of each file.
2532 if (!D->getLexicalDeclContext()->isFileContext())
2533 return;
2534
2535 SourceLocation FileLoc = SM.getFileLoc(Loc);
2536 assert(SM.isLocalSourceLocation(FileLoc));
2537 FileID FID;
2538 unsigned Offset;
2539 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2540 if (FID.isInvalid())
2541 return;
2542
2543 LocDeclsTy *&Decls = FileDecls[FID];
2544 if (!Decls)
2545 Decls = new LocDeclsTy();
2546
2547 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2548
2549 if (Decls->empty() || Decls->back().first <= Offset) {
2550 Decls->push_back(LocDecl);
2551 return;
2552 }
2553
2554 LocDeclsTy::iterator
2555 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2556
2557 Decls->insert(I, LocDecl);
2558}
2559
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002560void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2561 SmallVectorImpl<Decl *> &Decls) {
2562 if (File.isInvalid())
2563 return;
2564
2565 if (SourceMgr->isLoadedFileID(File)) {
2566 assert(Ctx->getExternalSource() && "No external source!");
2567 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2568 Decls);
2569 }
2570
2571 FileDeclsTy::iterator I = FileDecls.find(File);
2572 if (I == FileDecls.end())
2573 return;
2574
2575 LocDeclsTy &LocDecls = *I->second;
2576 if (LocDecls.empty())
2577 return;
2578
2579 LocDeclsTy::iterator
2580 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2581 std::make_pair(Offset, (Decl*)0), compLocDecl);
2582 if (BeginIt != LocDecls.begin())
2583 --BeginIt;
2584
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002585 // If we are pointing at a top-level decl inside an objc container, we need
2586 // to backtrack until we find it otherwise we will fail to report that the
2587 // region overlaps with an objc container.
2588 while (BeginIt != LocDecls.begin() &&
2589 BeginIt->second->isTopLevelDeclInObjCContainer())
2590 --BeginIt;
2591
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002592 LocDeclsTy::iterator
2593 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2594 std::make_pair(Offset+Length, (Decl*)0),
2595 compLocDecl);
2596 if (EndIt != LocDecls.end())
2597 ++EndIt;
2598
2599 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2600 Decls.push_back(DIt->second);
2601}
2602
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002603SourceLocation ASTUnit::getLocation(const FileEntry *File,
2604 unsigned Line, unsigned Col) const {
2605 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002606 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002607 return SM.getMacroArgExpandedLocation(Loc);
2608}
2609
2610SourceLocation ASTUnit::getLocation(const FileEntry *File,
2611 unsigned Offset) const {
2612 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002613 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002614 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2615}
2616
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002617/// \brief If \arg Loc is a loaded location from the preamble, returns
2618/// the corresponding local location of the main file, otherwise it returns
2619/// \arg Loc.
2620SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2621 FileID PreambleID;
2622 if (SourceMgr)
2623 PreambleID = SourceMgr->getPreambleFileID();
2624
2625 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2626 return Loc;
2627
2628 unsigned Offs;
2629 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2630 SourceLocation FileLoc
2631 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2632 return FileLoc.getLocWithOffset(Offs);
2633 }
2634
2635 return Loc;
2636}
2637
2638/// \brief If \arg Loc is a local location of the main file but inside the
2639/// preamble chunk, returns the corresponding loaded location from the
2640/// preamble, otherwise it returns \arg Loc.
2641SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2642 FileID PreambleID;
2643 if (SourceMgr)
2644 PreambleID = SourceMgr->getPreambleFileID();
2645
2646 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2647 return Loc;
2648
2649 unsigned Offs;
2650 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2651 Offs < Preamble.size()) {
2652 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2653 return FileLoc.getLocWithOffset(Offs);
2654 }
2655
2656 return Loc;
2657}
2658
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002659bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2660 FileID FID;
2661 if (SourceMgr)
2662 FID = SourceMgr->getPreambleFileID();
2663
2664 if (Loc.isInvalid() || FID.isInvalid())
2665 return false;
2666
2667 return SourceMgr->isInFileID(Loc, FID);
2668}
2669
2670bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2671 FileID FID;
2672 if (SourceMgr)
2673 FID = SourceMgr->getMainFileID();
2674
2675 if (Loc.isInvalid() || FID.isInvalid())
2676 return false;
2677
2678 return SourceMgr->isInFileID(Loc, FID);
2679}
2680
2681SourceLocation ASTUnit::getEndOfPreambleFileID() {
2682 FileID FID;
2683 if (SourceMgr)
2684 FID = SourceMgr->getPreambleFileID();
2685
2686 if (FID.isInvalid())
2687 return SourceLocation();
2688
2689 return SourceMgr->getLocForEndOfFile(FID);
2690}
2691
2692SourceLocation ASTUnit::getStartOfMainFileID() {
2693 FileID FID;
2694 if (SourceMgr)
2695 FID = SourceMgr->getMainFileID();
2696
2697 if (FID.isInvalid())
2698 return SourceLocation();
2699
2700 return SourceMgr->getLocForStartOfFile(FID);
2701}
2702
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002703void ASTUnit::PreambleData::countLines() const {
2704 NumLines = 0;
2705 if (empty())
2706 return;
2707
2708 for (std::vector<char>::const_iterator
2709 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2710 if (*I == '\n')
2711 ++NumLines;
2712 }
2713 if (Buffer.back() != '\n')
2714 ++NumLines;
2715}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002716
2717#ifndef NDEBUG
2718ASTUnit::ConcurrencyState::ConcurrencyState() {
2719 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2720}
2721
2722ASTUnit::ConcurrencyState::~ConcurrencyState() {
2723 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2724}
2725
2726void ASTUnit::ConcurrencyState::start() {
2727 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2728 assert(acquired && "Concurrent access to ASTUnit!");
2729}
2730
2731void ASTUnit::ConcurrencyState::finish() {
2732 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2733}
2734
2735#else // NDEBUG
2736
2737ASTUnit::ConcurrencyState::ConcurrencyState() {}
2738ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2739void ASTUnit::ConcurrencyState::start() {}
2740void ASTUnit::ConcurrencyState::finish() {}
2741
2742#endif