blob: 563ed03588d2d449260b48deeb1ca03a34b69b65 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-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 Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000030#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000031#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000032#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000049#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000050#include "llvm/Support/MutexGuard.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000051#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000052#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000053#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000054#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000055using namespace clang;
56
Douglas Gregor16896c42010-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 Kramerf2e5a912010-11-09 20:00:56 +000065 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000066 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000068 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000069 }
70
Chris Lattner0e62c1c2011-07-23 10:55:15 +000071 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000072 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000073 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000074 }
75
Douglas Gregor16896c42010-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 Kremenek06b4f912011-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 Kremenekbd307a52011-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 Kremenek06b4f912011-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 Kremenekbd307a52011-10-27 19:44:25 +0000125 // No mutex required here since we are leaving the program.
Ted Kremenek06b4f912011-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 Kremenekbd307a52011-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 Kremenek06b4f912011-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 Kremenekbd307a52011-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 Kremenek06b4f912011-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 Kyrtzidise54568d2011-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 Kremenek06b4f912011-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 Gregor16896c42010-10-28 15:44:59 +0000201}
202
Douglas Gregorbb420ab2010-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 Gregor68dbaea2010-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 Gregor9aeaa4d2010-12-07 00:05:48 +0000212static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000213
Douglas Gregord03e8232010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000215 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000216 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000217 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000218 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000219 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000220 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis85b4a372011-11-29 18:18:33 +0000221 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000222 ShouldCacheCodeCompletionResults(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000223 CompletionCacheTopLevelHashValue(0),
224 PreambleTopLevelHashValue(0),
225 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000226 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000227 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000228 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000229 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
230 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000231}
Douglas Gregord03e8232010-04-05 21:10:19 +0000232
Daniel Dunbar764c0822009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000234 clearFileLevelDecls();
235
Ted Kremenek06b4f912011-10-27 17:55:18 +0000236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
238
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
242 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000243 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
245 for (PreprocessorOptions::remapped_file_buffer_iterator
246 FB = PPOpts.remapped_file_buffer_begin(),
247 FBEnd = PPOpts.remapped_file_buffer_end();
248 FB != FBEnd;
249 ++FB)
250 delete FB->second;
251 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000252
253 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000254 delete PreambleBuffer;
255
Douglas Gregor16896c42010-10-28 15:44:59 +0000256 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000257
258 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000259 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000260 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
261 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000262}
263
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000264void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
265
Douglas Gregor39982192010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
268static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor39982192010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
278 unsigned Contexts = 0;
279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
283 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
286 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000287 | (1 << (CodeCompletionContext::CCC_Type - 1))
288 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
292 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
297 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor2c595ad2011-07-30 06:55:39 +0000301 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
305 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
306
Douglas Gregor59cab552010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000308 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000310 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
311 if (Record->isUnion())
312 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
313 else
314 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
315
Douglas Gregor39982192010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
322 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
323 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000324 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000325 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
326 } else if (isa<ObjCProtocolDecl>(ND)) {
327 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
329 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor16896c42010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000353 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000354 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
355 getCodeCompletionTUInfo(), Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000356
357 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000358 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
359
Douglas Gregorb14904c2010-08-13 22:48:40 +0000360 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
361 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000362 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000363 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000364 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000365 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000366 *CachedCompletionAllocator,
367 getCodeCompletionTUInfo());
Douglas Gregor39982192010-08-15 06:18:01 +0000368 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000369 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000370 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000371 CachedResult.Priority = Results[I].Priority;
372 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000373 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000374
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000375 // Keep track of the type of this completion in an ASTContext-agnostic
376 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000377 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000378 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000379 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000380 CachedResult.Type = 0;
381 } else {
382 CanQualType CanUsageType
383 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
384 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
385
386 // Determine whether we have already seen this type. If so, we save
387 // ourselves the work of formatting the type string by using the
388 // temporary, CanQualType-based hash table to find the associated value.
389 unsigned &TypeValue = CompletionTypes[CanUsageType];
390 if (TypeValue == 0) {
391 TypeValue = CompletionTypes.size();
392 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
393 = TypeValue;
394 }
395
396 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000397 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000398
Douglas Gregor39982192010-08-15 06:18:01 +0000399 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000400
401 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000402 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000403 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
404 // The contexts in which a nested-name-specifier can appear in C++.
405 unsigned NNSContexts
406 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
407 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
408 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
409 | (1 << (CodeCompletionContext::CCC_Statement - 1))
410 | (1 << (CodeCompletionContext::CCC_Expression - 1))
411 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
412 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
413 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
414 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000415 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000416 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
417 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000418
419 if (isa<NamespaceDecl>(Results[I].Declaration) ||
420 isa<NamespaceAliasDecl>(Results[I].Declaration))
421 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
422
423 if (unsigned RemainingContexts
424 = NNSContexts & ~CachedResult.ShowInContexts) {
425 // If there any contexts where this completion can be a
426 // nested-name-specifier but isn't already an option, create a
427 // nested-name-specifier completion.
428 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000429 CachedResult.Completion
430 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000431 *CachedCompletionAllocator,
432 getCodeCompletionTUInfo());
Douglas Gregor59cab552010-08-16 23:05:20 +0000433 CachedResult.ShowInContexts = RemainingContexts;
434 CachedResult.Priority = CCP_NestedNameSpecifier;
435 CachedResult.TypeClass = STC_Void;
436 CachedResult.Type = 0;
437 CachedCompletionResults.push_back(CachedResult);
438 }
439 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000440 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000441 }
442
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 case Result::RK_Keyword:
444 case Result::RK_Pattern:
445 // Ignore keywords and patterns; we don't care, since they are so
446 // easily regenerated.
447 break;
448
449 case Result::RK_Macro: {
450 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000451 CachedResult.Completion
452 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000453 *CachedCompletionAllocator,
454 getCodeCompletionTUInfo());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000455 CachedResult.ShowInContexts
456 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
457 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
458 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
459 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
460 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
461 | (1 << (CodeCompletionContext::CCC_Statement - 1))
462 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000463 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000464 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000465 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000466 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
467 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000468
Douglas Gregorb14904c2010-08-13 22:48:40 +0000469 CachedResult.Priority = Results[I].Priority;
470 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000471 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000472 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000473 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000474 CachedCompletionResults.push_back(CachedResult);
475 break;
476 }
477 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000479
480 // Save the current top-level hash value.
481 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482}
483
484void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000485 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000486 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000487 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000488}
489
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000490namespace {
491
Sebastian Redl2c499f62010-08-18 23:56:43 +0000492/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000493/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000494class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000495 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000496 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497 LangOptions &LangOpt;
498 HeaderSearch &HSI;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000499 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000500 std::string &Predefines;
501 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000503 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregore8bbc122011-09-02 00:18:52 +0000505 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000507 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
508 HeaderSearch &HSI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000509 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor83297df2011-09-01 23:39:15 +0000510 std::string &Predefines,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000511 unsigned &Counter)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000512 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor83297df2011-09-01 23:39:15 +0000513 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000514 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000515
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000517 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000518 return false;
519
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 LangOpt = LangOpts;
Douglas Gregor83297df2011-09-01 23:39:15 +0000521
522 // Initialize the preprocessor.
523 PP.Initialize(*Target);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000524
525 // Initialize the ASTContext
526 Context.InitBuiltinTypes(*Target);
527
528 InitializedLanguage = true;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000529 return false;
530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000532 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000533 // If we've already initialized the target, don't do it again.
534 if (Target)
535 return false;
536
537 // FIXME: This is broken, we should store the TargetOptions in the AST file.
538 TargetOptions TargetOpts;
539 TargetOpts.ABI = "";
540 TargetOpts.CXXABI = "";
541 TargetOpts.CPU = "";
542 TargetOpts.Features.clear();
543 TargetOpts.Triple = Triple;
544 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000545 return false;
546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Sebastian Redl8b41f302010-07-14 23:29:55 +0000548 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000549 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000550 std::string &SuggestedPredefines,
551 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000552 Predefines = Buffers[0].Data;
553 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
554 Predefines += Buffers[I].Data;
555 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000556 return false;
557 }
Mike Stump11289f42009-09-09 15:08:12 +0000558
Douglas Gregora2f49452010-03-16 19:09:18 +0000559 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000560 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
561 }
Mike Stump11289f42009-09-09 15:08:12 +0000562
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000563 virtual void ReadCounter(unsigned Value) {
564 Counter = Value;
565 }
566};
567
David Blaikief18d91a2011-09-26 00:01:39 +0000568class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000569 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000570
571public:
David Blaikief18d91a2011-09-26 00:01:39 +0000572 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000573 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000574 : StoredDiags(StoredDiags) { }
575
David Blaikie9c902b52011-09-25 23:23:43 +0000576 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000577 const Diagnostic &Info);
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000578
579 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
580 // Just drop any diagnostics that come from cloned consumers; they'll
581 // have different source managers anyway.
Douglas Gregore1fbde52012-01-29 19:57:03 +0000582 // FIXME: We'd like to be able to capture these somehow, even if it's just
583 // file/line/column, because they could occur when parsing module maps or
584 // building modules on-demand.
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000585 return new IgnoringDiagConsumer();
586 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000587};
588
589/// \brief RAII object that optionally captures diagnostics, if
590/// there is no diagnostic client to capture them already.
591class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000592 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000593 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000594 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595
596public:
David Blaikie9c902b52011-09-25 23:23:43 +0000597 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000598 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000599 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000600 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000601 if (RequestCapture || Diags.getClient() == 0) {
602 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000604 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000605 }
606
607 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000608 if (Diags.getClient() == &Client) {
609 Diags.takeClient();
610 Diags.setClient(PreviousClient);
611 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000612 }
613};
614
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000615} // anonymous namespace
616
David Blaikief18d91a2011-09-26 00:01:39 +0000617void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000618 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000619 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000620 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000621
Douglas Gregor33cdd812010-02-18 18:08:43 +0000622 StoredDiags.push_back(StoredDiagnostic(Level, Info));
623}
624
Steve Naroffc0683b92009-09-03 18:19:54 +0000625const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000626 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000627}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000628
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000629llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000630 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000631 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000632 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000633}
634
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000635/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000636void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000637 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000638 ASTUnit &AST, bool CaptureDiagnostics) {
639 if (!Diags.getPtr()) {
640 // No diagnostics engine was provided, so create our own diagnostics object
641 // with the default options.
642 DiagnosticOptions DiagOpts;
David Blaikiee2eefae2011-09-25 23:39:51 +0000643 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000644 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000645 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000646 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
647 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000648 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000650 }
651}
652
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000653ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000655 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000656 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000657 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000658 unsigned NumRemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000659 bool CaptureDiagnostics,
660 bool AllowPCHWithCompilerErrors) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000661 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000662
663 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000664 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
665 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000666 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
667 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000668 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000669
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000670 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000671
Douglas Gregor16bef852009-10-16 20:01:17 +0000672 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000673 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000674 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000675 AST->FileMgr = new FileManager(FileSystemOpts);
676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
677 AST->getFileManager());
Douglas Gregor197ac202011-11-11 00:35:06 +0000678 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000679 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000680 AST->ASTFileLangOpts,
681 /*Target=*/0));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000682
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000683 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000684 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
685 if (const llvm::MemoryBuffer *
686 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
687 // Create the file entry for the file that we're mapping from.
688 const FileEntry *FromFile
689 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
690 memBuf->getBufferSize(),
691 0);
692 if (!FromFile) {
693 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
694 << RemappedFiles[I].first;
695 delete memBuf;
696 continue;
697 }
698
699 // Override the contents of the "from" file with the contents of
700 // the "to" file.
701 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
702
703 } else {
704 const char *fname = fileOrBuf.get<const char *>();
705 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
706 if (!ToFile) {
707 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
708 << RemappedFiles[I].first << fname;
709 continue;
710 }
711
712 // Create the file entry for the file that we're mapping from.
713 const FileEntry *FromFile
714 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
715 ToFile->getSize(),
716 0);
717 if (!FromFile) {
718 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
719 << RemappedFiles[I].first;
720 delete memBuf;
721 continue;
722 }
723
724 // Override the contents of the "from" file with the contents of
725 // the "to" file.
726 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000727 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000728 }
729
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000730 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000731
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000732 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000733 std::string Predefines;
734 unsigned Counter;
735
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000736 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000737
Douglas Gregor83297df2011-09-01 23:39:15 +0000738 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
739 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
740 *AST,
741 /*IILookup=*/0,
742 /*OwnsHeaderSearch=*/false,
743 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000744 Preprocessor &PP = *AST->PP;
745
746 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
747 AST->getSourceManager(),
748 /*Target=*/0,
749 PP.getIdentifierTable(),
750 PP.getSelectorTable(),
751 PP.getBuiltinInfo(),
752 /* size_reserve = */0,
753 /*DelayInitialization=*/true);
754 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000755
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000756 Reader.reset(new ASTReader(PP, Context,
757 /*isysroot=*/"",
758 /*DisableValidation=*/false,
759 /*DisableStatCache=*/false,
760 AllowPCHWithCompilerErrors));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000761
762 // Recover resources if we crash before exiting this method.
763 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
764 ReaderCleanup(Reader.get());
765
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor83297df2011-09-01 23:39:15 +0000767 AST->ASTFileLangOpts, HeaderInfo,
768 AST->Target, Predefines, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000769
Douglas Gregora6895d82011-07-22 16:00:58 +0000770 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000771 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000772 break;
Mike Stump11289f42009-09-09 15:08:12 +0000773
Sebastian Redl2c499f62010-08-18 23:56:43 +0000774 case ASTReader::Failure:
775 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000776 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000777 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
Daniel Dunbara8a50932009-12-02 08:44:16 +0000780 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
781
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000782 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000783 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000784
Sebastian Redl2c499f62010-08-18 23:56:43 +0000785 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000786 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000787 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000788 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000789 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000790
791 // Unregister the cleanup for ASTReader. It will get cleaned up
792 // by the ASTUnit cleanup.
793 ReaderCleanup.unregister();
794
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000795 Context.setExternalSource(Source);
796
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000797 // Create an AST consumer, even though it isn't used.
798 AST->Consumer.reset(new ASTConsumer);
799
Sebastian Redl2c499f62010-08-18 23:56:43 +0000800 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000801 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
802 AST->TheSema->Initialize();
803 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +0000804 AST->Reader = ReaderPtr;
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000805
Mike Stump11289f42009-09-09 15:08:12 +0000806 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000807}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000808
809namespace {
810
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000811/// \brief Preprocessor callback class that updates a hash value with the names
812/// of all macros that have been defined by the translation unit.
813class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
814 unsigned &Hash;
815
816public:
817 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
818
819 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
820 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
821 }
822};
823
824/// \brief Add the given declaration to the hash of all top-level entities.
825void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
826 if (!D)
827 return;
828
829 DeclContext *DC = D->getDeclContext();
830 if (!DC)
831 return;
832
833 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
834 return;
835
836 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
837 if (ND->getIdentifier())
838 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
839 else if (DeclarationName Name = ND->getDeclName()) {
840 std::string NameStr = Name.getAsString();
841 Hash = llvm::HashString(NameStr, Hash);
842 }
843 return;
Douglas Gregorf6102672012-01-01 21:23:57 +0000844 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000845}
846
Daniel Dunbar644dca02009-12-04 08:17:33 +0000847class TopLevelDeclTrackerConsumer : public ASTConsumer {
848 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000849 unsigned &Hash;
850
Daniel Dunbar644dca02009-12-04 08:17:33 +0000851public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
853 : Unit(_Unit), Hash(Hash) {
854 Hash = 0;
855 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000856
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000857 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000858 if (!D)
859 return;
860
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000861 // FIXME: Currently ObjC method declarations are incorrectly being
862 // reported as top-level declarations, even though their DeclContext
863 // is the containing ObjC @interface/@implementation. This is a
864 // fundamental problem in the parser right now.
865 if (isa<ObjCMethodDecl>(D))
866 return;
867
868 AddTopLevelDeclarationToHash(D, Hash);
869 Unit.addTopLevelDecl(D);
870
871 handleFileLevelDecl(D);
872 }
873
874 void handleFileLevelDecl(Decl *D) {
875 Unit.addFileLevelDecl(D);
876 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
877 for (NamespaceDecl::decl_iterator
878 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
879 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000880 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000881 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000882
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000883 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000884 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
885 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000886 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000887 }
888
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000889 // We're not interested in "interesting" decls.
890 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000891
892 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
893 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
894 handleTopLevelDecl(*it);
895 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000896};
897
898class TopLevelDeclTrackerAction : public ASTFrontendAction {
899public:
900 ASTUnit &Unit;
901
Daniel Dunbar764c0822009-12-01 09:51:01 +0000902 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000903 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000904 CI.getPreprocessor().addPPCallbacks(
905 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
906 return new TopLevelDeclTrackerConsumer(Unit,
907 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000908 }
909
910public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000911 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
912
Daniel Dunbar764c0822009-12-01 09:51:01 +0000913 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000914 virtual TranslationUnitKind getTranslationUnitKind() {
915 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000916 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000917};
918
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000919class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000920 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000921 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000922 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000923
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000924public:
Douglas Gregor36db4f92011-08-25 22:35:51 +0000925 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000926 StringRef isysroot, raw_ostream *Out)
Douglas Gregorf7a700fd2011-11-30 04:39:39 +0000927 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000928 Hash(Unit.getCurrentTopLevelHashValue()) {
929 Hash = 0;
930 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000931
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000932 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000933 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
934 Decl *D = *it;
935 // FIXME: Currently ObjC method declarations are incorrectly being
936 // reported as top-level declarations, even though their DeclContext
937 // is the containing ObjC @interface/@implementation. This is a
938 // fundamental problem in the parser right now.
939 if (isa<ObjCMethodDecl>(D))
940 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000941 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000942 TopLevelDecls.push_back(D);
943 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000944 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000945 }
946
947 virtual void HandleTranslationUnit(ASTContext &Ctx) {
948 PCHGenerator::HandleTranslationUnit(Ctx);
949 if (!Unit.getDiagnostics().hasErrorOccurred()) {
950 // Translate the top-level declarations we captured during
951 // parsing into declaration IDs in the precompiled
952 // preamble. This will allow us to deserialize those top-level
953 // declarations when requested.
954 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
955 Unit.addTopLevelDeclFromPreamble(
956 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000957 }
958 }
959};
960
961class PrecompilePreambleAction : public ASTFrontendAction {
962 ASTUnit &Unit;
963
964public:
965 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
966
967 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000968 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000969 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000970 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000971 raw_ostream *OS = 0;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000972 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
973 OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000974 OS))
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000975 return 0;
976
Douglas Gregorc567ba22011-07-22 16:35:34 +0000977 if (!CI.getFrontendOpts().RelocatablePCH)
978 Sysroot.clear();
979
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000980 CI.getPreprocessor().addPPCallbacks(
981 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor36db4f92011-08-25 22:35:51 +0000982 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
983 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000984 }
985
986 virtual bool hasCodeCompletionSupport() const { return false; }
987 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000988 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000989};
990
Daniel Dunbar764c0822009-12-01 09:51:01 +0000991}
992
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000993static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
994 StoredDiagnostics) {
995 // Get rid of stored diagnostics except the ones from the driver which do not
996 // have a source location.
997 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
998 if (StoredDiagnostics[I].getLocation().isValid()) {
999 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1000 --I;
1001 }
1002 }
1003}
1004
1005static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1006 StoredDiagnostics,
1007 SourceManager &SM) {
1008 // The stored diagnostic has the old source manager in it; update
1009 // the locations to refer into the new source manager. Since we've
1010 // been careful to make sure that the source manager's state
1011 // before and after are identical, so that we can reuse the source
1012 // location itself.
1013 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1014 if (StoredDiagnostics[I].getLocation().isValid()) {
1015 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1016 StoredDiagnostics[I].setLocation(Loc);
1017 }
1018 }
1019}
1020
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001021/// Parse the source file into a translation unit using the given compiler
1022/// invocation, replacing the current translation unit.
1023///
1024/// \returns True if a failure occurred that causes the ASTUnit not to
1025/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001026bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001027 delete SavedMainFileBuffer;
1028 SavedMainFileBuffer = 0;
1029
Ted Kremenek5e14d392011-03-21 18:40:17 +00001030 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001031 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001032 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001033 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001034
Daniel Dunbar764c0822009-12-01 09:51:01 +00001035 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001036 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001037
1038 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001039 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1040 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001041
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001042 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001043 CCInvocation(new CompilerInvocation(*Invocation));
1044
1045 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor32fbe312012-01-20 16:28:04 +00001046 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001047
Douglas Gregor8e984da2010-08-04 16:47:14 +00001048 // Set up diagnostics, capturing any diagnostics that would
1049 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001050 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001051
Daniel Dunbar764c0822009-12-01 09:51:01 +00001052 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001053 Clang->getTargetOpts().Features = TargetFeatures;
1054 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001055 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001056 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001057 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001058 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001059 }
1060
Daniel Dunbar764c0822009-12-01 09:51:01 +00001061 // Inform the target of the language options.
1062 //
1063 // FIXME: We shouldn't need to do this, the target should be immutable once
1064 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001065 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001066
Ted Kremenek84de4a12011-03-21 18:40:07 +00001067 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001068 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001069 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001070 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001071 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001072 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001073
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001074 // Configure the various subsystems.
1075 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001076 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001077 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001078 FileMgr = new FileManager(FileSystemOpts);
1079 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001080 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001081 Ctx = 0;
1082 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001083 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001084
1085 // Clear out old caches and data.
1086 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001087 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001088 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001089
Douglas Gregor7b02b582010-08-20 00:02:33 +00001090 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001091 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001092 TopLevelDeclsInPreamble.clear();
1093 }
1094
Daniel Dunbar764c0822009-12-01 09:51:01 +00001095 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001096 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001097
Daniel Dunbar764c0822009-12-01 09:51:01 +00001098 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001100
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001101 // If the main file has been overridden due to the use of a preamble,
1102 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001104 if (OverrideMainBuffer) {
1105 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1106 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1107 PreprocessorOpts.PrecompiledPreambleBytes.second
1108 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001109 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001110 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001111
Douglas Gregord9a30af2010-08-02 20:51:39 +00001112 // The stored diagnostic has the old source manager in it; update
1113 // the locations to refer into the new source manager. Since we've
1114 // been careful to make sure that the source manager's state
1115 // before and after are identical, so that we can reuse the source
1116 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001117 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001118
1119 // Keep track of the override buffer;
1120 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001121 }
1122
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001123 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001124 new TopLevelDeclTrackerAction(*this));
1125
1126 // Recover resources if we crash before exiting this method.
1127 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1128 ActCleanup(Act.get());
1129
Douglas Gregor32fbe312012-01-20 16:28:04 +00001130 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001131 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001132
1133 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001134 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001135 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1136 getSourceManager(), PreambleDiagnostics,
1137 StoredDiagnostics);
1138 }
1139
Daniel Dunbar644dca02009-12-04 08:17:33 +00001140 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001141
Ted Kremenek5e14d392011-03-21 18:40:17 +00001142 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001143 TheSema.reset(Clang->takeSema());
1144 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +00001145 Ctx = &Clang->getASTContext();
1146 PP = &Clang->getPreprocessor();
1147 Clang->setSourceManager(0);
1148 Clang->setFileManager(0);
1149 Target = &Clang->getTarget();
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001150 Reader = Clang->getModuleManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001151
Daniel Dunbar644dca02009-12-04 08:17:33 +00001152 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001153
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001154 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001155
Daniel Dunbar764c0822009-12-01 09:51:01 +00001156error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001157 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001158 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001159 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001160 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001161 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001162
Douglas Gregorefc46952010-10-12 16:25:54 +00001163 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001164 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001165 return true;
1166}
1167
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001168/// \brief Simple function to retrieve a path for a preamble precompiled header.
1169static std::string GetPreamblePCHPath() {
1170 // FIXME: This is lame; sys::Path should provide this function (in particular,
1171 // it should know how to find the temporary files dir).
1172 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001173 // FIXME: This is a hack so that we can override the preamble file during
1174 // crash-recovery testing, which is the only case where the preamble files
1175 // are not necessarily cleaned up.
1176 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1177 if (TmpFile)
1178 return TmpFile;
1179
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001180 std::string Error;
1181 const char *TmpDir = ::getenv("TMPDIR");
1182 if (!TmpDir)
1183 TmpDir = ::getenv("TEMP");
1184 if (!TmpDir)
1185 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001186#ifdef LLVM_ON_WIN32
1187 if (!TmpDir)
1188 TmpDir = ::getenv("USERPROFILE");
1189#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001190 if (!TmpDir)
1191 TmpDir = "/tmp";
1192 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001193 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001194 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001195 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001196 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001197 return std::string();
1198
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001199 return P.str();
1200}
1201
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001202/// \brief Compute the preamble for the main file, providing the source buffer
1203/// that corresponds to the main file along with a pair (bytes, start-of-line)
1204/// that describes the preamble.
1205std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001206ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1207 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001208 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001209 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210 CreatedBuffer = false;
1211
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 // Try to determine if the main file has been remapped, either from the
1213 // command line (to another file) or directly through the compiler invocation
1214 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001215 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor32fbe312012-01-20 16:28:04 +00001216 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001217 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1218 // Check whether there is a file-file remapping of the main file
1219 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001220 M = PreprocessorOpts.remapped_file_begin(),
1221 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001222 M != E;
1223 ++M) {
1224 llvm::sys::PathWithStatus MPath(M->first);
1225 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1226 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1227 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001228 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001229 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001230 CreatedBuffer = false;
1231 }
1232
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001233 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001234 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001235 return std::make_pair((llvm::MemoryBuffer*)0,
1236 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001237 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238 }
1239 }
1240 }
1241
1242 // Check whether there is a file-buffer remapping. It supercedes the
1243 // file-file remapping.
1244 for (PreprocessorOptions::remapped_file_buffer_iterator
1245 M = PreprocessorOpts.remapped_file_buffer_begin(),
1246 E = PreprocessorOpts.remapped_file_buffer_end();
1247 M != E;
1248 ++M) {
1249 llvm::sys::PathWithStatus MPath(M->first);
1250 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1251 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1252 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001253 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001254 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001255 CreatedBuffer = false;
1256 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001257
Douglas Gregor4dde7492010-07-23 23:58:40 +00001258 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001259 }
1260 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001261 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001262 }
1263
1264 // If the main source file was not remapped, load it now.
1265 if (!Buffer) {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001266 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001267 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001268 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001269
1270 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001271 }
1272
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001273 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001274 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001275 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001276}
1277
Douglas Gregor6481ef12010-07-24 00:38:13 +00001278static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001279 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001280 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001281 llvm::MemoryBuffer *Result
1282 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1283 memcpy(const_cast<char*>(Result->getBufferStart()),
1284 Old->getBufferStart(), Old->getBufferSize());
1285 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001286 ' ', NewSize - Old->getBufferSize() - 1);
1287 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001288
Douglas Gregor6481ef12010-07-24 00:38:13 +00001289 return Result;
1290}
1291
Douglas Gregor4dde7492010-07-23 23:58:40 +00001292/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1293/// the source file.
1294///
1295/// This routine will compute the preamble of the main source file. If a
1296/// non-trivial preamble is found, it will precompile that preamble into a
1297/// precompiled header so that the precompiled preamble can be used to reduce
1298/// reparsing time. If a precompiled preamble has already been constructed,
1299/// this routine will determine if it is still valid and, if so, avoid
1300/// rebuilding the precompiled preamble.
1301///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001302/// \param AllowRebuild When true (the default), this routine is
1303/// allowed to rebuild the precompiled preamble if it is found to be
1304/// out-of-date.
1305///
1306/// \param MaxLines When non-zero, the maximum number of lines that
1307/// can occur within the preamble.
1308///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001309/// \returns If the precompiled preamble can be used, returns a newly-allocated
1310/// buffer that should be used in place of the main file when doing so.
1311/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001312llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001313 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001314 bool AllowRebuild,
1315 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001316
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001317 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001318 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1319 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001320 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001321 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001322
1323 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001324 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001325 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001326
Douglas Gregor925296b2011-07-19 16:10:42 +00001327 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001328 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001329 if (CreatedPreambleBuffer)
1330 OwnedPreambleBuffer.reset(NewPreamble.first);
1331
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001332 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001333 // We couldn't find a preamble in the main source. Clear out the current
1334 // preamble, if we have one. It's obviously no good any more.
1335 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001336 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001337
1338 // The next time we actually see a preamble, precompile it.
1339 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001340 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001341 }
1342
1343 if (!Preamble.empty()) {
1344 // We've previously computed a preamble. Check whether we have the same
1345 // preamble now that we did before, and that there's enough space in
1346 // the main-file buffer within the precompiled preamble to fit the
1347 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001348 if (Preamble.size() == NewPreamble.second.first &&
1349 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001350 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001351 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001352 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001353 // The preamble has not changed. We may be able to re-use the precompiled
1354 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001355
Douglas Gregor0e119552010-07-31 00:40:00 +00001356 // Check that none of the files used by the preamble have changed.
1357 bool AnyFileChanged = false;
1358
1359 // First, make a record of those files that have been overridden via
1360 // remapping or unsaved_files.
1361 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1362 for (PreprocessorOptions::remapped_file_iterator
1363 R = PreprocessorOpts.remapped_file_begin(),
1364 REnd = PreprocessorOpts.remapped_file_end();
1365 !AnyFileChanged && R != REnd;
1366 ++R) {
1367 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001368 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001369 // If we can't stat the file we're remapping to, assume that something
1370 // horrible happened.
1371 AnyFileChanged = true;
1372 break;
1373 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001374
Douglas Gregor0e119552010-07-31 00:40:00 +00001375 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1376 StatBuf.st_mtime);
1377 }
1378 for (PreprocessorOptions::remapped_file_buffer_iterator
1379 R = PreprocessorOpts.remapped_file_buffer_begin(),
1380 REnd = PreprocessorOpts.remapped_file_buffer_end();
1381 !AnyFileChanged && R != REnd;
1382 ++R) {
1383 // FIXME: Should we actually compare the contents of file->buffer
1384 // remappings?
1385 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1386 0);
1387 }
1388
1389 // Check whether anything has changed.
1390 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1391 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1392 !AnyFileChanged && F != FEnd;
1393 ++F) {
1394 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1395 = OverriddenFiles.find(F->first());
1396 if (Overridden != OverriddenFiles.end()) {
1397 // This file was remapped; check whether the newly-mapped file
1398 // matches up with the previous mapping.
1399 if (Overridden->second != F->second)
1400 AnyFileChanged = true;
1401 continue;
1402 }
1403
1404 // The file was not remapped; check whether it has changed on disk.
1405 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001406 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001407 // If we can't stat the file, assume that something horrible happened.
1408 AnyFileChanged = true;
1409 } else if (StatBuf.st_size != F->second.first ||
1410 StatBuf.st_mtime != F->second.second)
1411 AnyFileChanged = true;
1412 }
1413
1414 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001415 // Okay! We can re-use the precompiled preamble.
1416
1417 // Set the state of the diagnostic object to mimic its state
1418 // after parsing the preamble.
1419 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001420 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001421 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001422 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001423
1424 // Create a version of the main file buffer that is padded to
1425 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001426 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001427 PreambleReservedSize,
Douglas Gregor32fbe312012-01-20 16:28:04 +00001428 FrontendOpts.Inputs[0].File);
Douglas Gregor0e119552010-07-31 00:40:00 +00001429 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001430 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001431
1432 // If we aren't allowed to rebuild the precompiled preamble, just
1433 // return now.
1434 if (!AllowRebuild)
1435 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001436
Douglas Gregor4dde7492010-07-23 23:58:40 +00001437 // We can't reuse the previously-computed preamble. Build a new one.
1438 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001439 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001440 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001441 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001442 } else if (!AllowRebuild) {
1443 // We aren't allowed to rebuild the precompiled preamble; just
1444 // return now.
1445 return 0;
1446 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001447
1448 // If the preamble rebuild counter > 1, it's because we previously
1449 // failed to build a preamble and we're not yet ready to try
1450 // again. Decrement the counter and return a failure.
1451 if (PreambleRebuildCounter > 1) {
1452 --PreambleRebuildCounter;
1453 return 0;
1454 }
1455
Douglas Gregore10f0e52010-09-11 17:56:52 +00001456 // Create a temporary file for the precompiled preamble. In rare
1457 // circumstances, this can fail.
1458 std::string PreamblePCHPath = GetPreamblePCHPath();
1459 if (PreamblePCHPath.empty()) {
1460 // Try again next time.
1461 PreambleRebuildCounter = 1;
1462 return 0;
1463 }
1464
Douglas Gregor4dde7492010-07-23 23:58:40 +00001465 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001466 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001467 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001468
1469 // Create a new buffer that stores the preamble. The buffer also contains
1470 // extra space for the original contents of the file (which will be present
1471 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001472 // grows.
1473 PreambleReservedSize = NewPreamble.first->getBufferSize();
1474 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001475 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001476 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001477 PreambleReservedSize *= 2;
1478
Douglas Gregord9a30af2010-08-02 20:51:39 +00001479 // Save the preamble text for later; we'll need to compare against it for
1480 // subsequent reparses.
Douglas Gregor32fbe312012-01-20 16:28:04 +00001481 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001482 Preamble.assign(FileMgr->getFile(MainFilename),
1483 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001484 NewPreamble.first->getBufferStart()
1485 + NewPreamble.second.first);
1486 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1487
Douglas Gregora0734c52010-08-19 01:33:06 +00001488 delete PreambleBuffer;
1489 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001490 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor32fbe312012-01-20 16:28:04 +00001491 FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001492 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001493 NewPreamble.first->getBufferStart(), Preamble.size());
1494 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001495 ' ', PreambleReservedSize - Preamble.size() - 1);
1496 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001497
1498 // Remap the main source file to the preamble buffer.
Douglas Gregor32fbe312012-01-20 16:28:04 +00001499 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001500 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1501
1502 // Tell the compiler invocation to generate a temporary precompiled header.
1503 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001504 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001505 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001506 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1507 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001508
1509 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001510 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001511
1512 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001513 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1514 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001515
Douglas Gregor3cc15812011-07-01 18:22:13 +00001516 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor32fbe312012-01-20 16:28:04 +00001517 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001518
Douglas Gregor8e984da2010-08-04 16:47:14 +00001519 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001520 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001521
1522 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001523 Clang->getTargetOpts().Features = TargetFeatures;
1524 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1525 Clang->getTargetOpts()));
1526 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001527 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1528 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001529 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001530 PreprocessorOpts.eraseRemappedFile(
1531 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001532 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001533 }
1534
1535 // Inform the target of the language options.
1536 //
1537 // FIXME: We shouldn't need to do this, the target should be immutable once
1538 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001539 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001540
Ted Kremenek84de4a12011-03-21 18:40:07 +00001541 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001542 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001543 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001544 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001545 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001546 "IR inputs not support here!");
1547
1548 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001549 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001550 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001551 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001552 TopLevelDecls.clear();
1553 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554
1555 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001556 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001557
1558 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001559 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001560 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001561
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001562 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001563 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001564 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001565 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1566 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001567 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001568 PreprocessorOpts.eraseRemappedFile(
1569 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001570 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001571 }
1572
1573 Act->Execute();
1574 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001575
Douglas Gregore9db88f2010-08-03 19:06:41 +00001576 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001577 // There were errors parsing the preamble, so no precompiled header was
1578 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001579 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001580 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1581 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001582 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001583 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001584 PreprocessorOpts.eraseRemappedFile(
1585 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001586 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001587 }
1588
Douglas Gregor925296b2011-07-19 16:10:42 +00001589 // Transfer any diagnostics generated when parsing the preamble into the set
1590 // of preamble diagnostics.
1591 PreambleDiagnostics.clear();
1592 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001593 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001594 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001595
Douglas Gregor4dde7492010-07-23 23:58:40 +00001596 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001597 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001598 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001599
1600 // Keep track of all of the files that the source manager knows about,
1601 // so we can verify whether they have changed or not.
1602 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001603 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001604 const llvm::MemoryBuffer *MainFileBuffer
1605 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1606 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1607 FEnd = SourceMgr.fileinfo_end();
1608 F != FEnd;
1609 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001610 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001611 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1612 continue;
1613
1614 FilesInPreamble[File->getName()]
1615 = std::make_pair(F->second->getSize(), File->getModificationTime());
1616 }
1617
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001618 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001619 PreprocessorOpts.eraseRemappedFile(
1620 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001621
1622 // If the hash of top-level entities differs from the hash of the top-level
1623 // entities the last time we rebuilt the preamble, clear out the completion
1624 // cache.
1625 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1626 CompletionCacheTopLevelHashValue = 0;
1627 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1628 }
1629
Douglas Gregor6481ef12010-07-24 00:38:13 +00001630 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001631 PreambleReservedSize,
Douglas Gregor32fbe312012-01-20 16:28:04 +00001632 FrontendOpts.Inputs[0].File);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001633}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001634
Douglas Gregore9db88f2010-08-03 19:06:41 +00001635void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1636 std::vector<Decl *> Resolved;
1637 Resolved.reserve(TopLevelDeclsInPreamble.size());
1638 ExternalASTSource &Source = *getASTContext().getExternalSource();
1639 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1640 // Resolve the declaration ID to an actual declaration, possibly
1641 // deserializing the declaration in the process.
1642 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1643 if (D)
1644 Resolved.push_back(D);
1645 }
1646 TopLevelDeclsInPreamble.clear();
1647 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1648}
1649
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001650StringRef ASTUnit::getMainFileName() const {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001651 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor16896c42010-10-28 15:44:59 +00001652}
1653
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001654ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001655 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001656 bool CaptureDiagnostics) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001657 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001658 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001659 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001660 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001661 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001662 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001663 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001664 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001665
1666 return AST.take();
1667}
1668
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001669ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001670 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001671 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001672 ASTUnit *Unit,
1673 bool Persistent,
1674 StringRef ResourceFilesPath,
1675 bool OnlyLocalDecls,
1676 bool CaptureDiagnostics,
1677 bool PrecompilePreamble,
1678 bool CacheCodeCompletionResults) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001679 assert(CI && "A CompilerInvocation is required");
1680
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001681 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001682 ASTUnit *AST = Unit;
1683 if (!AST) {
1684 // Create the AST unit.
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001685 OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001686 AST = OwnAST.get();
1687 }
1688
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001689 if (!ResourceFilesPath.empty()) {
1690 // Override the resources path.
1691 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1692 }
1693 AST->OnlyLocalDecls = OnlyLocalDecls;
1694 AST->CaptureDiagnostics = CaptureDiagnostics;
1695 if (PrecompilePreamble)
1696 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001697 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001698 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001699
1700 // Recover resources if we crash before exiting this method.
1701 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001702 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001703 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1704 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001705 DiagCleanup(Diags.getPtr());
1706
1707 // We'll manage file buffers ourselves.
1708 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1709 CI->getFrontendOpts().DisableFree = false;
1710 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1711
1712 // Save the target features.
1713 AST->TargetFeatures = CI->getTargetOpts().Features;
1714
1715 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001716 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001717
1718 // Recover resources if we crash before exiting this method.
1719 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1720 CICleanup(Clang.get());
1721
1722 Clang->setInvocation(CI);
Douglas Gregor32fbe312012-01-20 16:28:04 +00001723 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001724
1725 // Set up diagnostics, capturing any diagnostics that would
1726 // otherwise be dropped.
1727 Clang->setDiagnostics(&AST->getDiagnostics());
1728
1729 // Create the target instance.
1730 Clang->getTargetOpts().Features = AST->TargetFeatures;
1731 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1732 Clang->getTargetOpts()));
1733 if (!Clang->hasTarget())
1734 return 0;
1735
1736 // Inform the target of the language options.
1737 //
1738 // FIXME: We shouldn't need to do this, the target should be immutable once
1739 // created. This complexity should be lifted elsewhere.
1740 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1741
1742 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1743 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001744 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001745 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00001746 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001747 "IR inputs not supported here!");
1748
1749 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001750 AST->TheSema.reset();
1751 AST->Ctx = 0;
1752 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001753 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001754
1755 // Create a file manager object to provide access to and cache the filesystem.
1756 Clang->setFileManager(&AST->getFileManager());
1757
1758 // Create the source manager.
1759 Clang->setSourceManager(&AST->getSourceManager());
1760
1761 ASTFrontendAction *Act = Action;
1762
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001763 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001764 if (!Act) {
1765 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1766 Act = TrackerAct.get();
1767 }
1768
1769 // Recover resources if we crash before exiting this method.
1770 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1771 ActCleanup(TrackerAct.get());
1772
Douglas Gregor32fbe312012-01-20 16:28:04 +00001773 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001774 return 0;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001775
1776 if (Persistent && !TrackerAct) {
1777 Clang->getPreprocessor().addPPCallbacks(
1778 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1779 std::vector<ASTConsumer*> Consumers;
1780 if (Clang->hasASTConsumer())
1781 Consumers.push_back(Clang->takeASTConsumer());
1782 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1783 AST->getCurrentTopLevelHashValue()));
1784 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1785 }
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001786 Act->Execute();
1787
1788 // Steal the created target, context, and preprocessor.
1789 AST->TheSema.reset(Clang->takeSema());
1790 AST->Consumer.reset(Clang->takeASTConsumer());
1791 AST->Ctx = &Clang->getASTContext();
1792 AST->PP = &Clang->getPreprocessor();
1793 Clang->setSourceManager(0);
1794 Clang->setFileManager(0);
1795 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001796 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001797
1798 Act->EndSourceFile();
1799
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001800 if (OwnAST)
1801 return OwnAST.take();
1802 else
1803 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001804}
1805
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001806bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1807 if (!Invocation)
1808 return true;
1809
1810 // We'll manage file buffers ourselves.
1811 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1812 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001813 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001814
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001815 // Save the target features.
1816 TargetFeatures = Invocation->getTargetOpts().Features;
1817
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001818 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001819 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001820 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001821 OverrideMainBuffer
1822 = getMainBufferWithPrecompiledPreamble(*Invocation);
1823 }
1824
Douglas Gregor16896c42010-10-28 15:44:59 +00001825 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001826 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001827
Ted Kremenek022a4902011-03-22 01:15:24 +00001828 // Recover resources if we crash before exiting this method.
1829 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1830 MemBufferCleanup(OverrideMainBuffer);
1831
Douglas Gregor16896c42010-10-28 15:44:59 +00001832 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001833}
1834
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001835ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001836 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001837 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001838 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001839 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001840 TranslationUnitKind TUKind,
Argyrios Kyrtzidis335c5a42012-02-25 02:41:16 +00001841 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001842 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001843 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001844 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001845 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001846 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001847 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001848 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001849 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001850 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001851 AST->Invocation = CI;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001852
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001853 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001854 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1855 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001856 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1857 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001858 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001859
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001860 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001861}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001862
1863ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1864 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001865 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001866 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001867 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001868 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001869 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001870 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001871 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001872 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001873 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001874 bool CacheCodeCompletionResults,
1875 bool AllowPCHWithCompilerErrors) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001876 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001877 // No diagnostics engine was provided, so create our own diagnostics object
1878 // with the default options.
1879 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001880 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1881 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001882 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001883
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001885
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001886 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001887
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001888 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001889
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001890 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001891 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001892
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001893 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001894 llvm::makeArrayRef(ArgBegin, ArgEnd),
1895 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001896 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001897 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001898 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001899
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001900 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001901 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1902 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1903 if (const llvm::MemoryBuffer *
1904 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1905 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1906 } else {
1907 const char *fname = fileOrBuf.get<const char *>();
1908 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1909 }
1910 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001911 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1912 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1913 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001914
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001915 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001916 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001917
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001918 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001919 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001920 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001921 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001922 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00001923 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001924 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001925 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001926 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001927 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001928 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001929 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1930 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001931 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001932 AST->Invocation = CI;
Ted Kremenek25047602011-11-17 23:01:17 +00001933 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001934
1935 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001936 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1937 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001938
Chris Lattner5159f612010-11-23 08:35:12 +00001939 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001940}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001941
1942bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001943 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001944 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001945
1946 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001947
Douglas Gregor16896c42010-10-28 15:44:59 +00001948 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001949 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001950
Douglas Gregor0e119552010-07-31 00:40:00 +00001951 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001952 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001953 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001954 for (PreprocessorOptions::remapped_file_buffer_iterator
1955 R = PPOpts.remapped_file_buffer_begin(),
1956 REnd = PPOpts.remapped_file_buffer_end();
1957 R != REnd;
1958 ++R) {
1959 delete R->second;
1960 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001961 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001962 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1963 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1964 if (const llvm::MemoryBuffer *
1965 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1966 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1967 memBuf);
1968 } else {
1969 const char *fname = fileOrBuf.get<const char *>();
1970 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1971 fname);
1972 }
1973 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001974
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001975 // If we have a preamble file lying around, or if we might try to
1976 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001977 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001978 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001979 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001980
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001981 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001982 getDiagnostics().Reset();
1983 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001984 if (OverrideMainBuffer)
1985 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001986
Douglas Gregor4dde7492010-07-23 23:58:40 +00001987 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001988 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001989
1990 // If we're caching global code-completion results, and the top-level
1991 // declarations have changed, clear out the code-completion cache.
1992 if (!Result && ShouldCacheCodeCompletionResults &&
1993 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1994 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001995
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001996 // We now need to clear out the completion info related to this translation
1997 // unit; it'll be recreated if necessary.
1998 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001999
Douglas Gregor4dde7492010-07-23 23:58:40 +00002000 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002001}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002002
Douglas Gregorb14904c2010-08-13 22:48:40 +00002003//----------------------------------------------------------------------------//
2004// Code completion
2005//----------------------------------------------------------------------------//
2006
2007namespace {
2008 /// \brief Code completion consumer that combines the cached code-completion
2009 /// results from an ASTUnit with the code-completion results provided to it,
2010 /// then passes the result on to
2011 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00002012 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002013 ASTUnit &AST;
2014 CodeCompleteConsumer &Next;
2015
2016 public:
2017 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00002018 bool IncludeMacros, bool IncludeCodePatterns,
2019 bool IncludeGlobals)
2020 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00002021 Next.isOutputBinary()), AST(AST), Next(Next)
2022 {
2023 // Compute the set of contexts in which we will look when we don't have
2024 // any information about the specific context.
2025 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00002026 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
2027 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
2028 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
2029 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
2030 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
2031 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
2032 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
2033 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
2034 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
2035 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
2036 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
2037 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
2038 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00002039
David Blaikiebbafb8a2012-03-11 07:00:24 +00002040 if (AST.getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00002041 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2042 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2043 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00002044 }
2045
2046 virtual void ProcessCodeCompleteResults(Sema &S,
2047 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002048 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002049 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002050
2051 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2052 OverloadCandidate *Candidates,
2053 unsigned NumCandidates) {
2054 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2055 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002056
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002057 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002058 return Next.getAllocator();
2059 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002060
2061 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2062 return Next.getCodeCompletionTUInfo();
2063 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002064 };
2065}
Douglas Gregord46cf182010-08-16 20:01:48 +00002066
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002067/// \brief Helper function that computes which global names are hidden by the
2068/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002069static void CalculateHiddenNames(const CodeCompletionContext &Context,
2070 CodeCompletionResult *Results,
2071 unsigned NumResults,
2072 ASTContext &Ctx,
2073 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002074 bool OnlyTagNames = false;
2075 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002076 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002077 case CodeCompletionContext::CCC_TopLevel:
2078 case CodeCompletionContext::CCC_ObjCInterface:
2079 case CodeCompletionContext::CCC_ObjCImplementation:
2080 case CodeCompletionContext::CCC_ObjCIvarList:
2081 case CodeCompletionContext::CCC_ClassStructUnion:
2082 case CodeCompletionContext::CCC_Statement:
2083 case CodeCompletionContext::CCC_Expression:
2084 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002085 case CodeCompletionContext::CCC_DotMemberAccess:
2086 case CodeCompletionContext::CCC_ArrowMemberAccess:
2087 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002088 case CodeCompletionContext::CCC_Namespace:
2089 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002090 case CodeCompletionContext::CCC_Name:
2091 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002092 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002093 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002094 break;
2095
2096 case CodeCompletionContext::CCC_EnumTag:
2097 case CodeCompletionContext::CCC_UnionTag:
2098 case CodeCompletionContext::CCC_ClassOrStructTag:
2099 OnlyTagNames = true;
2100 break;
2101
2102 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002103 case CodeCompletionContext::CCC_MacroName:
2104 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002105 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002106 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002107 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002108 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002109 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002110 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002111 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002112 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2113 case CodeCompletionContext::CCC_ObjCClassMessage:
2114 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002115 // We're looking for nothing, or we're looking for names that cannot
2116 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002117 return;
2118 }
2119
John McCall276321a2010-08-25 06:19:51 +00002120 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002121 for (unsigned I = 0; I != NumResults; ++I) {
2122 if (Results[I].Kind != Result::RK_Declaration)
2123 continue;
2124
2125 unsigned IDNS
2126 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2127
2128 bool Hiding = false;
2129 if (OnlyTagNames)
2130 Hiding = (IDNS & Decl::IDNS_Tag);
2131 else {
2132 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002133 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2134 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002135 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002136 HiddenIDNS |= Decl::IDNS_Tag;
2137 Hiding = (IDNS & HiddenIDNS);
2138 }
2139
2140 if (!Hiding)
2141 continue;
2142
2143 DeclarationName Name = Results[I].Declaration->getDeclName();
2144 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2145 HiddenNames.insert(Identifier->getName());
2146 else
2147 HiddenNames.insert(Name.getAsString());
2148 }
2149}
2150
2151
Douglas Gregord46cf182010-08-16 20:01:48 +00002152void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2153 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002154 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002155 unsigned NumResults) {
2156 // Merge the results we were given with the results we cached.
2157 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002158 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00002159 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi203f87c2011-08-17 01:46:16 +00002160 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002161 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002162 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002163 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002164 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002165 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002166 C = AST.cached_completion_begin(),
2167 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002168 C != CEnd; ++C) {
2169 // If the context we are in matches any of the contexts we are
2170 // interested in, we'll add this result.
2171 if ((C->ShowInContexts & InContexts) == 0)
2172 continue;
2173
2174 // If we haven't added any results previously, do so now.
2175 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002176 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2177 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002178 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2179 AddedResult = true;
2180 }
2181
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002182 // Determine whether this global completion result is hidden by a local
2183 // completion result. If so, skip it.
2184 if (C->Kind != CXCursor_MacroDefinition &&
2185 HiddenNames.count(C->Completion->getTypedText()))
2186 continue;
2187
Douglas Gregord46cf182010-08-16 20:01:48 +00002188 // Adjust priority based on similar type classes.
2189 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002190 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002191 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002192 if (!Context.getPreferredType().isNull()) {
2193 if (C->Kind == CXCursor_MacroDefinition) {
2194 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002195 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002196 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002197 } else if (C->Type) {
2198 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002199 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002200 Context.getPreferredType().getUnqualifiedType());
2201 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2202 if (ExpectedSTC == C->TypeClass) {
2203 // We know this type is similar; check for an exact match.
2204 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002205 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002206 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002207 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002208 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2209 Priority /= CCF_ExactTypeMatch;
2210 else
2211 Priority /= CCF_SimilarTypeMatch;
2212 }
2213 }
2214 }
2215
Douglas Gregor12785102010-08-24 20:21:13 +00002216 // Adjust the completion string, if required.
2217 if (C->Kind == CXCursor_MacroDefinition &&
2218 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2219 // Create a new code-completion string that just contains the
2220 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002221 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2222 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002223 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002224 CursorKind = CXCursor_NotImplemented;
2225 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002226 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002227 }
2228
Douglas Gregor8850aa32010-08-25 18:03:13 +00002229 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002230 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002231 }
2232
2233 // If we did not add any cached completion results, just forward the
2234 // results we were given to the next consumer.
2235 if (!AddedResult) {
2236 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2237 return;
2238 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002239
Douglas Gregord46cf182010-08-16 20:01:48 +00002240 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2241 AllResults.size());
2242}
2243
2244
2245
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002246void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002247 RemappedFile *RemappedFiles,
2248 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002249 bool IncludeMacros,
2250 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002251 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002252 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002253 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002254 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2255 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002256 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002257 return;
2258
Douglas Gregor16896c42010-10-28 15:44:59 +00002259 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002260 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002261 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002262
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002263 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002264 CCInvocation(new CompilerInvocation(*Invocation));
2265
2266 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2267 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002268
Douglas Gregorb14904c2010-08-13 22:48:40 +00002269 FrontendOpts.ShowMacrosInCodeCompletion
2270 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002271 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002272 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2273 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002274 FrontendOpts.CodeCompletionAt.FileName = File;
2275 FrontendOpts.CodeCompletionAt.Line = Line;
2276 FrontendOpts.CodeCompletionAt.Column = Column;
2277
2278 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002279 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002280
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002281 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002282
2283 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002284 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2285 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002286
Ted Kremenek5e14d392011-03-21 18:40:17 +00002287 Clang->setInvocation(&*CCInvocation);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002288 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002289
2290 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002291 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002292 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002293 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002294 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002295 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002296
2297 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002298 Clang->getTargetOpts().Features = TargetFeatures;
2299 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2300 Clang->getTargetOpts()));
2301 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002302 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002303 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002304 }
2305
2306 // Inform the target of the language options.
2307 //
2308 // FIXME: We shouldn't need to do this, the target should be immutable once
2309 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002310 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002311
Ted Kremenek84de4a12011-03-21 18:40:07 +00002312 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002313 "Invocation must have exactly one source file!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00002314 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002315 "FIXME: AST inputs not yet supported here!");
Douglas Gregor32fbe312012-01-20 16:28:04 +00002316 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002317 "IR inputs not support here!");
2318
2319
2320 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002321 Clang->setFileManager(&FileMgr);
2322 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002323
2324 // Remap files.
2325 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002326 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002327 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002328 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2329 if (const llvm::MemoryBuffer *
2330 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2331 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2332 OwnedBuffers.push_back(memBuf);
2333 } else {
2334 const char *fname = fileOrBuf.get<const char *>();
2335 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2336 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002337 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002338
Douglas Gregorb14904c2010-08-13 22:48:40 +00002339 // Use the code completion consumer we were given, but adding any cached
2340 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002341 AugmentedCodeCompleteConsumer *AugmentedConsumer
2342 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2343 FrontendOpts.ShowMacrosInCodeCompletion,
2344 FrontendOpts.ShowCodePatternsInCodeCompletion,
2345 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002346 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002347
Douglas Gregor028d3e42010-08-09 20:45:32 +00002348 // If we have a precompiled preamble, try to use it. We only allow
2349 // the use of the precompiled preamble if we're if the completion
2350 // point is within the main file, after the end of the precompiled
2351 // preamble.
2352 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002353 if (!getPreambleFile(this).empty()) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002354 using llvm::sys::FileStatus;
2355 llvm::sys::PathWithStatus CompleteFilePath(File);
2356 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2357 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2358 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +00002359 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2360 Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002361 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002362 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002363 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002364 }
2365
2366 // If the main file has been overridden due to the use of a preamble,
2367 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002368 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002369 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00002370 stored_diag_begin(),
2371 stored_diag_afterDriver_begin());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002372 if (OverrideMainBuffer) {
2373 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2374 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2375 PreprocessorOpts.PrecompiledPreambleBytes.second
2376 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002377 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002378 PreprocessorOpts.DisablePCHValidation = true;
2379
Douglas Gregorb97b6662010-08-20 00:59:43 +00002380 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002381 } else {
2382 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2383 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002384 }
2385
Douglas Gregor998caea2011-05-06 16:33:08 +00002386 // Disable the preprocessing record
2387 PreprocessorOpts.DetailedRecord = false;
2388
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002389 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002390 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002391 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002392 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00002393 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00002394 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2395 getSourceManager(), PreambleDiagnostics,
2396 StoredDiagnostics);
2397 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002398 Act->Execute();
2399 Act->EndSourceFile();
2400 }
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00002401
2402 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002403}
Douglas Gregore9386682010-08-13 05:36:37 +00002404
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002405CXSaveError ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002406 // Write to a temporary file and later rename it to the actual file, to avoid
2407 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002408 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002409 TempPath = File;
2410 TempPath += "-%%%%%%%%";
2411 int fd;
2412 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2413 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002414 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002415
Douglas Gregore9386682010-08-13 05:36:37 +00002416 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2417 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002418 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002419
2420 serialize(Out);
2421 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002422 if (Out.has_error()) {
2423 Out.clear_error();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002424 return CXSaveError_Unknown;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002425 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002426
Rafael Espindola65e025c2011-12-25 01:18:52 +00002427 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002428 bool exists;
2429 llvm::sys::fs::remove(TempPath.str(), exists);
2430 return CXSaveError_Unknown;
2431 }
2432
2433 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002434}
2435
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002436bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002437 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002438
Daniel Dunbar9a963862012-02-29 20:31:23 +00002439 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002440 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002441 ASTWriter Writer(Stream);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002442 // FIXME: Handle modules
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002443 Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
Douglas Gregore9386682010-08-13 05:36:37 +00002444
2445 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002446 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002447 OS.write((char *)&Buffer.front(), Buffer.size());
2448
2449 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002450}
Douglas Gregor925296b2011-07-19 16:10:42 +00002451
2452typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2453
2454static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2455 unsigned Raw = L.getRawEncoding();
2456 const unsigned MacroBit = 1U << 31;
2457 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2458 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2459}
2460
2461void ASTUnit::TranslateStoredDiagnostics(
2462 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002463 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002464 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002465 const SmallVectorImpl<StoredDiagnostic> &Diags,
2466 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002467 // The stored diagnostic has the old source manager in it; update
2468 // the locations to refer into the new source manager. We also need to remap
2469 // all the locations to the new view. This includes the diag location, any
2470 // associated source ranges, and the source ranges of associated fix-its.
2471 // FIXME: There should be a cleaner way to do this.
2472
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002473 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002474 Result.reserve(Diags.size());
2475 assert(MMan && "Don't have a module manager");
Douglas Gregorde3ef502011-11-30 23:21:26 +00002476 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002477 assert(Mod && "Don't have preamble module");
2478 SLocRemap &Remap = Mod->SLocRemap;
2479 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2480 // Rebuild the StoredDiagnostic.
2481 const StoredDiagnostic &SD = Diags[I];
2482 SourceLocation L = SD.getLocation();
2483 TranslateSLoc(L, Remap);
2484 FullSourceLoc Loc(L, SrcMgr);
2485
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002486 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002487 Ranges.reserve(SD.range_size());
2488 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2489 E = SD.range_end();
2490 I != E; ++I) {
2491 SourceLocation BL = I->getBegin();
2492 TranslateSLoc(BL, Remap);
2493 SourceLocation EL = I->getEnd();
2494 TranslateSLoc(EL, Remap);
2495 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2496 }
2497
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002498 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002499 FixIts.reserve(SD.fixit_size());
2500 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2501 E = SD.fixit_end();
2502 I != E; ++I) {
2503 FixIts.push_back(FixItHint());
2504 FixItHint &FH = FixIts.back();
2505 FH.CodeToInsert = I->CodeToInsert;
2506 SourceLocation BL = I->RemoveRange.getBegin();
2507 TranslateSLoc(BL, Remap);
2508 SourceLocation EL = I->RemoveRange.getEnd();
2509 TranslateSLoc(EL, Remap);
2510 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2511 I->RemoveRange.isTokenRange());
2512 }
2513
2514 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2515 SD.getMessage(), Loc, Ranges, FixIts));
2516 }
2517 Result.swap(Out);
2518}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002519
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002520static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2521 std::pair<unsigned, Decl *> R) {
2522 return L.first < R.first;
2523}
2524
2525void ASTUnit::addFileLevelDecl(Decl *D) {
2526 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002527
2528 // We only care about local declarations.
2529 if (D->isFromASTFile())
2530 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002531
2532 SourceManager &SM = *SourceMgr;
2533 SourceLocation Loc = D->getLocation();
2534 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2535 return;
2536
2537 // We only keep track of the file-level declarations of each file.
2538 if (!D->getLexicalDeclContext()->isFileContext())
2539 return;
2540
2541 SourceLocation FileLoc = SM.getFileLoc(Loc);
2542 assert(SM.isLocalSourceLocation(FileLoc));
2543 FileID FID;
2544 unsigned Offset;
2545 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2546 if (FID.isInvalid())
2547 return;
2548
2549 LocDeclsTy *&Decls = FileDecls[FID];
2550 if (!Decls)
2551 Decls = new LocDeclsTy();
2552
2553 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2554
2555 if (Decls->empty() || Decls->back().first <= Offset) {
2556 Decls->push_back(LocDecl);
2557 return;
2558 }
2559
2560 LocDeclsTy::iterator
2561 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2562
2563 Decls->insert(I, LocDecl);
2564}
2565
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002566void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2567 SmallVectorImpl<Decl *> &Decls) {
2568 if (File.isInvalid())
2569 return;
2570
2571 if (SourceMgr->isLoadedFileID(File)) {
2572 assert(Ctx->getExternalSource() && "No external source!");
2573 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2574 Decls);
2575 }
2576
2577 FileDeclsTy::iterator I = FileDecls.find(File);
2578 if (I == FileDecls.end())
2579 return;
2580
2581 LocDeclsTy &LocDecls = *I->second;
2582 if (LocDecls.empty())
2583 return;
2584
2585 LocDeclsTy::iterator
2586 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2587 std::make_pair(Offset, (Decl*)0), compLocDecl);
2588 if (BeginIt != LocDecls.begin())
2589 --BeginIt;
2590
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002591 // If we are pointing at a top-level decl inside an objc container, we need
2592 // to backtrack until we find it otherwise we will fail to report that the
2593 // region overlaps with an objc container.
2594 while (BeginIt != LocDecls.begin() &&
2595 BeginIt->second->isTopLevelDeclInObjCContainer())
2596 --BeginIt;
2597
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002598 LocDeclsTy::iterator
2599 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2600 std::make_pair(Offset+Length, (Decl*)0),
2601 compLocDecl);
2602 if (EndIt != LocDecls.end())
2603 ++EndIt;
2604
2605 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2606 Decls.push_back(DIt->second);
2607}
2608
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002609SourceLocation ASTUnit::getLocation(const FileEntry *File,
2610 unsigned Line, unsigned Col) const {
2611 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002612 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002613 return SM.getMacroArgExpandedLocation(Loc);
2614}
2615
2616SourceLocation ASTUnit::getLocation(const FileEntry *File,
2617 unsigned Offset) const {
2618 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002619 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002620 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2621}
2622
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002623/// \brief If \arg Loc is a loaded location from the preamble, returns
2624/// the corresponding local location of the main file, otherwise it returns
2625/// \arg Loc.
2626SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2627 FileID PreambleID;
2628 if (SourceMgr)
2629 PreambleID = SourceMgr->getPreambleFileID();
2630
2631 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2632 return Loc;
2633
2634 unsigned Offs;
2635 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2636 SourceLocation FileLoc
2637 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2638 return FileLoc.getLocWithOffset(Offs);
2639 }
2640
2641 return Loc;
2642}
2643
2644/// \brief If \arg Loc is a local location of the main file but inside the
2645/// preamble chunk, returns the corresponding loaded location from the
2646/// preamble, otherwise it returns \arg Loc.
2647SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2648 FileID PreambleID;
2649 if (SourceMgr)
2650 PreambleID = SourceMgr->getPreambleFileID();
2651
2652 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2653 return Loc;
2654
2655 unsigned Offs;
2656 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2657 Offs < Preamble.size()) {
2658 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2659 return FileLoc.getLocWithOffset(Offs);
2660 }
2661
2662 return Loc;
2663}
2664
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002665bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2666 FileID FID;
2667 if (SourceMgr)
2668 FID = SourceMgr->getPreambleFileID();
2669
2670 if (Loc.isInvalid() || FID.isInvalid())
2671 return false;
2672
2673 return SourceMgr->isInFileID(Loc, FID);
2674}
2675
2676bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2677 FileID FID;
2678 if (SourceMgr)
2679 FID = SourceMgr->getMainFileID();
2680
2681 if (Loc.isInvalid() || FID.isInvalid())
2682 return false;
2683
2684 return SourceMgr->isInFileID(Loc, FID);
2685}
2686
2687SourceLocation ASTUnit::getEndOfPreambleFileID() {
2688 FileID FID;
2689 if (SourceMgr)
2690 FID = SourceMgr->getPreambleFileID();
2691
2692 if (FID.isInvalid())
2693 return SourceLocation();
2694
2695 return SourceMgr->getLocForEndOfFile(FID);
2696}
2697
2698SourceLocation ASTUnit::getStartOfMainFileID() {
2699 FileID FID;
2700 if (SourceMgr)
2701 FID = SourceMgr->getMainFileID();
2702
2703 if (FID.isInvalid())
2704 return SourceLocation();
2705
2706 return SourceMgr->getLocForStartOfFile(FID);
2707}
2708
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002709void ASTUnit::PreambleData::countLines() const {
2710 NumLines = 0;
2711 if (empty())
2712 return;
2713
2714 for (std::vector<char>::const_iterator
2715 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2716 if (*I == '\n')
2717 ++NumLines;
2718 }
2719 if (Buffer.back() != '\n')
2720 ++NumLines;
2721}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002722
2723#ifndef NDEBUG
2724ASTUnit::ConcurrencyState::ConcurrencyState() {
2725 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2726}
2727
2728ASTUnit::ConcurrencyState::~ConcurrencyState() {
2729 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2730}
2731
2732void ASTUnit::ConcurrencyState::start() {
2733 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2734 assert(acquired && "Concurrent access to ASTUnit!");
2735}
2736
2737void ASTUnit::ConcurrencyState::finish() {
2738 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2739}
2740
2741#else // NDEBUG
2742
2743ASTUnit::ConcurrencyState::ConcurrencyState() {}
2744ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2745void ASTUnit::ConcurrencyState::start() {}
2746void ASTUnit::ConcurrencyState::finish() {}
2747
2748#endif