blob: 8ac5b681a6f6ac91ddbfff21ce191c813b9548e4 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000028#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000035#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000036#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000037#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000038#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000039#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000040#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000041#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000042using namespace clang;
43
Douglas Gregoreababfb2010-08-04 05:53:38 +000044/// \brief After failing to build a precompiled preamble (due to
45/// errors in the source that occurs in the preamble), the number of
46/// reparses during which we'll skip even trying to precompile the
47/// preamble.
48const unsigned DefaultPreambleRebuildInterval = 5;
49
Douglas Gregor3687e9d2010-04-05 21:10:19 +000050ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000051 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000052 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor87c08a52010-08-13 22:48:40 +000053 PreambleRebuildCounter(0), SavedMainFileBuffer(0),
54 ShouldCacheCodeCompletionResults(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000055}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000056
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000057ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000058 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000059 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000060 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000061 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000062
63 // Free the buffers associated with remapped files. We are required to
64 // perform this operation here because we explicitly request that the
65 // compiler instance *not* free these buffers for each invocation of the
66 // parser.
67 if (Invocation.get()) {
68 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
69 for (PreprocessorOptions::remapped_file_buffer_iterator
70 FB = PPOpts.remapped_file_buffer_begin(),
71 FBEnd = PPOpts.remapped_file_buffer_end();
72 FB != FBEnd;
73 ++FB)
74 delete FB->second;
75 }
Douglas Gregor28233422010-07-27 14:52:07 +000076
77 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000078
Douglas Gregor87c08a52010-08-13 22:48:40 +000079 ClearCachedCompletionResults();
80
Douglas Gregor385103b2010-07-30 20:58:08 +000081 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
82 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000083}
84
85void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000086 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
87 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000088 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000089}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000090
Douglas Gregor8071e422010-08-15 06:18:01 +000091/// \brief Determine the set of code-completion contexts in which this
92/// declaration should be shown.
93static unsigned getDeclShowContexts(NamedDecl *ND,
94 const LangOptions &LangOpts) {
95 if (isa<UsingShadowDecl>(ND))
96 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
97 if (!ND)
98 return 0;
99
100 unsigned Contexts = 0;
101 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
102 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
103 // Types can appear in these contexts.
104 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
105 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
106 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
107 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
108 | (1 << (CodeCompletionContext::CCC_Statement - 1))
109 | (1 << (CodeCompletionContext::CCC_Type - 1));
110
111 // In C++, types can appear in expressions contexts (for functional casts).
112 if (LangOpts.CPlusPlus)
113 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
114
115 // In Objective-C, message sends can send interfaces. In Objective-C++,
116 // all types are available due to functional casts.
117 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
118 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
119
120 // Deal with tag names.
121 if (isa<EnumDecl>(ND)) {
122 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
123
124 // Part of the nested-name-specifier.
125 if (LangOpts.CPlusPlus0x)
126 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1));
127 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
128 if (Record->isUnion())
129 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
130 else
131 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
132
133 // Part of the nested-name-specifier.
134 if (LangOpts.CPlusPlus)
135 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1));
136 }
137 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
138 // Values can appear in these contexts.
139 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
140 | (1 << (CodeCompletionContext::CCC_Expression - 1))
141 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
142 } else if (isa<ObjCProtocolDecl>(ND)) {
143 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
144 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
145 Contexts = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
146 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
147 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
148 | (1 << (CodeCompletionContext::CCC_Statement - 1))
149 | (1 << (CodeCompletionContext::CCC_Expression - 1))
150 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
151 | (1 << (CodeCompletionContext::CCC_Namespace - 1));
152
153 // Part of the nested-name-specifier.
154 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
155 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
156 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
157 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
158 | (1 << (CodeCompletionContext::CCC_Type - 1));
159 }
160
161 return Contexts;
162}
163
Douglas Gregor87c08a52010-08-13 22:48:40 +0000164void ASTUnit::CacheCodeCompletionResults() {
165 if (!TheSema)
166 return;
167
168 llvm::Timer *CachingTimer = 0;
169 if (TimerGroup.get()) {
170 CachingTimer = new llvm::Timer("Cache global code completions",
171 *TimerGroup);
172 CachingTimer->startTimer();
173 Timers.push_back(CachingTimer);
174 }
175
176 // Clear out the previous results.
177 ClearCachedCompletionResults();
178
179 // Gather the set of global code completions.
180 typedef CodeCompleteConsumer::Result Result;
181 llvm::SmallVector<Result, 8> Results;
182 TheSema->GatherGlobalCodeCompletions(Results);
183
184 // Translate global code completions into cached completions.
185 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
186 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000187 case Result::RK_Declaration: {
188 CachedCodeCompletionResult CachedResult;
189 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
190 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
191 Ctx->getLangOptions());
192 CachedResult.Priority = Results[I].Priority;
193 CachedResult.Kind = Results[I].CursorKind;
194 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000195 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000196 }
197
Douglas Gregor87c08a52010-08-13 22:48:40 +0000198 case Result::RK_Keyword:
199 case Result::RK_Pattern:
200 // Ignore keywords and patterns; we don't care, since they are so
201 // easily regenerated.
202 break;
203
204 case Result::RK_Macro: {
205 CachedCodeCompletionResult CachedResult;
206 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
207 CachedResult.ShowInContexts
208 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
209 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
210 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
211 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
212 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
213 | (1 << (CodeCompletionContext::CCC_Statement - 1))
214 | (1 << (CodeCompletionContext::CCC_Expression - 1))
215 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
216 CachedResult.Priority = Results[I].Priority;
217 CachedResult.Kind = Results[I].CursorKind;
218 CachedCompletionResults.push_back(CachedResult);
219 break;
220 }
221 }
222 Results[I].Destroy();
223 }
224
225 if (CachingTimer)
226 CachingTimer->stopTimer();
227}
228
229void ASTUnit::ClearCachedCompletionResults() {
230 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
231 delete CachedCompletionResults[I].Completion;
232 CachedCompletionResults.clear();
233}
234
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000235namespace {
236
237/// \brief Gathers information from PCHReader that will be used to initialize
238/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000239class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000240 LangOptions &LangOpt;
241 HeaderSearch &HSI;
242 std::string &TargetTriple;
243 std::string &Predefines;
244 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000246 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000248public:
249 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
250 std::string &TargetTriple, std::string &Predefines,
251 unsigned &Counter)
252 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
253 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000255 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
256 LangOpt = LangOpts;
257 return false;
258 }
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000260 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000261 TargetTriple = Triple;
262 return false;
263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000265 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000266 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000267 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000268 Predefines = Buffers[0].Data;
269 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
270 Predefines += Buffers[I].Data;
271 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000272 return false;
273 }
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000275 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000276 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
277 }
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000279 virtual void ReadCounter(unsigned Value) {
280 Counter = Value;
281 }
282};
283
Douglas Gregora88084b2010-02-18 18:08:43 +0000284class StoredDiagnosticClient : public DiagnosticClient {
285 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
286
287public:
288 explicit StoredDiagnosticClient(
289 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
290 : StoredDiags(StoredDiags) { }
291
292 virtual void HandleDiagnostic(Diagnostic::Level Level,
293 const DiagnosticInfo &Info);
294};
295
296/// \brief RAII object that optionally captures diagnostics, if
297/// there is no diagnostic client to capture them already.
298class CaptureDroppedDiagnostics {
299 Diagnostic &Diags;
300 StoredDiagnosticClient Client;
301 DiagnosticClient *PreviousClient;
302
303public:
304 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
305 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
306 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
307 {
308 if (RequestCapture || Diags.getClient() == 0)
309 Diags.setClient(&Client);
310 }
311
312 ~CaptureDroppedDiagnostics() {
313 Diags.setClient(PreviousClient);
314 }
315};
316
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000317} // anonymous namespace
318
Douglas Gregora88084b2010-02-18 18:08:43 +0000319void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
320 const DiagnosticInfo &Info) {
321 StoredDiags.push_back(StoredDiagnostic(Level, Info));
322}
323
Steve Naroff77accc12009-09-03 18:19:54 +0000324const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000325 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000326}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000327
Steve Naroffe19944c2009-10-15 22:23:48 +0000328const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000329 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000330 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000331}
332
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000333ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000334 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000335 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000336 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000337 unsigned NumRemappedFiles,
338 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000339 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
340
Douglas Gregor28019772010-04-05 23:52:57 +0000341 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000342 // No diagnostics engine was provided, so create our own diagnostics object
343 // with the default options.
344 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000345 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000346 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000347
348 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000349 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000350 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000351 AST->FileMgr.reset(new FileManager);
352 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000353 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000354
Douglas Gregora88084b2010-02-18 18:08:43 +0000355 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000356 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000357 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000358
Douglas Gregor4db64a42010-01-23 00:14:00 +0000359 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
360 // Create the file entry for the file that we're mapping from.
361 const FileEntry *FromFile
362 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
363 RemappedFiles[I].second->getBufferSize(),
364 0);
365 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000366 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000367 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000368 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000369 continue;
370 }
371
372 // Override the contents of the "from" file with the contents of
373 // the "to" file.
374 AST->getSourceManager().overrideFileContents(FromFile,
375 RemappedFiles[I].second);
376 }
377
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000378 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000380 LangOptions LangInfo;
381 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
382 std::string TargetTriple;
383 std::string Predefines;
384 unsigned Counter;
385
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000386 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000387
Ted Kremenekfc062212009-10-19 21:44:57 +0000388 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000389 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000390 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
391 Predefines, Counter));
392
393 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000394 case PCHReader::Success:
395 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000397 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000398 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000399 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000400 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000403 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
404
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000405 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000407 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000408 //
409 // FIXME: This is broken, we should store the TargetOptions in the PCH.
410 TargetOptions TargetOpts;
411 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000412 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000413 TargetOpts.CPU = "";
414 TargetOpts.Features.clear();
415 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000416 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
417 TargetOpts));
418 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
419 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000420 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000421 Preprocessor &PP = *AST->PP.get();
422
Daniel Dunbard5b61262009-09-21 03:03:47 +0000423 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000424 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000425 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000427 // Create and initialize the ASTContext.
428
429 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000430 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000431 *AST->Target.get(),
432 PP.getIdentifierTable(),
433 PP.getSelectorTable(),
434 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000435 /* size_reserve = */0));
436 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Daniel Dunbarcc318932009-09-03 05:59:35 +0000438 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000440 // Attach the PCH reader to the AST context as an external AST
441 // source, so that declarations will be deserialized from the
442 // PCH file as needed.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000443 PCHReader *ReaderPtr = Reader.get();
444 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000445 Context.setExternalSource(Source);
446
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000447 // Create an AST consumer, even though it isn't used.
448 AST->Consumer.reset(new ASTConsumer);
449
450 // Create a semantic analysis object and tell the PCH reader about it.
451 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
452 AST->TheSema->Initialize();
453 ReaderPtr->InitializeSema(*AST->TheSema);
454
Mike Stump1eb44332009-09-09 15:08:12 +0000455 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000456}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000457
458namespace {
459
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000460class TopLevelDeclTrackerConsumer : public ASTConsumer {
461 ASTUnit &Unit;
462
463public:
464 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
465
466 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000467 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
468 Decl *D = *it;
469 // FIXME: Currently ObjC method declarations are incorrectly being
470 // reported as top-level declarations, even though their DeclContext
471 // is the containing ObjC @interface/@implementation. This is a
472 // fundamental problem in the parser right now.
473 if (isa<ObjCMethodDecl>(D))
474 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000475 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000476 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000477 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000478
479 // We're not interested in "interesting" decls.
480 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000481};
482
483class TopLevelDeclTrackerAction : public ASTFrontendAction {
484public:
485 ASTUnit &Unit;
486
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000487 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
488 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000489 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000490 }
491
492public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000493 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
494
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000495 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000496 virtual bool usesCompleteTranslationUnit() {
497 return Unit.isCompleteTranslationUnit();
498 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000499};
500
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000501class PrecompilePreambleConsumer : public PCHGenerator {
502 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000503 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000504
505public:
506 PrecompilePreambleConsumer(ASTUnit &Unit,
507 const Preprocessor &PP, bool Chaining,
508 const char *isysroot, llvm::raw_ostream *Out)
509 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
510
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000511 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000512 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
513 Decl *D = *it;
514 // FIXME: Currently ObjC method declarations are incorrectly being
515 // reported as top-level declarations, even though their DeclContext
516 // is the containing ObjC @interface/@implementation. This is a
517 // fundamental problem in the parser right now.
518 if (isa<ObjCMethodDecl>(D))
519 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000520 TopLevelDecls.push_back(D);
521 }
522 }
523
524 virtual void HandleTranslationUnit(ASTContext &Ctx) {
525 PCHGenerator::HandleTranslationUnit(Ctx);
526 if (!Unit.getDiagnostics().hasErrorOccurred()) {
527 // Translate the top-level declarations we captured during
528 // parsing into declaration IDs in the precompiled
529 // preamble. This will allow us to deserialize those top-level
530 // declarations when requested.
531 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
532 Unit.addTopLevelDeclFromPreamble(
533 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000534 }
535 }
536};
537
538class PrecompilePreambleAction : public ASTFrontendAction {
539 ASTUnit &Unit;
540
541public:
542 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
543
544 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
545 llvm::StringRef InFile) {
546 std::string Sysroot;
547 llvm::raw_ostream *OS = 0;
548 bool Chaining;
549 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
550 OS, Chaining))
551 return 0;
552
553 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
554 Sysroot.c_str() : 0;
555 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
556 isysroot, OS);
557 }
558
559 virtual bool hasCodeCompletionSupport() const { return false; }
560 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000561 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000562};
563
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000564}
565
Douglas Gregorabc563f2010-07-19 21:46:24 +0000566/// Parse the source file into a translation unit using the given compiler
567/// invocation, replacing the current translation unit.
568///
569/// \returns True if a failure occurred that causes the ASTUnit not to
570/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000571bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000572 delete SavedMainFileBuffer;
573 SavedMainFileBuffer = 0;
574
Douglas Gregorabc563f2010-07-19 21:46:24 +0000575 if (!Invocation.get())
576 return true;
577
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000578 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000579 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000580 Clang.setInvocation(Invocation.take());
581 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
582
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000583 // Set up diagnostics, capturing any diagnostics that would
584 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000585 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000586 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
587 getDiagnostics(),
588 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000589 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000590
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000591 // Create the target instance.
592 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
593 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000594 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000595 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000596 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000597 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000598
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000599 // Inform the target of the language options.
600 //
601 // FIXME: We shouldn't need to do this, the target should be immutable once
602 // created. This complexity should be lifted elsewhere.
603 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000604
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000605 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
606 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000607 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000608 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000609 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
610 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000611
Douglas Gregorabc563f2010-07-19 21:46:24 +0000612 // Configure the various subsystems.
613 // FIXME: Should we retain the previous file manager?
614 FileMgr.reset(new FileManager);
615 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000616 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000617 Ctx.reset();
618 PP.reset();
619
620 // Clear out old caches and data.
621 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000622 CleanTemporaryFiles();
623 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000624
625 if (!OverrideMainBuffer)
626 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000627
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000628 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000629 Clang.setFileManager(&getFileManager());
630
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000631 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000632 Clang.setSourceManager(&getSourceManager());
633
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000634 // If the main file has been overridden due to the use of a preamble,
635 // make that override happen and introduce the preamble.
636 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000637 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000638 if (OverrideMainBuffer) {
639 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
640 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
641 PreprocessorOpts.PrecompiledPreambleBytes.second
642 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000643 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000644 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000645 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000646
647 // Keep track of the override buffer;
648 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000649
650 // The stored diagnostic has the old source manager in it; update
651 // the locations to refer into the new source manager. Since we've
652 // been careful to make sure that the source manager's state
653 // before and after are identical, so that we can reuse the source
654 // location itself.
655 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
656 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
657 getSourceManager());
658 StoredDiagnostics[I].setLocation(Loc);
659 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000660 }
661
Douglas Gregorabc563f2010-07-19 21:46:24 +0000662 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
663 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000664 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000665 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000666 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000667
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000668 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000669
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000670 // Steal the created target, context, and preprocessor, and take back the
671 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000672 TheSema.reset(Clang.takeSema());
673 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000674 Ctx.reset(Clang.takeASTContext());
675 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000676 Clang.takeSourceManager();
677 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000678 Target.reset(Clang.takeTarget());
679
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000680 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000681
682 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000683 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000684 PreprocessorOpts.eraseRemappedFile(
685 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000686 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
687 }
688
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000689 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000690
691 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000692
693 // If we were asked to cache code-completion results and don't have any
694 // results yet, do so now.
695 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
696 CacheCodeCompletionResults();
697
Douglas Gregorabc563f2010-07-19 21:46:24 +0000698 return false;
699
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000700error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000701 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000702 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000703 PreprocessorOpts.eraseRemappedFile(
704 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000705 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000706 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000707 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000708
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000709 Clang.takeSourceManager();
710 Clang.takeFileManager();
711 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000712 Invocation.reset(Clang.takeInvocation());
713 return true;
714}
715
Douglas Gregor44c181a2010-07-23 00:33:23 +0000716/// \brief Simple function to retrieve a path for a preamble precompiled header.
717static std::string GetPreamblePCHPath() {
718 // FIXME: This is lame; sys::Path should provide this function (in particular,
719 // it should know how to find the temporary files dir).
720 // FIXME: This is really lame. I copied this code from the Driver!
721 std::string Error;
722 const char *TmpDir = ::getenv("TMPDIR");
723 if (!TmpDir)
724 TmpDir = ::getenv("TEMP");
725 if (!TmpDir)
726 TmpDir = ::getenv("TMP");
727 if (!TmpDir)
728 TmpDir = "/tmp";
729 llvm::sys::Path P(TmpDir);
730 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000731 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000732 if (P.createTemporaryFileOnDisk())
733 return std::string();
734
Douglas Gregor44c181a2010-07-23 00:33:23 +0000735 return P.str();
736}
737
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000738/// \brief Compute the preamble for the main file, providing the source buffer
739/// that corresponds to the main file along with a pair (bytes, start-of-line)
740/// that describes the preamble.
741std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000742ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
743 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000744 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000745 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000746 = Invocation.getPreprocessorOpts();
747 CreatedBuffer = false;
748
Douglas Gregor44c181a2010-07-23 00:33:23 +0000749 // Try to determine if the main file has been remapped, either from the
750 // command line (to another file) or directly through the compiler invocation
751 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000752 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000753 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
754 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
755 // Check whether there is a file-file remapping of the main file
756 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000757 M = PreprocessorOpts.remapped_file_begin(),
758 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000759 M != E;
760 ++M) {
761 llvm::sys::PathWithStatus MPath(M->first);
762 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
763 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
764 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000765 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000766 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000767 CreatedBuffer = false;
768 }
769
Douglas Gregor44c181a2010-07-23 00:33:23 +0000770 Buffer = llvm::MemoryBuffer::getFile(M->second);
771 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000772 return std::make_pair((llvm::MemoryBuffer*)0,
773 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000774 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000775
Douglas Gregor175c4a92010-07-23 23:58:40 +0000776 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000777 M = PreprocessorOpts.eraseRemappedFile(M);
778 E = PreprocessorOpts.remapped_file_end();
779 }
780 }
781 }
782
783 // Check whether there is a file-buffer remapping. It supercedes the
784 // file-file remapping.
785 for (PreprocessorOptions::remapped_file_buffer_iterator
786 M = PreprocessorOpts.remapped_file_buffer_begin(),
787 E = PreprocessorOpts.remapped_file_buffer_end();
788 M != E;
789 ++M) {
790 llvm::sys::PathWithStatus MPath(M->first);
791 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
792 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
793 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000794 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000795 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000796 CreatedBuffer = false;
797 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000798
Douglas Gregor175c4a92010-07-23 23:58:40 +0000799 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
800
801 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000802 M = PreprocessorOpts.eraseRemappedFile(M);
803 E = PreprocessorOpts.remapped_file_buffer_end();
804 }
805 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000806 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000807 }
808
809 // If the main source file was not remapped, load it now.
810 if (!Buffer) {
811 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
812 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000813 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000814
815 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000816 }
817
Douglas Gregordf95a132010-08-09 20:45:32 +0000818 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000819}
820
Douglas Gregor754f3492010-07-24 00:38:13 +0000821static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
822 bool DeleteOld,
823 unsigned NewSize,
824 llvm::StringRef NewName) {
825 llvm::MemoryBuffer *Result
826 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
827 memcpy(const_cast<char*>(Result->getBufferStart()),
828 Old->getBufferStart(), Old->getBufferSize());
829 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000830 ' ', NewSize - Old->getBufferSize() - 1);
831 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000832
833 if (DeleteOld)
834 delete Old;
835
836 return Result;
837}
838
Douglas Gregor175c4a92010-07-23 23:58:40 +0000839/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
840/// the source file.
841///
842/// This routine will compute the preamble of the main source file. If a
843/// non-trivial preamble is found, it will precompile that preamble into a
844/// precompiled header so that the precompiled preamble can be used to reduce
845/// reparsing time. If a precompiled preamble has already been constructed,
846/// this routine will determine if it is still valid and, if so, avoid
847/// rebuilding the precompiled preamble.
848///
Douglas Gregordf95a132010-08-09 20:45:32 +0000849/// \param AllowRebuild When true (the default), this routine is
850/// allowed to rebuild the precompiled preamble if it is found to be
851/// out-of-date.
852///
853/// \param MaxLines When non-zero, the maximum number of lines that
854/// can occur within the preamble.
855///
Douglas Gregor754f3492010-07-24 00:38:13 +0000856/// \returns If the precompiled preamble can be used, returns a newly-allocated
857/// buffer that should be used in place of the main file when doing so.
858/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000859llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
860 bool AllowRebuild,
861 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000862 CompilerInvocation PreambleInvocation(*Invocation);
863 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
864 PreprocessorOptions &PreprocessorOpts
865 = PreambleInvocation.getPreprocessorOpts();
866
867 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000868 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000869 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000870
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000871 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000872 // We couldn't find a preamble in the main source. Clear out the current
873 // preamble, if we have one. It's obviously no good any more.
874 Preamble.clear();
875 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000876 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000877 PreambleFile.clear();
878 }
879 if (CreatedPreambleBuffer)
880 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000881
882 // The next time we actually see a preamble, precompile it.
883 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000884 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000885 }
886
887 if (!Preamble.empty()) {
888 // We've previously computed a preamble. Check whether we have the same
889 // preamble now that we did before, and that there's enough space in
890 // the main-file buffer within the precompiled preamble to fit the
891 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000892 if (Preamble.size() == NewPreamble.second.first &&
893 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000894 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000895 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000896 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000897 // The preamble has not changed. We may be able to re-use the precompiled
898 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000899
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000900 // Check that none of the files used by the preamble have changed.
901 bool AnyFileChanged = false;
902
903 // First, make a record of those files that have been overridden via
904 // remapping or unsaved_files.
905 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
906 for (PreprocessorOptions::remapped_file_iterator
907 R = PreprocessorOpts.remapped_file_begin(),
908 REnd = PreprocessorOpts.remapped_file_end();
909 !AnyFileChanged && R != REnd;
910 ++R) {
911 struct stat StatBuf;
912 if (stat(R->second.c_str(), &StatBuf)) {
913 // If we can't stat the file we're remapping to, assume that something
914 // horrible happened.
915 AnyFileChanged = true;
916 break;
917 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000918
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000919 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
920 StatBuf.st_mtime);
921 }
922 for (PreprocessorOptions::remapped_file_buffer_iterator
923 R = PreprocessorOpts.remapped_file_buffer_begin(),
924 REnd = PreprocessorOpts.remapped_file_buffer_end();
925 !AnyFileChanged && R != REnd;
926 ++R) {
927 // FIXME: Should we actually compare the contents of file->buffer
928 // remappings?
929 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
930 0);
931 }
932
933 // Check whether anything has changed.
934 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
935 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
936 !AnyFileChanged && F != FEnd;
937 ++F) {
938 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
939 = OverriddenFiles.find(F->first());
940 if (Overridden != OverriddenFiles.end()) {
941 // This file was remapped; check whether the newly-mapped file
942 // matches up with the previous mapping.
943 if (Overridden->second != F->second)
944 AnyFileChanged = true;
945 continue;
946 }
947
948 // The file was not remapped; check whether it has changed on disk.
949 struct stat StatBuf;
950 if (stat(F->first(), &StatBuf)) {
951 // If we can't stat the file, assume that something horrible happened.
952 AnyFileChanged = true;
953 } else if (StatBuf.st_size != F->second.first ||
954 StatBuf.st_mtime != F->second.second)
955 AnyFileChanged = true;
956 }
957
958 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000959 // Okay! We can re-use the precompiled preamble.
960
961 // Set the state of the diagnostic object to mimic its state
962 // after parsing the preamble.
963 getDiagnostics().Reset();
964 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
965 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
966 StoredDiagnostics.erase(
967 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
968 StoredDiagnostics.end());
969
970 // Create a version of the main file buffer that is padded to
971 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000972 return CreatePaddedMainFileBuffer(NewPreamble.first,
973 CreatedPreambleBuffer,
974 PreambleReservedSize,
975 FrontendOpts.Inputs[0].second);
976 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000977 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000978
979 // If we aren't allowed to rebuild the precompiled preamble, just
980 // return now.
981 if (!AllowRebuild)
982 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000983
984 // We can't reuse the previously-computed preamble. Build a new one.
985 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +0000986 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000987 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +0000988 } else if (!AllowRebuild) {
989 // We aren't allowed to rebuild the precompiled preamble; just
990 // return now.
991 return 0;
992 }
Douglas Gregoreababfb2010-08-04 05:53:38 +0000993
994 // If the preamble rebuild counter > 1, it's because we previously
995 // failed to build a preamble and we're not yet ready to try
996 // again. Decrement the counter and return a failure.
997 if (PreambleRebuildCounter > 1) {
998 --PreambleRebuildCounter;
999 return 0;
1000 }
1001
Douglas Gregor175c4a92010-07-23 23:58:40 +00001002 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001003 llvm::Timer *PreambleTimer = 0;
1004 if (TimerGroup.get()) {
1005 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1006 PreambleTimer->startTimer();
1007 Timers.push_back(PreambleTimer);
1008 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001009
1010 // Create a new buffer that stores the preamble. The buffer also contains
1011 // extra space for the original contents of the file (which will be present
1012 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001013 // grows.
1014 PreambleReservedSize = NewPreamble.first->getBufferSize();
1015 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001016 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001017 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001018 PreambleReservedSize *= 2;
1019
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001020 // Save the preamble text for later; we'll need to compare against it for
1021 // subsequent reparses.
1022 Preamble.assign(NewPreamble.first->getBufferStart(),
1023 NewPreamble.first->getBufferStart()
1024 + NewPreamble.second.first);
1025 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1026
Douglas Gregor44c181a2010-07-23 00:33:23 +00001027 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001028 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001029 FrontendOpts.Inputs[0].second);
1030 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001031 NewPreamble.first->getBufferStart(), Preamble.size());
1032 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001033 ' ', PreambleReservedSize - Preamble.size() - 1);
1034 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001035
1036 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001037 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001038 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1039
1040 // Tell the compiler invocation to generate a temporary precompiled header.
1041 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001042 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1043 if (::getenv("LIBCLANG_CHAINING"))
1044 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001045 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +00001046 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001047
1048 // Create the compiler instance to use for building the precompiled preamble.
1049 CompilerInstance Clang;
1050 Clang.setInvocation(&PreambleInvocation);
1051 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1052
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001053 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001054 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001055 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1056 getDiagnostics(),
1057 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001058 Clang.setDiagnosticClient(getDiagnostics().getClient());
1059
1060 // Create the target instance.
1061 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1062 Clang.getTargetOpts()));
1063 if (!Clang.hasTarget()) {
1064 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001065 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1066 Preamble.clear();
1067 if (CreatedPreambleBuffer)
1068 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001069 if (PreambleTimer)
1070 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001071 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001072 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001073 }
1074
1075 // Inform the target of the language options.
1076 //
1077 // FIXME: We shouldn't need to do this, the target should be immutable once
1078 // created. This complexity should be lifted elsewhere.
1079 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1080
1081 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1082 "Invocation must have exactly one source file!");
1083 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1084 "FIXME: AST inputs not yet supported here!");
1085 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1086 "IR inputs not support here!");
1087
1088 // Clear out old caches and data.
1089 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001090 TopLevelDecls.clear();
1091 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001092
1093 // Create a file manager object to provide access to and cache the filesystem.
1094 Clang.setFileManager(new FileManager);
1095
1096 // Create the source manager.
1097 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1098
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001099 llvm::OwningPtr<PrecompilePreambleAction> Act;
1100 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001101 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1102 Clang.getFrontendOpts().Inputs[0].first)) {
1103 Clang.takeDiagnosticClient();
1104 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001105 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1106 Preamble.clear();
1107 if (CreatedPreambleBuffer)
1108 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001109 if (PreambleTimer)
1110 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001111 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +00001112
Douglas Gregor754f3492010-07-24 00:38:13 +00001113 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001114 }
1115
1116 Act->Execute();
1117 Act->EndSourceFile();
1118 Clang.takeDiagnosticClient();
1119 Clang.takeInvocation();
1120
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001121 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001122 // There were errors parsing the preamble, so no precompiled header was
1123 // generated. Forget that we even tried.
1124 // FIXME: Should we leave a note for ourselves to try again?
1125 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1126 Preamble.clear();
1127 if (CreatedPreambleBuffer)
1128 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001129 if (PreambleTimer)
1130 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001131 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001132 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001133 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001134 }
1135
1136 // Keep track of the preamble we precompiled.
1137 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001138 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1139 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001140
1141 // Keep track of all of the files that the source manager knows about,
1142 // so we can verify whether they have changed or not.
1143 FilesInPreamble.clear();
1144 SourceManager &SourceMgr = Clang.getSourceManager();
1145 const llvm::MemoryBuffer *MainFileBuffer
1146 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1147 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1148 FEnd = SourceMgr.fileinfo_end();
1149 F != FEnd;
1150 ++F) {
1151 const FileEntry *File = F->second->Entry;
1152 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1153 continue;
1154
1155 FilesInPreamble[File->getName()]
1156 = std::make_pair(F->second->getSize(), File->getModificationTime());
1157 }
1158
Douglas Gregor385103b2010-07-30 20:58:08 +00001159 if (PreambleTimer)
1160 PreambleTimer->stopTimer();
1161
Douglas Gregoreababfb2010-08-04 05:53:38 +00001162 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001163 return CreatePaddedMainFileBuffer(NewPreamble.first,
1164 CreatedPreambleBuffer,
1165 PreambleReservedSize,
1166 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001167}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001168
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001169void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1170 std::vector<Decl *> Resolved;
1171 Resolved.reserve(TopLevelDeclsInPreamble.size());
1172 ExternalASTSource &Source = *getASTContext().getExternalSource();
1173 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1174 // Resolve the declaration ID to an actual declaration, possibly
1175 // deserializing the declaration in the process.
1176 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1177 if (D)
1178 Resolved.push_back(D);
1179 }
1180 TopLevelDeclsInPreamble.clear();
1181 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1182}
1183
1184unsigned ASTUnit::getMaxPCHLevel() const {
1185 if (!getOnlyLocalDecls())
1186 return Decl::MaxPCHLevel;
1187
1188 unsigned Result = 0;
1189 if (isMainFileAST() || SavedMainFileBuffer)
1190 ++Result;
1191 return Result;
1192}
1193
Douglas Gregorabc563f2010-07-19 21:46:24 +00001194ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1195 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1196 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001197 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001198 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001199 bool CompleteTranslationUnit,
1200 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001201 if (!Diags.getPtr()) {
1202 // No diagnostics engine was provided, so create our own diagnostics object
1203 // with the default options.
1204 DiagnosticOptions DiagOpts;
1205 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1206 }
1207
1208 // Create the AST unit.
1209 llvm::OwningPtr<ASTUnit> AST;
1210 AST.reset(new ASTUnit(false));
1211 AST->Diagnostics = Diags;
1212 AST->CaptureDiagnostics = CaptureDiagnostics;
1213 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001214 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001215 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001216 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001217 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001218
Douglas Gregor385103b2010-07-30 20:58:08 +00001219 if (getenv("LIBCLANG_TIMING"))
1220 AST->TimerGroup.reset(
1221 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1222
1223
Douglas Gregor754f3492010-07-24 00:38:13 +00001224 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001225 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001226 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1227 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001228 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001229 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001230
Douglas Gregor385103b2010-07-30 20:58:08 +00001231 llvm::Timer *ParsingTimer = 0;
1232 if (AST->TimerGroup.get()) {
1233 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1234 ParsingTimer->startTimer();
1235 AST->Timers.push_back(ParsingTimer);
1236 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001237
Douglas Gregor385103b2010-07-30 20:58:08 +00001238 bool Failed = AST->Parse(OverrideMainBuffer);
1239 if (ParsingTimer)
1240 ParsingTimer->stopTimer();
1241
1242 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001243}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001244
1245ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1246 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001247 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001248 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001249 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001250 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001251 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001252 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001253 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001254 bool CompleteTranslationUnit,
1255 bool CacheCodeCompletionResults) {
Douglas Gregor28019772010-04-05 23:52:57 +00001256 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001257 // No diagnostics engine was provided, so create our own diagnostics object
1258 // with the default options.
1259 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001260 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001261 }
1262
Daniel Dunbar7b556682009-12-02 03:23:45 +00001263 llvm::SmallVector<const char *, 16> Args;
1264 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1265 Args.insert(Args.end(), ArgBegin, ArgEnd);
1266
1267 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1268 // also want to force it to use clang.
1269 Args.push_back("-fsyntax-only");
1270
Daniel Dunbar869824e2009-12-13 03:46:13 +00001271 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001272 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001273 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001274
1275 // Don't check that inputs exist, they have been remapped.
1276 TheDriver.setCheckInputsExist(false);
1277
Daniel Dunbar7b556682009-12-02 03:23:45 +00001278 llvm::OwningPtr<driver::Compilation> C(
1279 TheDriver.BuildCompilation(Args.size(), Args.data()));
1280
1281 // We expect to get back exactly one command job, if we didn't something
1282 // failed.
1283 const driver::JobList &Jobs = C->getJobs();
1284 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1285 llvm::SmallString<256> Msg;
1286 llvm::raw_svector_ostream OS(Msg);
1287 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001288 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001289 return 0;
1290 }
1291
1292 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1293 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001294 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001295 return 0;
1296 }
1297
1298 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001299 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001300 CompilerInvocation::CreateFromArgs(*CI,
1301 const_cast<const char **>(CCArgs.data()),
1302 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001303 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001304 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001305
Douglas Gregor4db64a42010-01-23 00:14:00 +00001306 // Override any files that need remapping
1307 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001308 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001309 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001310
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001311 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001312 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001313
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001314 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001315 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001316 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001317 CompleteTranslationUnit,
1318 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001319}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001320
1321bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1322 if (!Invocation.get())
1323 return true;
1324
Douglas Gregor385103b2010-07-30 20:58:08 +00001325 llvm::Timer *ReparsingTimer = 0;
1326 if (TimerGroup.get()) {
1327 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1328 ReparsingTimer->startTimer();
1329 Timers.push_back(ReparsingTimer);
1330 }
1331
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001332 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001333 Invocation->getPreprocessorOpts().clearRemappedFiles();
1334 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1335 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1336 RemappedFiles[I].second);
1337
Douglas Gregoreababfb2010-08-04 05:53:38 +00001338 // If we have a preamble file lying around, or if we might try to
1339 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001340 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001341 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001342 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001343
Douglas Gregorabc563f2010-07-19 21:46:24 +00001344 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001345 if (!OverrideMainBuffer)
1346 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001347
Douglas Gregor175c4a92010-07-23 23:58:40 +00001348 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001349 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001350 if (ReparsingTimer)
1351 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001352 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001353}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001354
Douglas Gregor87c08a52010-08-13 22:48:40 +00001355//----------------------------------------------------------------------------//
1356// Code completion
1357//----------------------------------------------------------------------------//
1358
1359namespace {
1360 /// \brief Code completion consumer that combines the cached code-completion
1361 /// results from an ASTUnit with the code-completion results provided to it,
1362 /// then passes the result on to
1363 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1364 unsigned NormalContexts;
1365 ASTUnit &AST;
1366 CodeCompleteConsumer &Next;
1367
1368 public:
1369 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001370 bool IncludeMacros, bool IncludeCodePatterns,
1371 bool IncludeGlobals)
1372 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001373 Next.isOutputBinary()), AST(AST), Next(Next)
1374 {
1375 // Compute the set of contexts in which we will look when we don't have
1376 // any information about the specific context.
1377 NormalContexts
1378 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1379 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1380 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1381 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1382 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1383 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1384 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1385 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1386 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1387
1388 if (AST.getASTContext().getLangOptions().CPlusPlus)
1389 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1390 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1391 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1392 }
1393
1394 virtual void ProcessCodeCompleteResults(Sema &S,
1395 CodeCompletionContext Context,
1396 Result *Results,
1397 unsigned NumResults) {
1398 // Merge the results we were given with the results we cached.
1399 bool AddedResult = false;
1400 unsigned InContexts =
1401 (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1402 : (1 << (Context.getKind() - 1)));
1403 typedef CodeCompleteConsumer::Result Result;
1404 llvm::SmallVector<Result, 8> AllResults;
1405 for (ASTUnit::cached_completion_iterator
1406 C = AST.cached_completion_begin(),
1407 CEnd = AST.cached_completion_end();
1408 C != CEnd; ++C) {
1409 // If the context we are in matches any of the contexts we are
1410 // interested in, we'll add this result.
1411 if ((C->ShowInContexts & InContexts) == 0)
1412 continue;
1413
1414 // If we haven't added any results previously, do so now.
1415 if (!AddedResult) {
1416 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1417 AddedResult = true;
1418 }
1419
1420 AllResults.push_back(Result(C->Completion, C->Priority, C->Kind));
1421 }
1422
1423 // If we did not add any cached completion results, just forward the
1424 // results we were given to the next consumer.
1425 if (!AddedResult) {
1426 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1427 return;
1428 }
1429
1430 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1431 AllResults.size());
1432 }
1433
1434 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1435 OverloadCandidate *Candidates,
1436 unsigned NumCandidates) {
1437 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1438 }
1439 };
1440}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001441void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1442 RemappedFile *RemappedFiles,
1443 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001444 bool IncludeMacros,
1445 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001446 CodeCompleteConsumer &Consumer,
1447 Diagnostic &Diag, LangOptions &LangOpts,
1448 SourceManager &SourceMgr, FileManager &FileMgr,
1449 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1450 if (!Invocation.get())
1451 return;
1452
Douglas Gregordf95a132010-08-09 20:45:32 +00001453 llvm::Timer *CompletionTimer = 0;
1454 if (TimerGroup.get()) {
1455 llvm::SmallString<128> TimerName;
1456 llvm::raw_svector_ostream TimerNameOut(TimerName);
1457 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1458 << Column;
1459 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1460 CompletionTimer->startTimer();
1461 Timers.push_back(CompletionTimer);
1462 }
1463
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001464 CompilerInvocation CCInvocation(*Invocation);
1465 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1466 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001467
Douglas Gregor87c08a52010-08-13 22:48:40 +00001468 FrontendOpts.ShowMacrosInCodeCompletion
1469 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001470 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001471 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1472 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001473 FrontendOpts.CodeCompletionAt.FileName = File;
1474 FrontendOpts.CodeCompletionAt.Line = Line;
1475 FrontendOpts.CodeCompletionAt.Column = Column;
1476
Douglas Gregorcee235c2010-08-05 09:09:23 +00001477 // Turn on spell-checking when performing code completion. It leads
1478 // to better results.
1479 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1480 CCInvocation.getLangOpts().SpellChecking = 1;
1481
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001482 // Set the language options appropriately.
1483 LangOpts = CCInvocation.getLangOpts();
1484
1485 CompilerInstance Clang;
1486 Clang.setInvocation(&CCInvocation);
1487 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1488
1489 // Set up diagnostics, capturing any diagnostics produced.
1490 Clang.setDiagnostics(&Diag);
1491 CaptureDroppedDiagnostics Capture(true,
1492 Clang.getDiagnostics(),
1493 StoredDiagnostics);
1494 Clang.setDiagnosticClient(Diag.getClient());
1495
1496 // Create the target instance.
1497 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1498 Clang.getTargetOpts()));
1499 if (!Clang.hasTarget()) {
1500 Clang.takeDiagnosticClient();
1501 Clang.takeInvocation();
1502 }
1503
1504 // Inform the target of the language options.
1505 //
1506 // FIXME: We shouldn't need to do this, the target should be immutable once
1507 // created. This complexity should be lifted elsewhere.
1508 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1509
1510 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1511 "Invocation must have exactly one source file!");
1512 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1513 "FIXME: AST inputs not yet supported here!");
1514 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1515 "IR inputs not support here!");
1516
1517
1518 // Use the source and file managers that we were given.
1519 Clang.setFileManager(&FileMgr);
1520 Clang.setSourceManager(&SourceMgr);
1521
1522 // Remap files.
1523 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001524 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001525 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1526 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1527 RemappedFiles[I].second);
1528
Douglas Gregor87c08a52010-08-13 22:48:40 +00001529 // Use the code completion consumer we were given, but adding any cached
1530 // code-completion results.
1531 AugmentedCodeCompleteConsumer
1532 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001533 FrontendOpts.ShowCodePatternsInCodeCompletion,
1534 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001535 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001536
Douglas Gregordf95a132010-08-09 20:45:32 +00001537 // If we have a precompiled preamble, try to use it. We only allow
1538 // the use of the precompiled preamble if we're if the completion
1539 // point is within the main file, after the end of the precompiled
1540 // preamble.
1541 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1542 if (!PreambleFile.empty()) {
1543 using llvm::sys::FileStatus;
1544 llvm::sys::PathWithStatus CompleteFilePath(File);
1545 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1546 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1547 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1548 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1549 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1550 Line);
1551 }
1552
1553 // If the main file has been overridden due to the use of a preamble,
1554 // make that override happen and introduce the preamble.
1555 if (OverrideMainBuffer) {
1556 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1557 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1558 PreprocessorOpts.PrecompiledPreambleBytes.second
1559 = PreambleEndsAtStartOfLine;
1560 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1561 PreprocessorOpts.DisablePCHValidation = true;
1562
1563 // The stored diagnostics have the old source manager. Copy them
1564 // to our output set of stored diagnostics, updating the source
1565 // manager to the one we were given.
1566 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1567 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1568 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1569 StoredDiagnostics[I].setLocation(Loc);
1570 }
1571 }
1572
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001573 llvm::OwningPtr<SyntaxOnlyAction> Act;
1574 Act.reset(new SyntaxOnlyAction);
1575 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1576 Clang.getFrontendOpts().Inputs[0].first)) {
1577 Act->Execute();
1578 Act->EndSourceFile();
1579 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001580
1581 if (CompletionTimer)
1582 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001583
1584 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001585 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001586 Clang.takeFileManager();
1587 Clang.takeSourceManager();
1588 Clang.takeInvocation();
1589 Clang.takeDiagnosticClient();
1590 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001591 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001592}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001593
1594bool ASTUnit::Save(llvm::StringRef File) {
1595 if (getDiagnostics().hasErrorOccurred())
1596 return true;
1597
1598 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1599 // unconditionally create a stat cache when we parse the file?
1600 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001601 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1602 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001603 if (!ErrorInfo.empty() || Out.has_error())
1604 return true;
1605
1606 std::vector<unsigned char> Buffer;
1607 llvm::BitstreamWriter Stream(Buffer);
1608 PCHWriter Writer(Stream);
1609 Writer.WritePCH(getSema(), 0, 0);
1610
1611 // Write the generated bitstream to "Out".
1612 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001613 Out.close();
1614 return Out.has_error();
1615}