blob: fe4768db7c72afa98c85f6806d285def04ee2672 [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"
Douglas Gregor48c8cd32010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
19#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"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor48c8cd32010-08-03 08:14:03 +000028#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000035#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000036#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000037#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000038#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000039#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000040#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000041#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000042using namespace clang;
43
Douglas Gregorbb420ab2010-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 Gregord03e8232010-04-05 21:10:19 +000050ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000051 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor028d3e42010-08-09 20:45:32 +000052 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
53 PreambleRebuildCounter(0), SavedMainFileBuffer(0) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000054}
Douglas Gregord03e8232010-04-05 21:10:19 +000055
Daniel Dunbar764c0822009-12-01 09:51:01 +000056ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000057 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000058 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000059 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000060 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000061
62 // Free the buffers associated with remapped files. We are required to
63 // perform this operation here because we explicitly request that the
64 // compiler instance *not* free these buffers for each invocation of the
65 // parser.
66 if (Invocation.get()) {
67 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
68 for (PreprocessorOptions::remapped_file_buffer_iterator
69 FB = PPOpts.remapped_file_buffer_begin(),
70 FBEnd = PPOpts.remapped_file_buffer_end();
71 FB != FBEnd;
72 ++FB)
73 delete FB->second;
74 }
Douglas Gregor96c04262010-07-27 14:52:07 +000075
76 delete SavedMainFileBuffer;
Douglas Gregor15ba0b32010-07-30 20:58:08 +000077
78 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
79 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000080}
81
82void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000083 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
84 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000085 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000086}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000087
88namespace {
89
90/// \brief Gathers information from PCHReader that will be used to initialize
91/// a Preprocessor.
Benjamin Kramer16634c22009-11-28 10:07:24 +000092class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000093 LangOptions &LangOpt;
94 HeaderSearch &HSI;
95 std::string &TargetTriple;
96 std::string &Predefines;
97 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +000098
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000099 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000101public:
102 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
103 std::string &TargetTriple, std::string &Predefines,
104 unsigned &Counter)
105 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
106 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000107
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000108 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
109 LangOpt = LangOpts;
110 return false;
111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000113 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000114 TargetTriple = Triple;
115 return false;
116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Sebastian Redl8b41f302010-07-14 23:29:55 +0000118 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000119 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000120 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000121 Predefines = Buffers[0].Data;
122 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
123 Predefines += Buffers[I].Data;
124 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000125 return false;
126 }
Mike Stump11289f42009-09-09 15:08:12 +0000127
Douglas Gregora2f49452010-03-16 19:09:18 +0000128 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000129 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000132 virtual void ReadCounter(unsigned Value) {
133 Counter = Value;
134 }
135};
136
Douglas Gregor33cdd812010-02-18 18:08:43 +0000137class StoredDiagnosticClient : public DiagnosticClient {
138 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
139
140public:
141 explicit StoredDiagnosticClient(
142 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
143 : StoredDiags(StoredDiags) { }
144
145 virtual void HandleDiagnostic(Diagnostic::Level Level,
146 const DiagnosticInfo &Info);
147};
148
149/// \brief RAII object that optionally captures diagnostics, if
150/// there is no diagnostic client to capture them already.
151class CaptureDroppedDiagnostics {
152 Diagnostic &Diags;
153 StoredDiagnosticClient Client;
154 DiagnosticClient *PreviousClient;
155
156public:
157 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
158 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
159 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
160 {
161 if (RequestCapture || Diags.getClient() == 0)
162 Diags.setClient(&Client);
163 }
164
165 ~CaptureDroppedDiagnostics() {
166 Diags.setClient(PreviousClient);
167 }
168};
169
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000170} // anonymous namespace
171
Douglas Gregor33cdd812010-02-18 18:08:43 +0000172void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
173 const DiagnosticInfo &Info) {
174 StoredDiags.push_back(StoredDiagnostic(Level, Info));
175}
176
Steve Naroffc0683b92009-09-03 18:19:54 +0000177const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000178 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000179}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000180
Steve Naroff44cd60e2009-10-15 22:23:48 +0000181const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbara18f9582009-12-02 21:47:43 +0000182 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer2ecf8eb2010-01-30 16:23:25 +0000183 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000184}
185
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000186ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000187 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000188 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000189 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000190 unsigned NumRemappedFiles,
191 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000192 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
193
Douglas Gregor7f95d262010-04-05 23:52:57 +0000194 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000195 // No diagnostics engine was provided, so create our own diagnostics object
196 // with the default options.
197 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000198 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000199 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000200
201 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000202 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000203 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000204 AST->FileMgr.reset(new FileManager);
205 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000206 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000207
Douglas Gregor33cdd812010-02-18 18:08:43 +0000208 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000209 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000210 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000211
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000212 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
213 // Create the file entry for the file that we're mapping from.
214 const FileEntry *FromFile
215 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
216 RemappedFiles[I].second->getBufferSize(),
217 0);
218 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000219 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000220 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000221 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000222 continue;
223 }
224
225 // Override the contents of the "from" file with the contents of
226 // the "to" file.
227 AST->getSourceManager().overrideFileContents(FromFile,
228 RemappedFiles[I].second);
229 }
230
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000231 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000232
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000233 LangOptions LangInfo;
234 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
235 std::string TargetTriple;
236 std::string Predefines;
237 unsigned Counter;
238
Daniel Dunbar3a0637b2009-09-03 05:59:50 +0000239 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000240 llvm::OwningPtr<ExternalASTSource> Source;
241
Ted Kremenek428c6372009-10-19 21:44:57 +0000242 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000243 AST->getDiagnostics()));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000244 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
245 Predefines, Counter));
246
247 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000248 case PCHReader::Success:
249 break;
Mike Stump11289f42009-09-09 15:08:12 +0000250
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000251 case PCHReader::Failure:
Argyrios Kyrtzidis55c34112009-06-25 18:22:30 +0000252 case PCHReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000253 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000254 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000255 }
Mike Stump11289f42009-09-09 15:08:12 +0000256
Daniel Dunbara8a50932009-12-02 08:44:16 +0000257 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
258
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000259 // PCH loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000260
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000261 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000262 //
263 // FIXME: This is broken, we should store the TargetOptions in the PCH.
264 TargetOptions TargetOpts;
265 TargetOpts.ABI = "";
Charles Davis95a546e2010-06-11 01:06:47 +0000266 TargetOpts.CXXABI = "itanium";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000267 TargetOpts.CPU = "";
268 TargetOpts.Features.clear();
269 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000270 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
271 TargetOpts));
272 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
273 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000274 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000275 Preprocessor &PP = *AST->PP.get();
276
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000277 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000278 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000279 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000280
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000281 // Create and initialize the ASTContext.
282
283 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000284 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000285 *AST->Target.get(),
286 PP.getIdentifierTable(),
287 PP.getSelectorTable(),
288 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000289 /* size_reserve = */0));
290 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000291
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000292 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000293
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000294 // Attach the PCH reader to the AST context as an external AST
295 // source, so that declarations will be deserialized from the
296 // PCH file as needed.
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000297 Source.reset(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000298 Context.setExternalSource(Source);
299
Mike Stump11289f42009-09-09 15:08:12 +0000300 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000301}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000302
303namespace {
304
Daniel Dunbar644dca02009-12-04 08:17:33 +0000305class TopLevelDeclTrackerConsumer : public ASTConsumer {
306 ASTUnit &Unit;
307
308public:
309 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
310
311 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000312 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
313 Decl *D = *it;
314 // FIXME: Currently ObjC method declarations are incorrectly being
315 // reported as top-level declarations, even though their DeclContext
316 // is the containing ObjC @interface/@implementation. This is a
317 // fundamental problem in the parser right now.
318 if (isa<ObjCMethodDecl>(D))
319 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000320 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000321 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000322 }
323};
324
325class TopLevelDeclTrackerAction : public ASTFrontendAction {
326public:
327 ASTUnit &Unit;
328
Daniel Dunbar764c0822009-12-01 09:51:01 +0000329 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
330 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000331 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000332 }
333
334public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000335 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
336
Daniel Dunbar764c0822009-12-01 09:51:01 +0000337 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000338 virtual bool usesCompleteTranslationUnit() {
339 return Unit.isCompleteTranslationUnit();
340 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000341};
342
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000343class PrecompilePreambleConsumer : public PCHGenerator {
344 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000345 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000346
347public:
348 PrecompilePreambleConsumer(ASTUnit &Unit,
349 const Preprocessor &PP, bool Chaining,
350 const char *isysroot, llvm::raw_ostream *Out)
351 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
352
Douglas Gregore9db88f2010-08-03 19:06:41 +0000353 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000354 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
355 Decl *D = *it;
356 // FIXME: Currently ObjC method declarations are incorrectly being
357 // reported as top-level declarations, even though their DeclContext
358 // is the containing ObjC @interface/@implementation. This is a
359 // fundamental problem in the parser right now.
360 if (isa<ObjCMethodDecl>(D))
361 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000362 TopLevelDecls.push_back(D);
363 }
364 }
365
366 virtual void HandleTranslationUnit(ASTContext &Ctx) {
367 PCHGenerator::HandleTranslationUnit(Ctx);
368 if (!Unit.getDiagnostics().hasErrorOccurred()) {
369 // Translate the top-level declarations we captured during
370 // parsing into declaration IDs in the precompiled
371 // preamble. This will allow us to deserialize those top-level
372 // declarations when requested.
373 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
374 Unit.addTopLevelDeclFromPreamble(
375 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000376 }
377 }
378};
379
380class PrecompilePreambleAction : public ASTFrontendAction {
381 ASTUnit &Unit;
382
383public:
384 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
385
386 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
387 llvm::StringRef InFile) {
388 std::string Sysroot;
389 llvm::raw_ostream *OS = 0;
390 bool Chaining;
391 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
392 OS, Chaining))
393 return 0;
394
395 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
396 Sysroot.c_str() : 0;
397 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
398 isysroot, OS);
399 }
400
401 virtual bool hasCodeCompletionSupport() const { return false; }
402 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000403 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000404};
405
Daniel Dunbar764c0822009-12-01 09:51:01 +0000406}
407
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000408/// Parse the source file into a translation unit using the given compiler
409/// invocation, replacing the current translation unit.
410///
411/// \returns True if a failure occurred that causes the ASTUnit not to
412/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000413bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000414 delete SavedMainFileBuffer;
415 SavedMainFileBuffer = 0;
416
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000417 if (!Invocation.get())
418 return true;
419
Daniel Dunbar764c0822009-12-01 09:51:01 +0000420 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000421 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000422 Clang.setInvocation(Invocation.take());
423 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
424
Douglas Gregor8e984da2010-08-04 16:47:14 +0000425 // Set up diagnostics, capturing any diagnostics that would
426 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000427 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000428 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
429 getDiagnostics(),
430 StoredDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000431 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregord03e8232010-04-05 21:10:19 +0000432
Daniel Dunbar764c0822009-12-01 09:51:01 +0000433 // Create the target instance.
434 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
435 Clang.getTargetOpts()));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000436 if (!Clang.hasTarget()) {
Douglas Gregor33cdd812010-02-18 18:08:43 +0000437 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000438 return true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000439 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000440
Daniel Dunbar764c0822009-12-01 09:51:01 +0000441 // Inform the target of the language options.
442 //
443 // FIXME: We shouldn't need to do this, the target should be immutable once
444 // created. This complexity should be lifted elsewhere.
445 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000446
Daniel Dunbar764c0822009-12-01 09:51:01 +0000447 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
448 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000449 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000450 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000451 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
452 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000453
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000454 // Configure the various subsystems.
455 // FIXME: Should we retain the previous file manager?
456 FileMgr.reset(new FileManager);
457 SourceMgr.reset(new SourceManager(getDiagnostics()));
458 Ctx.reset();
459 PP.reset();
460
461 // Clear out old caches and data.
462 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000463 CleanTemporaryFiles();
464 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000465
466 if (!OverrideMainBuffer)
467 StoredDiagnostics.clear();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000468
Daniel Dunbar764c0822009-12-01 09:51:01 +0000469 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000470 Clang.setFileManager(&getFileManager());
471
Daniel Dunbar764c0822009-12-01 09:51:01 +0000472 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000473 Clang.setSourceManager(&getSourceManager());
474
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000475 // If the main file has been overridden due to the use of a preamble,
476 // make that override happen and introduce the preamble.
477 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000478 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000479 if (OverrideMainBuffer) {
480 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
481 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
482 PreprocessorOpts.PrecompiledPreambleBytes.second
483 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000484 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000485 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000486 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000487
488 // Keep track of the override buffer;
489 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000490
491 // The stored diagnostic has the old source manager in it; update
492 // the locations to refer into the new source manager. Since we've
493 // been careful to make sure that the source manager's state
494 // before and after are identical, so that we can reuse the source
495 // location itself.
496 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
497 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
498 getSourceManager());
499 StoredDiagnostics[I].setLocation(Loc);
500 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000501 }
502
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000503 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
504 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000505 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000506 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000507 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000508
Daniel Dunbar644dca02009-12-04 08:17:33 +0000509 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000510
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000511 // Steal the created target, context, and preprocessor, and take back the
512 // source and file managers.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000513 Ctx.reset(Clang.takeASTContext());
514 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000515 Clang.takeSourceManager();
516 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000517 Target.reset(Clang.takeTarget());
518
Daniel Dunbar644dca02009-12-04 08:17:33 +0000519 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000520
521 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000522 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000523 PreprocessorOpts.eraseRemappedFile(
524 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000525 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
526 }
527
Daniel Dunbar764c0822009-12-01 09:51:01 +0000528 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000529
530 Invocation.reset(Clang.takeInvocation());
531 return false;
532
Daniel Dunbar764c0822009-12-01 09:51:01 +0000533error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000534 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000535 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000536 PreprocessorOpts.eraseRemappedFile(
537 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000538 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000539 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000540 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000541
Daniel Dunbar764c0822009-12-01 09:51:01 +0000542 Clang.takeSourceManager();
543 Clang.takeFileManager();
544 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000545 Invocation.reset(Clang.takeInvocation());
546 return true;
547}
548
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000549/// \brief Simple function to retrieve a path for a preamble precompiled header.
550static std::string GetPreamblePCHPath() {
551 // FIXME: This is lame; sys::Path should provide this function (in particular,
552 // it should know how to find the temporary files dir).
553 // FIXME: This is really lame. I copied this code from the Driver!
554 std::string Error;
555 const char *TmpDir = ::getenv("TMPDIR");
556 if (!TmpDir)
557 TmpDir = ::getenv("TEMP");
558 if (!TmpDir)
559 TmpDir = ::getenv("TMP");
560 if (!TmpDir)
561 TmpDir = "/tmp";
562 llvm::sys::Path P(TmpDir);
563 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000564 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000565 if (P.createTemporaryFileOnDisk())
566 return std::string();
567
Douglas Gregor20975b22010-08-11 13:06:56 +0000568 fprintf(stderr, "Preamble file: %s\n", P.str().c_str());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000569 return P.str();
570}
571
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000572/// \brief Compute the preamble for the main file, providing the source buffer
573/// that corresponds to the main file along with a pair (bytes, start-of-line)
574/// that describes the preamble.
575std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000576ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
577 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000578 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000579 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000580 = Invocation.getPreprocessorOpts();
581 CreatedBuffer = false;
582
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000583 // Try to determine if the main file has been remapped, either from the
584 // command line (to another file) or directly through the compiler invocation
585 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000586 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000587 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
588 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
589 // Check whether there is a file-file remapping of the main file
590 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000591 M = PreprocessorOpts.remapped_file_begin(),
592 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000593 M != E;
594 ++M) {
595 llvm::sys::PathWithStatus MPath(M->first);
596 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
597 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
598 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000599 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000600 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000601 CreatedBuffer = false;
602 }
603
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000604 Buffer = llvm::MemoryBuffer::getFile(M->second);
605 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000606 return std::make_pair((llvm::MemoryBuffer*)0,
607 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000608 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000609
Douglas Gregor4dde7492010-07-23 23:58:40 +0000610 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000611 M = PreprocessorOpts.eraseRemappedFile(M);
612 E = PreprocessorOpts.remapped_file_end();
613 }
614 }
615 }
616
617 // Check whether there is a file-buffer remapping. It supercedes the
618 // file-file remapping.
619 for (PreprocessorOptions::remapped_file_buffer_iterator
620 M = PreprocessorOpts.remapped_file_buffer_begin(),
621 E = PreprocessorOpts.remapped_file_buffer_end();
622 M != E;
623 ++M) {
624 llvm::sys::PathWithStatus MPath(M->first);
625 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
626 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
627 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000628 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000629 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000630 CreatedBuffer = false;
631 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000632
Douglas Gregor4dde7492010-07-23 23:58:40 +0000633 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
634
635 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000636 M = PreprocessorOpts.eraseRemappedFile(M);
637 E = PreprocessorOpts.remapped_file_buffer_end();
638 }
639 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000640 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000641 }
642
643 // If the main source file was not remapped, load it now.
644 if (!Buffer) {
645 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
646 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000647 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000648
649 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000650 }
651
Douglas Gregor028d3e42010-08-09 20:45:32 +0000652 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000653}
654
Douglas Gregor6481ef12010-07-24 00:38:13 +0000655static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
656 bool DeleteOld,
657 unsigned NewSize,
658 llvm::StringRef NewName) {
659 llvm::MemoryBuffer *Result
660 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
661 memcpy(const_cast<char*>(Result->getBufferStart()),
662 Old->getBufferStart(), Old->getBufferSize());
663 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000664 ' ', NewSize - Old->getBufferSize() - 1);
665 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000666
667 if (DeleteOld)
668 delete Old;
669
670 return Result;
671}
672
Douglas Gregor4dde7492010-07-23 23:58:40 +0000673/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
674/// the source file.
675///
676/// This routine will compute the preamble of the main source file. If a
677/// non-trivial preamble is found, it will precompile that preamble into a
678/// precompiled header so that the precompiled preamble can be used to reduce
679/// reparsing time. If a precompiled preamble has already been constructed,
680/// this routine will determine if it is still valid and, if so, avoid
681/// rebuilding the precompiled preamble.
682///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000683/// \param AllowRebuild When true (the default), this routine is
684/// allowed to rebuild the precompiled preamble if it is found to be
685/// out-of-date.
686///
687/// \param MaxLines When non-zero, the maximum number of lines that
688/// can occur within the preamble.
689///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000690/// \returns If the precompiled preamble can be used, returns a newly-allocated
691/// buffer that should be used in place of the main file when doing so.
692/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000693llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
694 bool AllowRebuild,
695 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000696 CompilerInvocation PreambleInvocation(*Invocation);
697 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
698 PreprocessorOptions &PreprocessorOpts
699 = PreambleInvocation.getPreprocessorOpts();
700
701 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000702 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +0000703 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000704
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000705 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000706 // We couldn't find a preamble in the main source. Clear out the current
707 // preamble, if we have one. It's obviously no good any more.
708 Preamble.clear();
709 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000710 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000711 PreambleFile.clear();
712 }
713 if (CreatedPreambleBuffer)
714 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000715
716 // The next time we actually see a preamble, precompile it.
717 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000718 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000719 }
720
721 if (!Preamble.empty()) {
722 // We've previously computed a preamble. Check whether we have the same
723 // preamble now that we did before, and that there's enough space in
724 // the main-file buffer within the precompiled preamble to fit the
725 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000726 if (Preamble.size() == NewPreamble.second.first &&
727 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000728 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000729 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000730 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000731 // The preamble has not changed. We may be able to re-use the precompiled
732 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000733
Douglas Gregor0e119552010-07-31 00:40:00 +0000734 // Check that none of the files used by the preamble have changed.
735 bool AnyFileChanged = false;
736
737 // First, make a record of those files that have been overridden via
738 // remapping or unsaved_files.
739 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
740 for (PreprocessorOptions::remapped_file_iterator
741 R = PreprocessorOpts.remapped_file_begin(),
742 REnd = PreprocessorOpts.remapped_file_end();
743 !AnyFileChanged && R != REnd;
744 ++R) {
745 struct stat StatBuf;
746 if (stat(R->second.c_str(), &StatBuf)) {
747 // If we can't stat the file we're remapping to, assume that something
748 // horrible happened.
749 AnyFileChanged = true;
750 break;
751 }
Douglas Gregor6481ef12010-07-24 00:38:13 +0000752
Douglas Gregor0e119552010-07-31 00:40:00 +0000753 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
754 StatBuf.st_mtime);
755 }
756 for (PreprocessorOptions::remapped_file_buffer_iterator
757 R = PreprocessorOpts.remapped_file_buffer_begin(),
758 REnd = PreprocessorOpts.remapped_file_buffer_end();
759 !AnyFileChanged && R != REnd;
760 ++R) {
761 // FIXME: Should we actually compare the contents of file->buffer
762 // remappings?
763 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
764 0);
765 }
766
767 // Check whether anything has changed.
768 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
769 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
770 !AnyFileChanged && F != FEnd;
771 ++F) {
772 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
773 = OverriddenFiles.find(F->first());
774 if (Overridden != OverriddenFiles.end()) {
775 // This file was remapped; check whether the newly-mapped file
776 // matches up with the previous mapping.
777 if (Overridden->second != F->second)
778 AnyFileChanged = true;
779 continue;
780 }
781
782 // The file was not remapped; check whether it has changed on disk.
783 struct stat StatBuf;
784 if (stat(F->first(), &StatBuf)) {
785 // If we can't stat the file, assume that something horrible happened.
786 AnyFileChanged = true;
787 } else if (StatBuf.st_size != F->second.first ||
788 StatBuf.st_mtime != F->second.second)
789 AnyFileChanged = true;
790 }
791
792 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000793 // Okay! We can re-use the precompiled preamble.
794
795 // Set the state of the diagnostic object to mimic its state
796 // after parsing the preamble.
797 getDiagnostics().Reset();
798 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
799 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
800 StoredDiagnostics.erase(
801 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
802 StoredDiagnostics.end());
803
804 // Create a version of the main file buffer that is padded to
805 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +0000806 return CreatePaddedMainFileBuffer(NewPreamble.first,
807 CreatedPreambleBuffer,
808 PreambleReservedSize,
809 FrontendOpts.Inputs[0].second);
810 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000811 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000812
813 // If we aren't allowed to rebuild the precompiled preamble, just
814 // return now.
815 if (!AllowRebuild)
816 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000817
818 // We can't reuse the previously-computed preamble. Build a new one.
819 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000820 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000821 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000822 } else if (!AllowRebuild) {
823 // We aren't allowed to rebuild the precompiled preamble; just
824 // return now.
825 return 0;
826 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000827
828 // If the preamble rebuild counter > 1, it's because we previously
829 // failed to build a preamble and we're not yet ready to try
830 // again. Decrement the counter and return a failure.
831 if (PreambleRebuildCounter > 1) {
832 --PreambleRebuildCounter;
833 return 0;
834 }
835
Douglas Gregor4dde7492010-07-23 23:58:40 +0000836 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000837 llvm::Timer *PreambleTimer = 0;
838 if (TimerGroup.get()) {
839 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
840 PreambleTimer->startTimer();
841 Timers.push_back(PreambleTimer);
842 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000843
844 // Create a new buffer that stores the preamble. The buffer also contains
845 // extra space for the original contents of the file (which will be present
846 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +0000847 // grows.
848 PreambleReservedSize = NewPreamble.first->getBufferSize();
849 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000850 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000851 else
Douglas Gregor4dde7492010-07-23 23:58:40 +0000852 PreambleReservedSize *= 2;
853
Douglas Gregord9a30af2010-08-02 20:51:39 +0000854 // Save the preamble text for later; we'll need to compare against it for
855 // subsequent reparses.
856 Preamble.assign(NewPreamble.first->getBufferStart(),
857 NewPreamble.first->getBufferStart()
858 + NewPreamble.second.first);
859 PreambleEndsAtStartOfLine = NewPreamble.second.second;
860
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000861 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +0000862 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000863 FrontendOpts.Inputs[0].second);
864 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +0000865 NewPreamble.first->getBufferStart(), Preamble.size());
866 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000867 ' ', PreambleReservedSize - Preamble.size() - 1);
868 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000869
870 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000871 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000872 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
873
874 // Tell the compiler invocation to generate a temporary precompiled header.
875 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redle98428d2010-08-06 00:35:11 +0000876 // FIXME: Set ChainedPCH unconditionally, once it is ready.
877 if (::getenv("LIBCLANG_CHAINING"))
878 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000879 // FIXME: Generate the precompiled header into memory?
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000880 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000881
882 // Create the compiler instance to use for building the precompiled preamble.
883 CompilerInstance Clang;
884 Clang.setInvocation(&PreambleInvocation);
885 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
886
Douglas Gregor8e984da2010-08-04 16:47:14 +0000887 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000888 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000889 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
890 getDiagnostics(),
891 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000892 Clang.setDiagnosticClient(getDiagnostics().getClient());
893
894 // Create the target instance.
895 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
896 Clang.getTargetOpts()));
897 if (!Clang.hasTarget()) {
898 Clang.takeDiagnosticClient();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000899 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
900 Preamble.clear();
901 if (CreatedPreambleBuffer)
902 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000903 if (PreambleTimer)
904 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000905 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000906 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000907 }
908
909 // Inform the target of the language options.
910 //
911 // FIXME: We shouldn't need to do this, the target should be immutable once
912 // created. This complexity should be lifted elsewhere.
913 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
914
915 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
916 "Invocation must have exactly one source file!");
917 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
918 "FIXME: AST inputs not yet supported here!");
919 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
920 "IR inputs not support here!");
921
922 // Clear out old caches and data.
923 StoredDiagnostics.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +0000924 TopLevelDecls.clear();
925 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000926
927 // Create a file manager object to provide access to and cache the filesystem.
928 Clang.setFileManager(new FileManager);
929
930 // Create the source manager.
931 Clang.setSourceManager(new SourceManager(getDiagnostics()));
932
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000933 llvm::OwningPtr<PrecompilePreambleAction> Act;
934 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000935 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
936 Clang.getFrontendOpts().Inputs[0].first)) {
937 Clang.takeDiagnosticClient();
938 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000939 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
940 Preamble.clear();
941 if (CreatedPreambleBuffer)
942 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000943 if (PreambleTimer)
944 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000945 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000946
Douglas Gregor6481ef12010-07-24 00:38:13 +0000947 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000948 }
949
950 Act->Execute();
951 Act->EndSourceFile();
952 Clang.takeDiagnosticClient();
953 Clang.takeInvocation();
954
Douglas Gregore9db88f2010-08-03 19:06:41 +0000955 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000956 // There were errors parsing the preamble, so no precompiled header was
957 // generated. Forget that we even tried.
958 // FIXME: Should we leave a note for ourselves to try again?
959 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
960 Preamble.clear();
961 if (CreatedPreambleBuffer)
962 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000963 if (PreambleTimer)
964 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +0000965 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000966 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000967 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000968 }
969
970 // Keep track of the preamble we precompiled.
971 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000972 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
973 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +0000974
975 // Keep track of all of the files that the source manager knows about,
976 // so we can verify whether they have changed or not.
977 FilesInPreamble.clear();
978 SourceManager &SourceMgr = Clang.getSourceManager();
979 const llvm::MemoryBuffer *MainFileBuffer
980 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
981 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
982 FEnd = SourceMgr.fileinfo_end();
983 F != FEnd;
984 ++F) {
985 const FileEntry *File = F->second->Entry;
986 if (!File || F->second->getRawBuffer() == MainFileBuffer)
987 continue;
988
989 FilesInPreamble[File->getName()]
990 = std::make_pair(F->second->getSize(), File->getModificationTime());
991 }
992
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000993 if (PreambleTimer)
994 PreambleTimer->stopTimer();
995
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000996 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000997 return CreatePaddedMainFileBuffer(NewPreamble.first,
998 CreatedPreambleBuffer,
999 PreambleReservedSize,
1000 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001001}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001002
Douglas Gregore9db88f2010-08-03 19:06:41 +00001003void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1004 std::vector<Decl *> Resolved;
1005 Resolved.reserve(TopLevelDeclsInPreamble.size());
1006 ExternalASTSource &Source = *getASTContext().getExternalSource();
1007 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1008 // Resolve the declaration ID to an actual declaration, possibly
1009 // deserializing the declaration in the process.
1010 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1011 if (D)
1012 Resolved.push_back(D);
1013 }
1014 TopLevelDeclsInPreamble.clear();
1015 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1016}
1017
1018unsigned ASTUnit::getMaxPCHLevel() const {
1019 if (!getOnlyLocalDecls())
1020 return Decl::MaxPCHLevel;
1021
1022 unsigned Result = 0;
1023 if (isMainFileAST() || SavedMainFileBuffer)
1024 ++Result;
1025 return Result;
1026}
1027
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001028ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1029 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1030 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001031 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001032 bool PrecompilePreamble,
1033 bool CompleteTranslationUnit) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001034 if (!Diags.getPtr()) {
1035 // No diagnostics engine was provided, so create our own diagnostics object
1036 // with the default options.
1037 DiagnosticOptions DiagOpts;
1038 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1039 }
1040
1041 // Create the AST unit.
1042 llvm::OwningPtr<ASTUnit> AST;
1043 AST.reset(new ASTUnit(false));
1044 AST->Diagnostics = Diags;
1045 AST->CaptureDiagnostics = CaptureDiagnostics;
1046 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001047 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001048 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001049 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001050
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001051 if (getenv("LIBCLANG_TIMING"))
1052 AST->TimerGroup.reset(
1053 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1054
1055
Douglas Gregor6481ef12010-07-24 00:38:13 +00001056 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregora5fd5222010-07-28 22:12:37 +00001057 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001058 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1059 AST->PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001060 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001061 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001062
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001063 llvm::Timer *ParsingTimer = 0;
1064 if (AST->TimerGroup.get()) {
1065 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1066 ParsingTimer->startTimer();
1067 AST->Timers.push_back(ParsingTimer);
1068 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001069
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001070 bool Failed = AST->Parse(OverrideMainBuffer);
1071 if (ParsingTimer)
1072 ParsingTimer->stopTimer();
1073
1074 return Failed? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001075}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001076
1077ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1078 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001079 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001080 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001081 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001082 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001083 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001084 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001085 bool PrecompilePreamble,
1086 bool CompleteTranslationUnit) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001087 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001088 // No diagnostics engine was provided, so create our own diagnostics object
1089 // with the default options.
1090 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001091 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +00001092 }
1093
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001094 llvm::SmallVector<const char *, 16> Args;
1095 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1096 Args.insert(Args.end(), ArgBegin, ArgEnd);
1097
1098 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1099 // also want to force it to use clang.
1100 Args.push_back("-fsyntax-only");
1101
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001102 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +00001103 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001104 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001105
1106 // Don't check that inputs exist, they have been remapped.
1107 TheDriver.setCheckInputsExist(false);
1108
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001109 llvm::OwningPtr<driver::Compilation> C(
1110 TheDriver.BuildCompilation(Args.size(), Args.data()));
1111
1112 // We expect to get back exactly one command job, if we didn't something
1113 // failed.
1114 const driver::JobList &Jobs = C->getJobs();
1115 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1116 llvm::SmallString<256> Msg;
1117 llvm::raw_svector_ostream OS(Msg);
1118 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +00001119 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001120 return 0;
1121 }
1122
1123 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1124 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +00001125 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001126 return 0;
1127 }
1128
1129 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001130 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +00001131 CompilerInvocation::CreateFromArgs(*CI,
1132 const_cast<const char **>(CCArgs.data()),
1133 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001134 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001135 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +00001136
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001137 // Override any files that need remapping
1138 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001139 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001140 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001141
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001142 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001143 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001144
Daniel Dunbar19511922010-02-16 01:55:04 +00001145 CI->getFrontendOpts().DisableFree = true;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001146 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001147 CaptureDiagnostics, PrecompilePreamble,
1148 CompleteTranslationUnit);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001149}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001150
1151bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1152 if (!Invocation.get())
1153 return true;
1154
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001155 llvm::Timer *ReparsingTimer = 0;
1156 if (TimerGroup.get()) {
1157 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1158 ReparsingTimer->startTimer();
1159 Timers.push_back(ReparsingTimer);
1160 }
1161
Douglas Gregor0e119552010-07-31 00:40:00 +00001162 // Remap files.
Douglas Gregor0e119552010-07-31 00:40:00 +00001163 Invocation->getPreprocessorOpts().clearRemappedFiles();
1164 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1165 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1166 RemappedFiles[I].second);
1167
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001168 // If we have a preamble file lying around, or if we might try to
1169 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001170 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001171 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor028d3e42010-08-09 20:45:32 +00001172 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001173
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001174 // Clear out the diagnostics state.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001175 if (!OverrideMainBuffer)
1176 getDiagnostics().Reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001177
Douglas Gregor4dde7492010-07-23 23:58:40 +00001178 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001179 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001180 if (ReparsingTimer)
1181 ReparsingTimer->stopTimer();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001182 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001183}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001184
1185void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1186 RemappedFile *RemappedFiles,
1187 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001188 bool IncludeMacros,
1189 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001190 CodeCompleteConsumer &Consumer,
1191 Diagnostic &Diag, LangOptions &LangOpts,
1192 SourceManager &SourceMgr, FileManager &FileMgr,
1193 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1194 if (!Invocation.get())
1195 return;
1196
Douglas Gregor028d3e42010-08-09 20:45:32 +00001197 llvm::Timer *CompletionTimer = 0;
1198 if (TimerGroup.get()) {
1199 llvm::SmallString<128> TimerName;
1200 llvm::raw_svector_ostream TimerNameOut(TimerName);
1201 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1202 << Column;
1203 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1204 CompletionTimer->startTimer();
1205 Timers.push_back(CompletionTimer);
1206 }
1207
Douglas Gregor8e984da2010-08-04 16:47:14 +00001208 CompilerInvocation CCInvocation(*Invocation);
1209 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1210 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001211
1212 FrontendOpts.ShowMacrosInCodeCompletion = IncludeMacros;
1213 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001214 FrontendOpts.CodeCompletionAt.FileName = File;
1215 FrontendOpts.CodeCompletionAt.Line = Line;
1216 FrontendOpts.CodeCompletionAt.Column = Column;
1217
Douglas Gregorb68bc592010-08-05 09:09:23 +00001218 // Turn on spell-checking when performing code completion. It leads
1219 // to better results.
1220 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1221 CCInvocation.getLangOpts().SpellChecking = 1;
1222
Douglas Gregor8e984da2010-08-04 16:47:14 +00001223 // Set the language options appropriately.
1224 LangOpts = CCInvocation.getLangOpts();
1225
1226 CompilerInstance Clang;
1227 Clang.setInvocation(&CCInvocation);
1228 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1229
1230 // Set up diagnostics, capturing any diagnostics produced.
1231 Clang.setDiagnostics(&Diag);
1232 CaptureDroppedDiagnostics Capture(true,
1233 Clang.getDiagnostics(),
1234 StoredDiagnostics);
1235 Clang.setDiagnosticClient(Diag.getClient());
1236
1237 // Create the target instance.
1238 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1239 Clang.getTargetOpts()));
1240 if (!Clang.hasTarget()) {
1241 Clang.takeDiagnosticClient();
1242 Clang.takeInvocation();
1243 }
1244
1245 // Inform the target of the language options.
1246 //
1247 // FIXME: We shouldn't need to do this, the target should be immutable once
1248 // created. This complexity should be lifted elsewhere.
1249 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1250
1251 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1252 "Invocation must have exactly one source file!");
1253 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1254 "FIXME: AST inputs not yet supported here!");
1255 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1256 "IR inputs not support here!");
1257
1258
1259 // Use the source and file managers that we were given.
1260 Clang.setFileManager(&FileMgr);
1261 Clang.setSourceManager(&SourceMgr);
1262
1263 // Remap files.
1264 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001265 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001266 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1267 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1268 RemappedFiles[I].second);
1269
1270 // Use the code completion consumer we were given.
1271 Clang.setCodeCompletionConsumer(&Consumer);
1272
Douglas Gregor028d3e42010-08-09 20:45:32 +00001273 // If we have a precompiled preamble, try to use it. We only allow
1274 // the use of the precompiled preamble if we're if the completion
1275 // point is within the main file, after the end of the precompiled
1276 // preamble.
1277 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1278 if (!PreambleFile.empty()) {
1279 using llvm::sys::FileStatus;
1280 llvm::sys::PathWithStatus CompleteFilePath(File);
1281 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1282 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1283 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1284 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1285 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1286 Line);
1287 }
1288
1289 // If the main file has been overridden due to the use of a preamble,
1290 // make that override happen and introduce the preamble.
1291 if (OverrideMainBuffer) {
1292 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1293 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1294 PreprocessorOpts.PrecompiledPreambleBytes.second
1295 = PreambleEndsAtStartOfLine;
1296 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1297 PreprocessorOpts.DisablePCHValidation = true;
1298
1299 // The stored diagnostics have the old source manager. Copy them
1300 // to our output set of stored diagnostics, updating the source
1301 // manager to the one we were given.
1302 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1303 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1304 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1305 StoredDiagnostics[I].setLocation(Loc);
1306 }
1307 }
1308
Douglas Gregor8e984da2010-08-04 16:47:14 +00001309 llvm::OwningPtr<SyntaxOnlyAction> Act;
1310 Act.reset(new SyntaxOnlyAction);
1311 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1312 Clang.getFrontendOpts().Inputs[0].first)) {
1313 Act->Execute();
1314 Act->EndSourceFile();
1315 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001316
1317 if (CompletionTimer)
1318 CompletionTimer->stopTimer();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001319
1320 // Steal back our resources.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001321 delete OverrideMainBuffer;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001322 Clang.takeFileManager();
1323 Clang.takeSourceManager();
1324 Clang.takeInvocation();
1325 Clang.takeDiagnosticClient();
1326 Clang.takeCodeCompletionConsumer();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001327 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001328}