blob: 7ff3cdc5b9a0600eefd3bf210fa48f180ba56cd0 [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"
15#include "clang/Frontend/PCHReader.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"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000033#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000034#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000035#include "llvm/System/Path.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000036#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000037#include <cstdio>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000038using namespace clang;
39
Douglas Gregord03e8232010-04-05 21:10:19 +000040ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000041 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
42 ConcurrencyCheckValue(CheckUnlocked) { }
Douglas Gregord03e8232010-04-05 21:10:19 +000043
Daniel Dunbar764c0822009-12-01 09:51:01 +000044ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000045 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000046 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000047 if (!PreambleFile.empty())
48 PreambleFile.eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000049
50 // Free the buffers associated with remapped files. We are required to
51 // perform this operation here because we explicitly request that the
52 // compiler instance *not* free these buffers for each invocation of the
53 // parser.
54 if (Invocation.get()) {
55 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
56 for (PreprocessorOptions::remapped_file_buffer_iterator
57 FB = PPOpts.remapped_file_buffer_begin(),
58 FBEnd = PPOpts.remapped_file_buffer_end();
59 FB != FBEnd;
60 ++FB)
61 delete FB->second;
62 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +000063}
64
65void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000066 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
67 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000068 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000069}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000070
71namespace {
72
73/// \brief Gathers information from PCHReader that will be used to initialize
74/// a Preprocessor.
Benjamin Kramer16634c22009-11-28 10:07:24 +000075class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000076 LangOptions &LangOpt;
77 HeaderSearch &HSI;
78 std::string &TargetTriple;
79 std::string &Predefines;
80 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +000081
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000082 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +000083
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000084public:
85 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
86 std::string &TargetTriple, std::string &Predefines,
87 unsigned &Counter)
88 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
89 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +000090
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000091 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
92 LangOpt = LangOpts;
93 return false;
94 }
Mike Stump11289f42009-09-09 15:08:12 +000095
Daniel Dunbar20a682d2009-11-11 00:52:11 +000096 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000097 TargetTriple = Triple;
98 return false;
99 }
Mike Stump11289f42009-09-09 15:08:12 +0000100
Sebastian Redl8b41f302010-07-14 23:29:55 +0000101 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000102 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000103 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000104 Predefines = Buffers[0].Data;
105 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
106 Predefines += Buffers[I].Data;
107 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000108 return false;
109 }
Mike Stump11289f42009-09-09 15:08:12 +0000110
Douglas Gregora2f49452010-03-16 19:09:18 +0000111 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000112 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
113 }
Mike Stump11289f42009-09-09 15:08:12 +0000114
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000115 virtual void ReadCounter(unsigned Value) {
116 Counter = Value;
117 }
118};
119
Douglas Gregor33cdd812010-02-18 18:08:43 +0000120class StoredDiagnosticClient : public DiagnosticClient {
121 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
122
123public:
124 explicit StoredDiagnosticClient(
125 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
126 : StoredDiags(StoredDiags) { }
127
128 virtual void HandleDiagnostic(Diagnostic::Level Level,
129 const DiagnosticInfo &Info);
130};
131
132/// \brief RAII object that optionally captures diagnostics, if
133/// there is no diagnostic client to capture them already.
134class CaptureDroppedDiagnostics {
135 Diagnostic &Diags;
136 StoredDiagnosticClient Client;
137 DiagnosticClient *PreviousClient;
138
139public:
140 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
141 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
142 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
143 {
144 if (RequestCapture || Diags.getClient() == 0)
145 Diags.setClient(&Client);
146 }
147
148 ~CaptureDroppedDiagnostics() {
149 Diags.setClient(PreviousClient);
150 }
151};
152
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000153} // anonymous namespace
154
Douglas Gregor33cdd812010-02-18 18:08:43 +0000155void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
156 const DiagnosticInfo &Info) {
157 StoredDiags.push_back(StoredDiagnostic(Level, Info));
158}
159
Steve Naroffc0683b92009-09-03 18:19:54 +0000160const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000161 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000162}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000163
Steve Naroff44cd60e2009-10-15 22:23:48 +0000164const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbara18f9582009-12-02 21:47:43 +0000165 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer2ecf8eb2010-01-30 16:23:25 +0000166 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000167}
168
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000169ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000170 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000171 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000172 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000173 unsigned NumRemappedFiles,
174 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000175 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
176
Douglas Gregor7f95d262010-04-05 23:52:57 +0000177 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000178 // No diagnostics engine was provided, so create our own diagnostics object
179 // with the default options.
180 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000181 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000182 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000183
184 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000185 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000186 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000187 AST->FileMgr.reset(new FileManager);
188 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000189 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000190
Douglas Gregor33cdd812010-02-18 18:08:43 +0000191 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000192 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000193 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000194
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000195 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
196 // Create the file entry for the file that we're mapping from.
197 const FileEntry *FromFile
198 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
199 RemappedFiles[I].second->getBufferSize(),
200 0);
201 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000202 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000203 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000204 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000205 continue;
206 }
207
208 // Override the contents of the "from" file with the contents of
209 // the "to" file.
210 AST->getSourceManager().overrideFileContents(FromFile,
211 RemappedFiles[I].second);
212 }
213
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000214 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000215
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000216 LangOptions LangInfo;
217 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
218 std::string TargetTriple;
219 std::string Predefines;
220 unsigned Counter;
221
Daniel Dunbar3a0637b2009-09-03 05:59:50 +0000222 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000223 llvm::OwningPtr<ExternalASTSource> Source;
224
Ted Kremenek428c6372009-10-19 21:44:57 +0000225 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000226 AST->getDiagnostics()));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000227 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
228 Predefines, Counter));
229
230 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000231 case PCHReader::Success:
232 break;
Mike Stump11289f42009-09-09 15:08:12 +0000233
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000234 case PCHReader::Failure:
Argyrios Kyrtzidis55c34112009-06-25 18:22:30 +0000235 case PCHReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000236 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000237 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000238 }
Mike Stump11289f42009-09-09 15:08:12 +0000239
Daniel Dunbara8a50932009-12-02 08:44:16 +0000240 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
241
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000242 // PCH loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000243
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000244 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000245 //
246 // FIXME: This is broken, we should store the TargetOptions in the PCH.
247 TargetOptions TargetOpts;
248 TargetOpts.ABI = "";
Charles Davis95a546e2010-06-11 01:06:47 +0000249 TargetOpts.CXXABI = "itanium";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000250 TargetOpts.CPU = "";
251 TargetOpts.Features.clear();
252 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000253 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
254 TargetOpts));
255 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
256 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000257 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000258 Preprocessor &PP = *AST->PP.get();
259
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000260 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000261 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000262 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000263
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000264 // Create and initialize the ASTContext.
265
266 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000267 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000268 *AST->Target.get(),
269 PP.getIdentifierTable(),
270 PP.getSelectorTable(),
271 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000272 /* size_reserve = */0));
273 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000274
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000275 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000277 // Attach the PCH reader to the AST context as an external AST
278 // source, so that declarations will be deserialized from the
279 // PCH file as needed.
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000280 Source.reset(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000281 Context.setExternalSource(Source);
282
Mike Stump11289f42009-09-09 15:08:12 +0000283 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000284}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000285
286namespace {
287
Daniel Dunbar644dca02009-12-04 08:17:33 +0000288class TopLevelDeclTrackerConsumer : public ASTConsumer {
289 ASTUnit &Unit;
290
291public:
292 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
293
294 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000295 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
296 Decl *D = *it;
297 // FIXME: Currently ObjC method declarations are incorrectly being
298 // reported as top-level declarations, even though their DeclContext
299 // is the containing ObjC @interface/@implementation. This is a
300 // fundamental problem in the parser right now.
301 if (isa<ObjCMethodDecl>(D))
302 continue;
303 Unit.getTopLevelDecls().push_back(D);
304 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000305 }
306};
307
308class TopLevelDeclTrackerAction : public ASTFrontendAction {
309public:
310 ASTUnit &Unit;
311
Daniel Dunbar764c0822009-12-01 09:51:01 +0000312 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
313 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000314 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000315 }
316
317public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000318 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
319
Daniel Dunbar764c0822009-12-01 09:51:01 +0000320 virtual bool hasCodeCompletionSupport() const { return false; }
321};
322
323}
324
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000325/// Parse the source file into a translation unit using the given compiler
326/// invocation, replacing the current translation unit.
327///
328/// \returns True if a failure occurred that causes the ASTUnit not to
329/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000330bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000331 if (!Invocation.get())
332 return true;
333
Daniel Dunbar764c0822009-12-01 09:51:01 +0000334 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000335 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000336 Clang.setInvocation(Invocation.take());
337 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
338
339 // Set up diagnostics.
340 Clang.setDiagnostics(&getDiagnostics());
341 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregord03e8232010-04-05 21:10:19 +0000342
Daniel Dunbar764c0822009-12-01 09:51:01 +0000343 // Create the target instance.
344 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
345 Clang.getTargetOpts()));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000346 if (!Clang.hasTarget()) {
Douglas Gregor33cdd812010-02-18 18:08:43 +0000347 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000348 return true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000349 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000350
Daniel Dunbar764c0822009-12-01 09:51:01 +0000351 // Inform the target of the language options.
352 //
353 // FIXME: We shouldn't need to do this, the target should be immutable once
354 // created. This complexity should be lifted elsewhere.
355 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000356
Daniel Dunbar764c0822009-12-01 09:51:01 +0000357 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
358 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000359 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000360 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000361 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
362 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000363
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000364 // Configure the various subsystems.
365 // FIXME: Should we retain the previous file manager?
366 FileMgr.reset(new FileManager);
367 SourceMgr.reset(new SourceManager(getDiagnostics()));
368 Ctx.reset();
369 PP.reset();
370
371 // Clear out old caches and data.
372 TopLevelDecls.clear();
373 StoredDiagnostics.clear();
374 CleanTemporaryFiles();
375 PreprocessedEntitiesByFile.clear();
376
Douglas Gregor33cdd812010-02-18 18:08:43 +0000377 // Capture any diagnostics that would otherwise be dropped.
378 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
379 Clang.getDiagnostics(),
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000380 StoredDiagnostics);
381
Daniel Dunbar764c0822009-12-01 09:51:01 +0000382 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000383 Clang.setFileManager(&getFileManager());
384
Daniel Dunbar764c0822009-12-01 09:51:01 +0000385 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000386 Clang.setSourceManager(&getSourceManager());
387
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000388 // If the main file has been overridden due to the use of a preamble,
389 // make that override happen and introduce the preamble.
390 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
391 if (OverrideMainBuffer) {
392 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
393 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
394 PreprocessorOpts.PrecompiledPreambleBytes.second
395 = PreambleEndsAtStartOfLine;
396 PreprocessorOpts.ImplicitPCHInclude = PreambleFile.str();
397 }
398
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000399 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
400 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000401 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000402 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000403 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000404
Daniel Dunbar644dca02009-12-04 08:17:33 +0000405 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000406
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000407 // Steal the created target, context, and preprocessor, and take back the
408 // source and file managers.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000409 Ctx.reset(Clang.takeASTContext());
410 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000411 Clang.takeSourceManager();
412 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000413 Target.reset(Clang.takeTarget());
414
Daniel Dunbar644dca02009-12-04 08:17:33 +0000415 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000416
417 // Remove the overridden buffer we used for the preamble.
418 if (OverrideMainBuffer)
419 PreprocessorOpts.eraseRemappedFile(
420 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000421
Daniel Dunbar764c0822009-12-01 09:51:01 +0000422 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000423
424 Invocation.reset(Clang.takeInvocation());
425 return false;
426
Daniel Dunbar764c0822009-12-01 09:51:01 +0000427error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000428 // Remove the overridden buffer we used for the preamble.
429 if (OverrideMainBuffer)
430 PreprocessorOpts.eraseRemappedFile(
431 PreprocessorOpts.remapped_file_buffer_end() - 1);
432
Daniel Dunbar764c0822009-12-01 09:51:01 +0000433 Clang.takeSourceManager();
434 Clang.takeFileManager();
435 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000436 Invocation.reset(Clang.takeInvocation());
437 return true;
438}
439
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000440/// \brief Simple function to retrieve a path for a preamble precompiled header.
441static std::string GetPreamblePCHPath() {
442 // FIXME: This is lame; sys::Path should provide this function (in particular,
443 // it should know how to find the temporary files dir).
444 // FIXME: This is really lame. I copied this code from the Driver!
445 std::string Error;
446 const char *TmpDir = ::getenv("TMPDIR");
447 if (!TmpDir)
448 TmpDir = ::getenv("TEMP");
449 if (!TmpDir)
450 TmpDir = ::getenv("TMP");
451 if (!TmpDir)
452 TmpDir = "/tmp";
453 llvm::sys::Path P(TmpDir);
454 P.appendComponent("preamble");
455 if (P.createTemporaryFileOnDisk())
456 return std::string();
457
458 P.appendSuffix("pch");
459 return P.str();
460}
461
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000462/// \brief Compute the preamble for the main file, providing the source buffer
463/// that corresponds to the main file along with a pair (bytes, start-of-line)
464/// that describes the preamble.
465std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor4dde7492010-07-23 23:58:40 +0000466ASTUnit::ComputePreamble(CompilerInvocation &Invocation, bool &CreatedBuffer) {
467 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000468 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000469 = Invocation.getPreprocessorOpts();
470 CreatedBuffer = false;
471
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000472 // Try to determine if the main file has been remapped, either from the
473 // command line (to another file) or directly through the compiler invocation
474 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000475 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000476 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
477 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
478 // Check whether there is a file-file remapping of the main file
479 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000480 M = PreprocessorOpts.remapped_file_begin(),
481 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000482 M != E;
483 ++M) {
484 llvm::sys::PathWithStatus MPath(M->first);
485 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
486 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
487 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000488 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000489 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000490 CreatedBuffer = false;
491 }
492
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000493 Buffer = llvm::MemoryBuffer::getFile(M->second);
494 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000495 return std::make_pair((llvm::MemoryBuffer*)0,
496 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000497 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000498
Douglas Gregor4dde7492010-07-23 23:58:40 +0000499 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000500 M = PreprocessorOpts.eraseRemappedFile(M);
501 E = PreprocessorOpts.remapped_file_end();
502 }
503 }
504 }
505
506 // Check whether there is a file-buffer remapping. It supercedes the
507 // file-file remapping.
508 for (PreprocessorOptions::remapped_file_buffer_iterator
509 M = PreprocessorOpts.remapped_file_buffer_begin(),
510 E = PreprocessorOpts.remapped_file_buffer_end();
511 M != E;
512 ++M) {
513 llvm::sys::PathWithStatus MPath(M->first);
514 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
515 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
516 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000517 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000518 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000519 CreatedBuffer = false;
520 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000521
Douglas Gregor4dde7492010-07-23 23:58:40 +0000522 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
523
524 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000525 M = PreprocessorOpts.eraseRemappedFile(M);
526 E = PreprocessorOpts.remapped_file_buffer_end();
527 }
528 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000529 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000530 }
531
532 // If the main source file was not remapped, load it now.
533 if (!Buffer) {
534 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
535 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000536 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000537
538 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000539 }
540
Douglas Gregor4dde7492010-07-23 23:58:40 +0000541 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer));
542}
543
Douglas Gregor6481ef12010-07-24 00:38:13 +0000544static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
545 bool DeleteOld,
546 unsigned NewSize,
547 llvm::StringRef NewName) {
548 llvm::MemoryBuffer *Result
549 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
550 memcpy(const_cast<char*>(Result->getBufferStart()),
551 Old->getBufferStart(), Old->getBufferSize());
552 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000553 ' ', NewSize - Old->getBufferSize() - 1);
554 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000555
556 if (DeleteOld)
557 delete Old;
558
559 return Result;
560}
561
Douglas Gregor4dde7492010-07-23 23:58:40 +0000562/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
563/// the source file.
564///
565/// This routine will compute the preamble of the main source file. If a
566/// non-trivial preamble is found, it will precompile that preamble into a
567/// precompiled header so that the precompiled preamble can be used to reduce
568/// reparsing time. If a precompiled preamble has already been constructed,
569/// this routine will determine if it is still valid and, if so, avoid
570/// rebuilding the precompiled preamble.
571///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000572/// \returns If the precompiled preamble can be used, returns a newly-allocated
573/// buffer that should be used in place of the main file when doing so.
574/// Otherwise, returns a NULL pointer.
575llvm::MemoryBuffer *ASTUnit::BuildPrecompiledPreamble() {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000576 CompilerInvocation PreambleInvocation(*Invocation);
577 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
578 PreprocessorOptions &PreprocessorOpts
579 = PreambleInvocation.getPreprocessorOpts();
580
581 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000582 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor4dde7492010-07-23 23:58:40 +0000583 = ComputePreamble(PreambleInvocation, CreatedPreambleBuffer);
584
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000585 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000586 // We couldn't find a preamble in the main source. Clear out the current
587 // preamble, if we have one. It's obviously no good any more.
588 Preamble.clear();
589 if (!PreambleFile.empty()) {
590 PreambleFile.eraseFromDisk();
591 PreambleFile.clear();
592 }
593 if (CreatedPreambleBuffer)
594 delete NewPreamble.first;
595
Douglas Gregor6481ef12010-07-24 00:38:13 +0000596 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000597 }
598
599 if (!Preamble.empty()) {
600 // We've previously computed a preamble. Check whether we have the same
601 // preamble now that we did before, and that there's enough space in
602 // the main-file buffer within the precompiled preamble to fit the
603 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000604 if (Preamble.size() == NewPreamble.second.first &&
605 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000606 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000607 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000608 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000609 // The preamble has not changed. We may be able to re-use the precompiled
610 // preamble.
611 // FIXME: Check that none of the files used by the preamble have changed.
612
Douglas Gregor6481ef12010-07-24 00:38:13 +0000613
Douglas Gregor4dde7492010-07-23 23:58:40 +0000614 // Okay! Re-use the precompiled preamble.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000615 return CreatePaddedMainFileBuffer(NewPreamble.first,
616 CreatedPreambleBuffer,
617 PreambleReservedSize,
618 FrontendOpts.Inputs[0].second);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000619 }
620
621 // We can't reuse the previously-computed preamble. Build a new one.
622 Preamble.clear();
623 PreambleFile.eraseFromDisk();
624 }
625
626 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000627
628 // Create a new buffer that stores the preamble. The buffer also contains
629 // extra space for the original contents of the file (which will be present
630 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +0000631 // grows.
632 PreambleReservedSize = NewPreamble.first->getBufferSize();
633 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000634 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000635 else
Douglas Gregor4dde7492010-07-23 23:58:40 +0000636 PreambleReservedSize *= 2;
637
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000638 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +0000639 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000640 FrontendOpts.Inputs[0].second);
641 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +0000642 NewPreamble.first->getBufferStart(), Preamble.size());
643 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000644 ' ', PreambleReservedSize - Preamble.size() - 1);
645 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorf5275a82010-07-24 00:42:07 +0000646
Douglas Gregor4dde7492010-07-23 23:58:40 +0000647 // Save the preamble text for later; we'll need to compare against it for
648 // subsequent reparses.
649 Preamble.assign(NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000650 NewPreamble.first->getBufferStart()
651 + NewPreamble.second.first);
652 PreambleEndsAtStartOfLine = NewPreamble.second.second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000653
654 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000655 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000656 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
657
658 // Tell the compiler invocation to generate a temporary precompiled header.
659 FrontendOpts.ProgramAction = frontend::GeneratePCH;
660 // FIXME: Set ChainedPCH, once it is ready.
661 // FIXME: Generate the precompiled header into memory?
Douglas Gregor4dde7492010-07-23 23:58:40 +0000662 if (PreambleFile.isEmpty())
663 FrontendOpts.OutputFile = GetPreamblePCHPath();
664 else
665 FrontendOpts.OutputFile = PreambleFile.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000666
667 // Create the compiler instance to use for building the precompiled preamble.
668 CompilerInstance Clang;
669 Clang.setInvocation(&PreambleInvocation);
670 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
671
672 // Set up diagnostics.
673 Clang.setDiagnostics(&getDiagnostics());
674 Clang.setDiagnosticClient(getDiagnostics().getClient());
675
676 // Create the target instance.
677 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
678 Clang.getTargetOpts()));
679 if (!Clang.hasTarget()) {
680 Clang.takeDiagnosticClient();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000681 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
682 Preamble.clear();
683 if (CreatedPreambleBuffer)
684 delete NewPreamble.first;
685
Douglas Gregor6481ef12010-07-24 00:38:13 +0000686 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000687 }
688
689 // Inform the target of the language options.
690 //
691 // FIXME: We shouldn't need to do this, the target should be immutable once
692 // created. This complexity should be lifted elsewhere.
693 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
694
695 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
696 "Invocation must have exactly one source file!");
697 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
698 "FIXME: AST inputs not yet supported here!");
699 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
700 "IR inputs not support here!");
701
702 // Clear out old caches and data.
703 StoredDiagnostics.clear();
704
705 // Capture any diagnostics that would otherwise be dropped.
706 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
707 Clang.getDiagnostics(),
708 StoredDiagnostics);
709
710 // Create a file manager object to provide access to and cache the filesystem.
711 Clang.setFileManager(new FileManager);
712
713 // Create the source manager.
714 Clang.setSourceManager(new SourceManager(getDiagnostics()));
715
716 // FIXME: Eventually, we'll have to track top-level declarations here, too.
717 llvm::OwningPtr<GeneratePCHAction> Act;
718 Act.reset(new GeneratePCHAction);
719 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
720 Clang.getFrontendOpts().Inputs[0].first)) {
721 Clang.takeDiagnosticClient();
722 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000723 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
724 Preamble.clear();
725 if (CreatedPreambleBuffer)
726 delete NewPreamble.first;
727
Douglas Gregor6481ef12010-07-24 00:38:13 +0000728 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000729 }
730
731 Act->Execute();
732 Act->EndSourceFile();
733 Clang.takeDiagnosticClient();
734 Clang.takeInvocation();
735
Douglas Gregor4dde7492010-07-23 23:58:40 +0000736 if (Diagnostics->getNumErrors() > 0) {
737 // There were errors parsing the preamble, so no precompiled header was
738 // generated. Forget that we even tried.
739 // FIXME: Should we leave a note for ourselves to try again?
740 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
741 Preamble.clear();
742 if (CreatedPreambleBuffer)
743 delete NewPreamble.first;
744
Douglas Gregor6481ef12010-07-24 00:38:13 +0000745 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000746 }
747
748 // Keep track of the preamble we precompiled.
749 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000750 fprintf(stderr, "Preamble PCH: %s\n", FrontendOpts.OutputFile.c_str());
Douglas Gregor6481ef12010-07-24 00:38:13 +0000751 return CreatePaddedMainFileBuffer(NewPreamble.first,
752 CreatedPreambleBuffer,
753 PreambleReservedSize,
754 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000755}
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000756
757ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
758 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
759 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000760 bool CaptureDiagnostics,
761 bool PrecompilePreamble) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000762 if (!Diags.getPtr()) {
763 // No diagnostics engine was provided, so create our own diagnostics object
764 // with the default options.
765 DiagnosticOptions DiagOpts;
766 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
767 }
768
769 // Create the AST unit.
770 llvm::OwningPtr<ASTUnit> AST;
771 AST.reset(new ASTUnit(false));
772 AST->Diagnostics = Diags;
773 AST->CaptureDiagnostics = CaptureDiagnostics;
774 AST->OnlyLocalDecls = OnlyLocalDecls;
775 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000776 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000777
Douglas Gregor6481ef12010-07-24 00:38:13 +0000778 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000779 if (PrecompilePreamble)
Douglas Gregor6481ef12010-07-24 00:38:13 +0000780 OverrideMainBuffer = AST->BuildPrecompiledPreamble();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000781
Douglas Gregor6481ef12010-07-24 00:38:13 +0000782 if (!AST->Parse(OverrideMainBuffer))
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000783 return AST.take();
784
Douglas Gregor6481ef12010-07-24 00:38:13 +0000785 delete OverrideMainBuffer;
Daniel Dunbar764c0822009-12-01 09:51:01 +0000786 return 0;
787}
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000788
789ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
790 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000791 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +0000792 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000793 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000794 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000795 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000796 bool CaptureDiagnostics,
797 bool PrecompilePreamble) {
Douglas Gregor7f95d262010-04-05 23:52:57 +0000798 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000799 // No diagnostics engine was provided, so create our own diagnostics object
800 // with the default options.
801 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000802 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000803 }
804
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000805 llvm::SmallVector<const char *, 16> Args;
806 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
807 Args.insert(Args.end(), ArgBegin, ArgEnd);
808
809 // FIXME: Find a cleaner way to force the driver into restricted modes. We
810 // also want to force it to use clang.
811 Args.push_back("-fsyntax-only");
812
Daniel Dunbar8d4a2022009-12-13 03:46:13 +0000813 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +0000814 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000815 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +0000816
817 // Don't check that inputs exist, they have been remapped.
818 TheDriver.setCheckInputsExist(false);
819
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000820 llvm::OwningPtr<driver::Compilation> C(
821 TheDriver.BuildCompilation(Args.size(), Args.data()));
822
823 // We expect to get back exactly one command job, if we didn't something
824 // failed.
825 const driver::JobList &Jobs = C->getJobs();
826 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
827 llvm::SmallString<256> Msg;
828 llvm::raw_svector_ostream OS(Msg);
829 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +0000830 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000831 return 0;
832 }
833
834 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
835 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +0000836 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000837 return 0;
838 }
839
840 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +0000841 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +0000842 CompilerInvocation::CreateFromArgs(*CI,
843 const_cast<const char **>(CCArgs.data()),
844 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000845 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000846 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +0000847
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000848 // Override any files that need remapping
849 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +0000850 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +0000851 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000852
Daniel Dunbara5a166d2009-12-15 00:06:45 +0000853 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +0000854 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000855
Daniel Dunbar19511922010-02-16 01:55:04 +0000856 CI->getFrontendOpts().DisableFree = true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000857 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000858 CaptureDiagnostics, PrecompilePreamble);
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000859}
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000860
861bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
862 if (!Invocation.get())
863 return true;
864
Douglas Gregor4dde7492010-07-23 23:58:40 +0000865 // If we have a preamble file lying around, build or reuse the precompiled
866 // preamble.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000867 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000868 if (!PreambleFile.empty())
Douglas Gregor6481ef12010-07-24 00:38:13 +0000869 OverrideMainBuffer = BuildPrecompiledPreamble();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000870
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000871 // Clear out the diagnostics state.
872 getDiagnostics().Reset();
873
874 // Remap files.
875 Invocation->getPreprocessorOpts().clearRemappedFiles();
876 for (unsigned I = 0; I != NumRemappedFiles; ++I)
877 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Douglas Gregor4dde7492010-07-23 23:58:40 +0000878 RemappedFiles[I].second);
879
880 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +0000881 bool Result = Parse(OverrideMainBuffer);
882 delete OverrideMainBuffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000883 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000884}