blob: bbe2ec5bea66eede54239cf506728c661c9a8a3e [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),
53 PreambleRebuildCounter(0), SavedMainFileBuffer(0) {
Douglas Gregor385103b2010-07-30 20:58:08 +000054}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000055
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000056ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000057 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000058 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000059 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000060 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-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 Gregor28233422010-07-27 14:52:07 +000075
76 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000077
78 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
79 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000080}
81
82void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000083 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
84 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000085 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000086}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000087
88namespace {
89
90/// \brief Gathers information from PCHReader that will be used to initialize
91/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +000092class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000093 LangOptions &LangOpt;
94 HeaderSearch &HSI;
95 std::string &TargetTriple;
96 std::string &Predefines;
97 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000099 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Argyrios Kyrtzidis0853a022009-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 Stump1eb44332009-09-09 15:08:12 +0000107
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000108 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
109 LangOpt = LangOpts;
110 return false;
111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000113 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000114 TargetTriple = Triple;
115 return false;
116 }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000118 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000119 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000120 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000125 return false;
126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000128 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000129 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000132 virtual void ReadCounter(unsigned Value) {
133 Counter = Value;
134 }
135};
136
Douglas Gregora88084b2010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000170} // anonymous namespace
171
Douglas Gregora88084b2010-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 Naroff77accc12009-09-03 18:19:54 +0000177const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000178 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000179}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000180
Steve Naroffe19944c2009-10-15 22:23:48 +0000181const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000182 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000183 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000184}
185
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000186ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000187 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000188 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000189 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000190 unsigned NumRemappedFiles,
191 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000192 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
193
Douglas Gregor28019772010-04-05 23:52:57 +0000194 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-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 Gregor28019772010-04-05 23:52:57 +0000198 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000199 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000200
201 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000202 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000203 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000204 AST->FileMgr.reset(new FileManager);
205 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000206 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000207
Douglas Gregora88084b2010-02-18 18:08:43 +0000208 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000209 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000210 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000211
Douglas Gregor4db64a42010-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 Gregor3687e9d2010-04-05 21:10:19 +0000219 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000220 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000221 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000231 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Argyrios Kyrtzidis0853a022009-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 Dunbarbce6f622009-09-03 05:59:50 +0000239 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000240 llvm::OwningPtr<ExternalASTSource> Source;
241
Ted Kremenekfc062212009-10-19 21:44:57 +0000242 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000243 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000244 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
245 Predefines, Counter));
246
247 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000248 case PCHReader::Success:
249 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000251 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000252 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000253 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000254 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000257 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
258
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000259 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000261 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-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 Davis98b7c5c2010-06-11 01:06:47 +0000266 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000267 TargetOpts.CPU = "";
268 TargetOpts.Features.clear();
269 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-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 Dunbar31b87d82009-09-21 03:03:39 +0000274 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000275 Preprocessor &PP = *AST->PP.get();
276
Daniel Dunbard5b61262009-09-21 03:03:47 +0000277 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000278 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000279 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000281 // Create and initialize the ASTContext.
282
283 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000284 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000285 *AST->Target.get(),
286 PP.getIdentifierTable(),
287 PP.getSelectorTable(),
288 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000289 /* size_reserve = */0));
290 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Daniel Dunbarcc318932009-09-03 05:59:35 +0000292 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Argyrios Kyrtzidis0853a022009-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 Dunbarcc318932009-09-03 05:59:35 +0000297 Source.reset(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000298 Context.setExternalSource(Source);
299
Mike Stump1eb44332009-09-09 15:08:12 +0000300 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000301}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000302
303namespace {
304
Daniel Dunbarf772d1e2009-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 Kremenekda5a4282010-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 Gregoreb8837b2010-08-03 19:06:41 +0000320 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000321 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000322 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000323
324 // We're not interested in "interesting" decls.
325 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000326};
327
328class TopLevelDeclTrackerAction : public ASTFrontendAction {
329public:
330 ASTUnit &Unit;
331
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000332 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
333 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000334 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000335 }
336
337public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000338 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
339
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000340 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000341 virtual bool usesCompleteTranslationUnit() {
342 return Unit.isCompleteTranslationUnit();
343 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000344};
345
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000346class PrecompilePreambleConsumer : public PCHGenerator {
347 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000348 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000349
350public:
351 PrecompilePreambleConsumer(ASTUnit &Unit,
352 const Preprocessor &PP, bool Chaining,
353 const char *isysroot, llvm::raw_ostream *Out)
354 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
355
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000356 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000357 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
358 Decl *D = *it;
359 // FIXME: Currently ObjC method declarations are incorrectly being
360 // reported as top-level declarations, even though their DeclContext
361 // is the containing ObjC @interface/@implementation. This is a
362 // fundamental problem in the parser right now.
363 if (isa<ObjCMethodDecl>(D))
364 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000365 TopLevelDecls.push_back(D);
366 }
367 }
368
369 virtual void HandleTranslationUnit(ASTContext &Ctx) {
370 PCHGenerator::HandleTranslationUnit(Ctx);
371 if (!Unit.getDiagnostics().hasErrorOccurred()) {
372 // Translate the top-level declarations we captured during
373 // parsing into declaration IDs in the precompiled
374 // preamble. This will allow us to deserialize those top-level
375 // declarations when requested.
376 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
377 Unit.addTopLevelDeclFromPreamble(
378 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000379 }
380 }
381};
382
383class PrecompilePreambleAction : public ASTFrontendAction {
384 ASTUnit &Unit;
385
386public:
387 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
388
389 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
390 llvm::StringRef InFile) {
391 std::string Sysroot;
392 llvm::raw_ostream *OS = 0;
393 bool Chaining;
394 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
395 OS, Chaining))
396 return 0;
397
398 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
399 Sysroot.c_str() : 0;
400 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
401 isysroot, OS);
402 }
403
404 virtual bool hasCodeCompletionSupport() const { return false; }
405 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000406 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000407};
408
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000409}
410
Douglas Gregorabc563f2010-07-19 21:46:24 +0000411/// Parse the source file into a translation unit using the given compiler
412/// invocation, replacing the current translation unit.
413///
414/// \returns True if a failure occurred that causes the ASTUnit not to
415/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000416bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000417 delete SavedMainFileBuffer;
418 SavedMainFileBuffer = 0;
419
Douglas Gregorabc563f2010-07-19 21:46:24 +0000420 if (!Invocation.get())
421 return true;
422
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000423 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000424 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000425 Clang.setInvocation(Invocation.take());
426 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
427
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000428 // Set up diagnostics, capturing any diagnostics that would
429 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000430 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000431 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
432 getDiagnostics(),
433 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000434 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000435
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000436 // Create the target instance.
437 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
438 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000439 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000440 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000441 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000442 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000443
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000444 // Inform the target of the language options.
445 //
446 // FIXME: We shouldn't need to do this, the target should be immutable once
447 // created. This complexity should be lifted elsewhere.
448 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000449
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000450 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
451 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000452 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000453 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000454 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
455 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000456
Douglas Gregorabc563f2010-07-19 21:46:24 +0000457 // Configure the various subsystems.
458 // FIXME: Should we retain the previous file manager?
459 FileMgr.reset(new FileManager);
460 SourceMgr.reset(new SourceManager(getDiagnostics()));
461 Ctx.reset();
462 PP.reset();
463
464 // Clear out old caches and data.
465 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000466 CleanTemporaryFiles();
467 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000468
469 if (!OverrideMainBuffer)
470 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000471
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000472 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000473 Clang.setFileManager(&getFileManager());
474
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000475 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000476 Clang.setSourceManager(&getSourceManager());
477
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000478 // If the main file has been overridden due to the use of a preamble,
479 // make that override happen and introduce the preamble.
480 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000481 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000482 if (OverrideMainBuffer) {
483 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
484 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
485 PreprocessorOpts.PrecompiledPreambleBytes.second
486 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000487 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000488 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000489 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000490
491 // Keep track of the override buffer;
492 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000493
494 // The stored diagnostic has the old source manager in it; update
495 // the locations to refer into the new source manager. Since we've
496 // been careful to make sure that the source manager's state
497 // before and after are identical, so that we can reuse the source
498 // location itself.
499 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
500 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
501 getSourceManager());
502 StoredDiagnostics[I].setLocation(Loc);
503 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000504 }
505
Douglas Gregorabc563f2010-07-19 21:46:24 +0000506 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
507 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000508 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000509 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000510 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000511
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000512 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000513
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000514 // Steal the created target, context, and preprocessor, and take back the
515 // source and file managers.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000516 Ctx.reset(Clang.takeASTContext());
517 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000518 Clang.takeSourceManager();
519 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000520 Target.reset(Clang.takeTarget());
521
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000522 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000523
524 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000525 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000526 PreprocessorOpts.eraseRemappedFile(
527 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000528 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
529 }
530
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000531 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000532
533 Invocation.reset(Clang.takeInvocation());
534 return false;
535
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000536error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000537 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000538 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000539 PreprocessorOpts.eraseRemappedFile(
540 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000541 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000542 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000543 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000544
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000545 Clang.takeSourceManager();
546 Clang.takeFileManager();
547 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000548 Invocation.reset(Clang.takeInvocation());
549 return true;
550}
551
Douglas Gregor44c181a2010-07-23 00:33:23 +0000552/// \brief Simple function to retrieve a path for a preamble precompiled header.
553static std::string GetPreamblePCHPath() {
554 // FIXME: This is lame; sys::Path should provide this function (in particular,
555 // it should know how to find the temporary files dir).
556 // FIXME: This is really lame. I copied this code from the Driver!
557 std::string Error;
558 const char *TmpDir = ::getenv("TMPDIR");
559 if (!TmpDir)
560 TmpDir = ::getenv("TEMP");
561 if (!TmpDir)
562 TmpDir = ::getenv("TMP");
563 if (!TmpDir)
564 TmpDir = "/tmp";
565 llvm::sys::Path P(TmpDir);
566 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000567 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000568 if (P.createTemporaryFileOnDisk())
569 return std::string();
570
Douglas Gregor6bf18302010-08-11 13:06:56 +0000571 fprintf(stderr, "Preamble file: %s\n", P.str().c_str());
Douglas Gregor44c181a2010-07-23 00:33:23 +0000572 return P.str();
573}
574
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000575/// \brief Compute the preamble for the main file, providing the source buffer
576/// that corresponds to the main file along with a pair (bytes, start-of-line)
577/// that describes the preamble.
578std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000579ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
580 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000581 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000582 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000583 = Invocation.getPreprocessorOpts();
584 CreatedBuffer = false;
585
Douglas Gregor44c181a2010-07-23 00:33:23 +0000586 // Try to determine if the main file has been remapped, either from the
587 // command line (to another file) or directly through the compiler invocation
588 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000589 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000590 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
591 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
592 // Check whether there is a file-file remapping of the main file
593 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000594 M = PreprocessorOpts.remapped_file_begin(),
595 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000596 M != E;
597 ++M) {
598 llvm::sys::PathWithStatus MPath(M->first);
599 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
600 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
601 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000602 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000603 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000604 CreatedBuffer = false;
605 }
606
Douglas Gregor44c181a2010-07-23 00:33:23 +0000607 Buffer = llvm::MemoryBuffer::getFile(M->second);
608 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000609 return std::make_pair((llvm::MemoryBuffer*)0,
610 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000611 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000612
Douglas Gregor175c4a92010-07-23 23:58:40 +0000613 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000614 M = PreprocessorOpts.eraseRemappedFile(M);
615 E = PreprocessorOpts.remapped_file_end();
616 }
617 }
618 }
619
620 // Check whether there is a file-buffer remapping. It supercedes the
621 // file-file remapping.
622 for (PreprocessorOptions::remapped_file_buffer_iterator
623 M = PreprocessorOpts.remapped_file_buffer_begin(),
624 E = PreprocessorOpts.remapped_file_buffer_end();
625 M != E;
626 ++M) {
627 llvm::sys::PathWithStatus MPath(M->first);
628 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
629 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
630 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000631 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000632 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000633 CreatedBuffer = false;
634 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000635
Douglas Gregor175c4a92010-07-23 23:58:40 +0000636 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
637
638 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000639 M = PreprocessorOpts.eraseRemappedFile(M);
640 E = PreprocessorOpts.remapped_file_buffer_end();
641 }
642 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000643 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000644 }
645
646 // If the main source file was not remapped, load it now.
647 if (!Buffer) {
648 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
649 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000650 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000651
652 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000653 }
654
Douglas Gregordf95a132010-08-09 20:45:32 +0000655 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000656}
657
Douglas Gregor754f3492010-07-24 00:38:13 +0000658static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
659 bool DeleteOld,
660 unsigned NewSize,
661 llvm::StringRef NewName) {
662 llvm::MemoryBuffer *Result
663 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
664 memcpy(const_cast<char*>(Result->getBufferStart()),
665 Old->getBufferStart(), Old->getBufferSize());
666 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000667 ' ', NewSize - Old->getBufferSize() - 1);
668 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000669
670 if (DeleteOld)
671 delete Old;
672
673 return Result;
674}
675
Douglas Gregor175c4a92010-07-23 23:58:40 +0000676/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
677/// the source file.
678///
679/// This routine will compute the preamble of the main source file. If a
680/// non-trivial preamble is found, it will precompile that preamble into a
681/// precompiled header so that the precompiled preamble can be used to reduce
682/// reparsing time. If a precompiled preamble has already been constructed,
683/// this routine will determine if it is still valid and, if so, avoid
684/// rebuilding the precompiled preamble.
685///
Douglas Gregordf95a132010-08-09 20:45:32 +0000686/// \param AllowRebuild When true (the default), this routine is
687/// allowed to rebuild the precompiled preamble if it is found to be
688/// out-of-date.
689///
690/// \param MaxLines When non-zero, the maximum number of lines that
691/// can occur within the preamble.
692///
Douglas Gregor754f3492010-07-24 00:38:13 +0000693/// \returns If the precompiled preamble can be used, returns a newly-allocated
694/// buffer that should be used in place of the main file when doing so.
695/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000696llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
697 bool AllowRebuild,
698 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000699 CompilerInvocation PreambleInvocation(*Invocation);
700 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
701 PreprocessorOptions &PreprocessorOpts
702 = PreambleInvocation.getPreprocessorOpts();
703
704 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000705 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000706 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000707
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000708 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000709 // We couldn't find a preamble in the main source. Clear out the current
710 // preamble, if we have one. It's obviously no good any more.
711 Preamble.clear();
712 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000713 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000714 PreambleFile.clear();
715 }
716 if (CreatedPreambleBuffer)
717 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000718
719 // The next time we actually see a preamble, precompile it.
720 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000721 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000722 }
723
724 if (!Preamble.empty()) {
725 // We've previously computed a preamble. Check whether we have the same
726 // preamble now that we did before, and that there's enough space in
727 // the main-file buffer within the precompiled preamble to fit the
728 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000729 if (Preamble.size() == NewPreamble.second.first &&
730 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000731 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000732 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000733 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000734 // The preamble has not changed. We may be able to re-use the precompiled
735 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000736
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000737 // Check that none of the files used by the preamble have changed.
738 bool AnyFileChanged = false;
739
740 // First, make a record of those files that have been overridden via
741 // remapping or unsaved_files.
742 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
743 for (PreprocessorOptions::remapped_file_iterator
744 R = PreprocessorOpts.remapped_file_begin(),
745 REnd = PreprocessorOpts.remapped_file_end();
746 !AnyFileChanged && R != REnd;
747 ++R) {
748 struct stat StatBuf;
749 if (stat(R->second.c_str(), &StatBuf)) {
750 // If we can't stat the file we're remapping to, assume that something
751 // horrible happened.
752 AnyFileChanged = true;
753 break;
754 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000755
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000756 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
757 StatBuf.st_mtime);
758 }
759 for (PreprocessorOptions::remapped_file_buffer_iterator
760 R = PreprocessorOpts.remapped_file_buffer_begin(),
761 REnd = PreprocessorOpts.remapped_file_buffer_end();
762 !AnyFileChanged && R != REnd;
763 ++R) {
764 // FIXME: Should we actually compare the contents of file->buffer
765 // remappings?
766 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
767 0);
768 }
769
770 // Check whether anything has changed.
771 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
772 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
773 !AnyFileChanged && F != FEnd;
774 ++F) {
775 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
776 = OverriddenFiles.find(F->first());
777 if (Overridden != OverriddenFiles.end()) {
778 // This file was remapped; check whether the newly-mapped file
779 // matches up with the previous mapping.
780 if (Overridden->second != F->second)
781 AnyFileChanged = true;
782 continue;
783 }
784
785 // The file was not remapped; check whether it has changed on disk.
786 struct stat StatBuf;
787 if (stat(F->first(), &StatBuf)) {
788 // If we can't stat the file, assume that something horrible happened.
789 AnyFileChanged = true;
790 } else if (StatBuf.st_size != F->second.first ||
791 StatBuf.st_mtime != F->second.second)
792 AnyFileChanged = true;
793 }
794
795 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000796 // Okay! We can re-use the precompiled preamble.
797
798 // Set the state of the diagnostic object to mimic its state
799 // after parsing the preamble.
800 getDiagnostics().Reset();
801 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
802 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
803 StoredDiagnostics.erase(
804 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
805 StoredDiagnostics.end());
806
807 // Create a version of the main file buffer that is padded to
808 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000809 return CreatePaddedMainFileBuffer(NewPreamble.first,
810 CreatedPreambleBuffer,
811 PreambleReservedSize,
812 FrontendOpts.Inputs[0].second);
813 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000814 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000815
816 // If we aren't allowed to rebuild the precompiled preamble, just
817 // return now.
818 if (!AllowRebuild)
819 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000820
821 // We can't reuse the previously-computed preamble. Build a new one.
822 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +0000823 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000824 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +0000825 } else if (!AllowRebuild) {
826 // We aren't allowed to rebuild the precompiled preamble; just
827 // return now.
828 return 0;
829 }
Douglas Gregoreababfb2010-08-04 05:53:38 +0000830
831 // If the preamble rebuild counter > 1, it's because we previously
832 // failed to build a preamble and we're not yet ready to try
833 // again. Decrement the counter and return a failure.
834 if (PreambleRebuildCounter > 1) {
835 --PreambleRebuildCounter;
836 return 0;
837 }
838
Douglas Gregor175c4a92010-07-23 23:58:40 +0000839 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +0000840 llvm::Timer *PreambleTimer = 0;
841 if (TimerGroup.get()) {
842 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
843 PreambleTimer->startTimer();
844 Timers.push_back(PreambleTimer);
845 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000846
847 // Create a new buffer that stores the preamble. The buffer also contains
848 // extra space for the original contents of the file (which will be present
849 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +0000850 // grows.
851 PreambleReservedSize = NewPreamble.first->getBufferSize();
852 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000853 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000854 else
Douglas Gregor175c4a92010-07-23 23:58:40 +0000855 PreambleReservedSize *= 2;
856
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000857 // Save the preamble text for later; we'll need to compare against it for
858 // subsequent reparses.
859 Preamble.assign(NewPreamble.first->getBufferStart(),
860 NewPreamble.first->getBufferStart()
861 + NewPreamble.second.first);
862 PreambleEndsAtStartOfLine = NewPreamble.second.second;
863
Douglas Gregor44c181a2010-07-23 00:33:23 +0000864 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +0000865 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +0000866 FrontendOpts.Inputs[0].second);
867 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +0000868 NewPreamble.first->getBufferStart(), Preamble.size());
869 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000870 ' ', PreambleReservedSize - Preamble.size() - 1);
871 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +0000872
873 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000874 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000875 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
876
877 // Tell the compiler invocation to generate a temporary precompiled header.
878 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +0000879 // FIXME: Set ChainedPCH unconditionally, once it is ready.
880 if (::getenv("LIBCLANG_CHAINING"))
881 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000882 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +0000883 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000884
885 // Create the compiler instance to use for building the precompiled preamble.
886 CompilerInstance Clang;
887 Clang.setInvocation(&PreambleInvocation);
888 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
889
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000890 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000891 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000892 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
893 getDiagnostics(),
894 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000895 Clang.setDiagnosticClient(getDiagnostics().getClient());
896
897 // Create the target instance.
898 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
899 Clang.getTargetOpts()));
900 if (!Clang.hasTarget()) {
901 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000902 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
903 Preamble.clear();
904 if (CreatedPreambleBuffer)
905 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000906 if (PreambleTimer)
907 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000908 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +0000909 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000910 }
911
912 // Inform the target of the language options.
913 //
914 // FIXME: We shouldn't need to do this, the target should be immutable once
915 // created. This complexity should be lifted elsewhere.
916 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
917
918 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
919 "Invocation must have exactly one source file!");
920 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
921 "FIXME: AST inputs not yet supported here!");
922 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
923 "IR inputs not support here!");
924
925 // Clear out old caches and data.
926 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000927 TopLevelDecls.clear();
928 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000929
930 // Create a file manager object to provide access to and cache the filesystem.
931 Clang.setFileManager(new FileManager);
932
933 // Create the source manager.
934 Clang.setSourceManager(new SourceManager(getDiagnostics()));
935
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000936 llvm::OwningPtr<PrecompilePreambleAction> Act;
937 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +0000938 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
939 Clang.getFrontendOpts().Inputs[0].first)) {
940 Clang.takeDiagnosticClient();
941 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000942 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
943 Preamble.clear();
944 if (CreatedPreambleBuffer)
945 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000946 if (PreambleTimer)
947 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000948 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +0000949
Douglas Gregor754f3492010-07-24 00:38:13 +0000950 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000951 }
952
953 Act->Execute();
954 Act->EndSourceFile();
955 Clang.takeDiagnosticClient();
956 Clang.takeInvocation();
957
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000958 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000959 // There were errors parsing the preamble, so no precompiled header was
960 // generated. Forget that we even tried.
961 // FIXME: Should we leave a note for ourselves to try again?
962 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
963 Preamble.clear();
964 if (CreatedPreambleBuffer)
965 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000966 if (PreambleTimer)
967 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000968 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000969 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +0000970 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000971 }
972
973 // Keep track of the preamble we precompiled.
974 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000975 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
976 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000977
978 // Keep track of all of the files that the source manager knows about,
979 // so we can verify whether they have changed or not.
980 FilesInPreamble.clear();
981 SourceManager &SourceMgr = Clang.getSourceManager();
982 const llvm::MemoryBuffer *MainFileBuffer
983 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
984 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
985 FEnd = SourceMgr.fileinfo_end();
986 F != FEnd;
987 ++F) {
988 const FileEntry *File = F->second->Entry;
989 if (!File || F->second->getRawBuffer() == MainFileBuffer)
990 continue;
991
992 FilesInPreamble[File->getName()]
993 = std::make_pair(F->second->getSize(), File->getModificationTime());
994 }
995
Douglas Gregor385103b2010-07-30 20:58:08 +0000996 if (PreambleTimer)
997 PreambleTimer->stopTimer();
998
Douglas Gregoreababfb2010-08-04 05:53:38 +0000999 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001000 return CreatePaddedMainFileBuffer(NewPreamble.first,
1001 CreatedPreambleBuffer,
1002 PreambleReservedSize,
1003 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001004}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001005
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001006void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1007 std::vector<Decl *> Resolved;
1008 Resolved.reserve(TopLevelDeclsInPreamble.size());
1009 ExternalASTSource &Source = *getASTContext().getExternalSource();
1010 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1011 // Resolve the declaration ID to an actual declaration, possibly
1012 // deserializing the declaration in the process.
1013 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1014 if (D)
1015 Resolved.push_back(D);
1016 }
1017 TopLevelDeclsInPreamble.clear();
1018 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1019}
1020
1021unsigned ASTUnit::getMaxPCHLevel() const {
1022 if (!getOnlyLocalDecls())
1023 return Decl::MaxPCHLevel;
1024
1025 unsigned Result = 0;
1026 if (isMainFileAST() || SavedMainFileBuffer)
1027 ++Result;
1028 return Result;
1029}
1030
Douglas Gregorabc563f2010-07-19 21:46:24 +00001031ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1032 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1033 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001034 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001035 bool PrecompilePreamble,
1036 bool CompleteTranslationUnit) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001037 if (!Diags.getPtr()) {
1038 // No diagnostics engine was provided, so create our own diagnostics object
1039 // with the default options.
1040 DiagnosticOptions DiagOpts;
1041 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1042 }
1043
1044 // Create the AST unit.
1045 llvm::OwningPtr<ASTUnit> AST;
1046 AST.reset(new ASTUnit(false));
1047 AST->Diagnostics = Diags;
1048 AST->CaptureDiagnostics = CaptureDiagnostics;
1049 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001050 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001051 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001052 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001053
Douglas Gregor385103b2010-07-30 20:58:08 +00001054 if (getenv("LIBCLANG_TIMING"))
1055 AST->TimerGroup.reset(
1056 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1057
1058
Douglas Gregor754f3492010-07-24 00:38:13 +00001059 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001060 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001061 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1062 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001063 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001064 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001065
Douglas Gregor385103b2010-07-30 20:58:08 +00001066 llvm::Timer *ParsingTimer = 0;
1067 if (AST->TimerGroup.get()) {
1068 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1069 ParsingTimer->startTimer();
1070 AST->Timers.push_back(ParsingTimer);
1071 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001072
Douglas Gregor385103b2010-07-30 20:58:08 +00001073 bool Failed = AST->Parse(OverrideMainBuffer);
1074 if (ParsingTimer)
1075 ParsingTimer->stopTimer();
1076
1077 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001078}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001079
1080ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1081 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001082 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001083 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001084 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001085 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001086 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001087 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001088 bool PrecompilePreamble,
1089 bool CompleteTranslationUnit) {
Douglas Gregor28019772010-04-05 23:52:57 +00001090 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001091 // No diagnostics engine was provided, so create our own diagnostics object
1092 // with the default options.
1093 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001094 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001095 }
1096
Daniel Dunbar7b556682009-12-02 03:23:45 +00001097 llvm::SmallVector<const char *, 16> Args;
1098 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1099 Args.insert(Args.end(), ArgBegin, ArgEnd);
1100
1101 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1102 // also want to force it to use clang.
1103 Args.push_back("-fsyntax-only");
1104
Daniel Dunbar869824e2009-12-13 03:46:13 +00001105 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001106 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001107 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001108
1109 // Don't check that inputs exist, they have been remapped.
1110 TheDriver.setCheckInputsExist(false);
1111
Daniel Dunbar7b556682009-12-02 03:23:45 +00001112 llvm::OwningPtr<driver::Compilation> C(
1113 TheDriver.BuildCompilation(Args.size(), Args.data()));
1114
1115 // We expect to get back exactly one command job, if we didn't something
1116 // failed.
1117 const driver::JobList &Jobs = C->getJobs();
1118 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1119 llvm::SmallString<256> Msg;
1120 llvm::raw_svector_ostream OS(Msg);
1121 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001122 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001123 return 0;
1124 }
1125
1126 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1127 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001128 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001129 return 0;
1130 }
1131
1132 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001133 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001134 CompilerInvocation::CreateFromArgs(*CI,
1135 const_cast<const char **>(CCArgs.data()),
1136 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001137 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001138 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001139
Douglas Gregor4db64a42010-01-23 00:14:00 +00001140 // Override any files that need remapping
1141 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001142 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001143 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001144
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001145 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001146 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001147
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001148 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001149 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001150 CaptureDiagnostics, PrecompilePreamble,
1151 CompleteTranslationUnit);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001152}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001153
1154bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1155 if (!Invocation.get())
1156 return true;
1157
Douglas Gregor385103b2010-07-30 20:58:08 +00001158 llvm::Timer *ReparsingTimer = 0;
1159 if (TimerGroup.get()) {
1160 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1161 ReparsingTimer->startTimer();
1162 Timers.push_back(ReparsingTimer);
1163 }
1164
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001165 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001166 Invocation->getPreprocessorOpts().clearRemappedFiles();
1167 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1168 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1169 RemappedFiles[I].second);
1170
Douglas Gregoreababfb2010-08-04 05:53:38 +00001171 // If we have a preamble file lying around, or if we might try to
1172 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001173 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001174 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001175 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001176
Douglas Gregorabc563f2010-07-19 21:46:24 +00001177 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001178 if (!OverrideMainBuffer)
1179 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001180
Douglas Gregor175c4a92010-07-23 23:58:40 +00001181 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001182 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001183 if (ReparsingTimer)
1184 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001185 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001186}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001187
1188void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1189 RemappedFile *RemappedFiles,
1190 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001191 bool IncludeMacros,
1192 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001193 CodeCompleteConsumer &Consumer,
1194 Diagnostic &Diag, LangOptions &LangOpts,
1195 SourceManager &SourceMgr, FileManager &FileMgr,
1196 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1197 if (!Invocation.get())
1198 return;
1199
Douglas Gregordf95a132010-08-09 20:45:32 +00001200 llvm::Timer *CompletionTimer = 0;
1201 if (TimerGroup.get()) {
1202 llvm::SmallString<128> TimerName;
1203 llvm::raw_svector_ostream TimerNameOut(TimerName);
1204 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1205 << Column;
1206 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1207 CompletionTimer->startTimer();
1208 Timers.push_back(CompletionTimer);
1209 }
1210
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001211 CompilerInvocation CCInvocation(*Invocation);
1212 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1213 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001214
1215 FrontendOpts.ShowMacrosInCodeCompletion = IncludeMacros;
1216 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001217 FrontendOpts.CodeCompletionAt.FileName = File;
1218 FrontendOpts.CodeCompletionAt.Line = Line;
1219 FrontendOpts.CodeCompletionAt.Column = Column;
1220
Douglas Gregorcee235c2010-08-05 09:09:23 +00001221 // Turn on spell-checking when performing code completion. It leads
1222 // to better results.
1223 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1224 CCInvocation.getLangOpts().SpellChecking = 1;
1225
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001226 // Set the language options appropriately.
1227 LangOpts = CCInvocation.getLangOpts();
1228
1229 CompilerInstance Clang;
1230 Clang.setInvocation(&CCInvocation);
1231 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1232
1233 // Set up diagnostics, capturing any diagnostics produced.
1234 Clang.setDiagnostics(&Diag);
1235 CaptureDroppedDiagnostics Capture(true,
1236 Clang.getDiagnostics(),
1237 StoredDiagnostics);
1238 Clang.setDiagnosticClient(Diag.getClient());
1239
1240 // Create the target instance.
1241 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1242 Clang.getTargetOpts()));
1243 if (!Clang.hasTarget()) {
1244 Clang.takeDiagnosticClient();
1245 Clang.takeInvocation();
1246 }
1247
1248 // Inform the target of the language options.
1249 //
1250 // FIXME: We shouldn't need to do this, the target should be immutable once
1251 // created. This complexity should be lifted elsewhere.
1252 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1253
1254 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1255 "Invocation must have exactly one source file!");
1256 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1257 "FIXME: AST inputs not yet supported here!");
1258 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1259 "IR inputs not support here!");
1260
1261
1262 // Use the source and file managers that we were given.
1263 Clang.setFileManager(&FileMgr);
1264 Clang.setSourceManager(&SourceMgr);
1265
1266 // Remap files.
1267 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001268 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001269 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1270 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1271 RemappedFiles[I].second);
1272
1273 // Use the code completion consumer we were given.
1274 Clang.setCodeCompletionConsumer(&Consumer);
1275
Douglas Gregordf95a132010-08-09 20:45:32 +00001276 // If we have a precompiled preamble, try to use it. We only allow
1277 // the use of the precompiled preamble if we're if the completion
1278 // point is within the main file, after the end of the precompiled
1279 // preamble.
1280 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1281 if (!PreambleFile.empty()) {
1282 using llvm::sys::FileStatus;
1283 llvm::sys::PathWithStatus CompleteFilePath(File);
1284 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1285 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1286 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1287 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1288 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1289 Line);
1290 }
1291
1292 // If the main file has been overridden due to the use of a preamble,
1293 // make that override happen and introduce the preamble.
1294 if (OverrideMainBuffer) {
1295 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1296 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1297 PreprocessorOpts.PrecompiledPreambleBytes.second
1298 = PreambleEndsAtStartOfLine;
1299 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1300 PreprocessorOpts.DisablePCHValidation = true;
1301
1302 // The stored diagnostics have the old source manager. Copy them
1303 // to our output set of stored diagnostics, updating the source
1304 // manager to the one we were given.
1305 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1306 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1307 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1308 StoredDiagnostics[I].setLocation(Loc);
1309 }
1310 }
1311
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001312 llvm::OwningPtr<SyntaxOnlyAction> Act;
1313 Act.reset(new SyntaxOnlyAction);
1314 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1315 Clang.getFrontendOpts().Inputs[0].first)) {
1316 Act->Execute();
1317 Act->EndSourceFile();
1318 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001319
1320 if (CompletionTimer)
1321 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001322
1323 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001324 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001325 Clang.takeFileManager();
1326 Clang.takeSourceManager();
1327 Clang.takeInvocation();
1328 Clang.takeDiagnosticClient();
1329 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001330 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001331}