blob: 6e3a1e1fa7b73c9682ca73ac034a6673200bde02 [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"
Daniel Dunbar764c0822009-12-01 09:51:01 +000033#include "llvm/LLVMContext.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"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000036using namespace clang;
37
Daniel Dunbar764c0822009-12-01 09:51:01 +000038ASTUnit::ASTUnit(DiagnosticClient *diagClient) : tempFile(false) {
Ted Kremenek428c6372009-10-19 21:44:57 +000039 Diags.setClient(diagClient ? diagClient : new TextDiagnosticBuffer());
Steve Naroff505fb842009-10-19 14:34:22 +000040}
Daniel Dunbar764c0822009-12-01 09:51:01 +000041ASTUnit::~ASTUnit() {
Steve Naroff44cd60e2009-10-15 22:23:48 +000042 if (tempFile)
Benjamin Kramer6c839f82009-10-18 11:34:14 +000043 llvm::sys::Path(getPCHFileName()).eraseFromDisk();
Daniel Dunbar764c0822009-12-01 09:51:01 +000044
Ted Kremenek428c6372009-10-19 21:44:57 +000045 // The ASTUnit object owns the DiagnosticClient.
46 delete Diags.getClient();
Steve Naroff44cd60e2009-10-15 22:23:48 +000047}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000048
49namespace {
50
51/// \brief Gathers information from PCHReader that will be used to initialize
52/// a Preprocessor.
Benjamin Kramer16634c22009-11-28 10:07:24 +000053class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000054 LangOptions &LangOpt;
55 HeaderSearch &HSI;
56 std::string &TargetTriple;
57 std::string &Predefines;
58 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +000059
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000060 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +000061
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000062public:
63 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
64 std::string &TargetTriple, std::string &Predefines,
65 unsigned &Counter)
66 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
67 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +000068
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000069 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
70 LangOpt = LangOpts;
71 return false;
72 }
Mike Stump11289f42009-09-09 15:08:12 +000073
Daniel Dunbar20a682d2009-11-11 00:52:11 +000074 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000075 TargetTriple = Triple;
76 return false;
77 }
Mike Stump11289f42009-09-09 15:08:12 +000078
Daniel Dunbar20a682d2009-11-11 00:52:11 +000079 virtual bool ReadPredefinesBuffer(llvm::StringRef PCHPredef,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000080 FileID PCHBufferID,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +000081 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000082 std::string &SuggestedPredefines) {
83 Predefines = PCHPredef;
84 return false;
85 }
Mike Stump11289f42009-09-09 15:08:12 +000086
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000087 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
88 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
89 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000091 virtual void ReadCounter(unsigned Value) {
92 Counter = Value;
93 }
94};
95
96} // anonymous namespace
97
Steve Naroffc0683b92009-09-03 18:19:54 +000098const std::string &ASTUnit::getOriginalSourceFileName() {
99 return dyn_cast<PCHReader>(Ctx->getExternalSource())->getOriginalSourceFile();
100}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000101
Steve Naroff44cd60e2009-10-15 22:23:48 +0000102const std::string &ASTUnit::getPCHFileName() {
103 return dyn_cast<PCHReader>(Ctx->getExternalSource())->getFileName();
104}
105
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000106ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor16bef852009-10-16 20:01:17 +0000107 std::string *ErrMsg,
Ted Kremenek428c6372009-10-19 21:44:57 +0000108 DiagnosticClient *diagClient,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000109 bool OnlyLocalDecls,
110 bool UseBumpAllocator) {
Ted Kremenek428c6372009-10-19 21:44:57 +0000111 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(diagClient));
Douglas Gregor16bef852009-10-16 20:01:17 +0000112 AST->OnlyLocalDecls = OnlyLocalDecls;
Steve Naroff505fb842009-10-19 14:34:22 +0000113 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000114
115 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000116
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000117 LangOptions LangInfo;
118 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
119 std::string TargetTriple;
120 std::string Predefines;
121 unsigned Counter;
122
Daniel Dunbar3a0637b2009-09-03 05:59:50 +0000123 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000124 llvm::OwningPtr<ExternalASTSource> Source;
125
Ted Kremenek428c6372009-10-19 21:44:57 +0000126 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
127 AST->Diags));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000128 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
129 Predefines, Counter));
130
131 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000132 case PCHReader::Success:
133 break;
Mike Stump11289f42009-09-09 15:08:12 +0000134
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000135 case PCHReader::Failure:
Argyrios Kyrtzidis55c34112009-06-25 18:22:30 +0000136 case PCHReader::IgnorePCH:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000137 if (ErrMsg)
138 *ErrMsg = "Could not load PCH file";
139 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000142 // PCH loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000143
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000144 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000145 //
146 // FIXME: This is broken, we should store the TargetOptions in the PCH.
147 TargetOptions TargetOpts;
148 TargetOpts.ABI = "";
149 TargetOpts.CPU = "";
150 TargetOpts.Features.clear();
151 TargetOpts.Triple = TargetTriple;
152 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->Diags, TargetOpts));
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000153 AST->PP.reset(new Preprocessor(AST->Diags, LangInfo, *AST->Target.get(),
154 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000155 Preprocessor &PP = *AST->PP.get();
156
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000157 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000158 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000159 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000160
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000161 // Create and initialize the ASTContext.
162
163 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000164 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000165 *AST->Target.get(),
166 PP.getIdentifierTable(),
167 PP.getSelectorTable(),
168 PP.getBuiltinInfo(),
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000169 /* FreeMemory = */ !UseBumpAllocator,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000170 /* size_reserve = */0));
171 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000172
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000173 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000174
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000175 // Attach the PCH reader to the AST context as an external AST
176 // source, so that declarations will be deserialized from the
177 // PCH file as needed.
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000178 Source.reset(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000179 Context.setExternalSource(Source);
180
Mike Stump11289f42009-09-09 15:08:12 +0000181 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000182}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000183
184namespace {
185
186class NullAction : public ASTFrontendAction {
187 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
188 llvm::StringRef InFile) {
189 return new ASTConsumer();
190 }
191
192public:
193 virtual bool hasCodeCompletionSupport() const { return false; }
194};
195
196}
197
198ASTUnit *ASTUnit::LoadFromCompilerInvocation(const CompilerInvocation &CI,
199 Diagnostic &Diags,
200 bool OnlyLocalDecls,
201 bool UseBumpAllocator) {
202 // Create the compiler instance to use for building the AST.
203 CompilerInstance Clang(&llvm::getGlobalContext(), false);
204 llvm::OwningPtr<ASTUnit> AST;
205 NullAction Act;
206
207 Clang.getInvocation() = CI;
208
209 Clang.setDiagnostics(&Diags);
210 Clang.setDiagnosticClient(Diags.getClient());
211
212 // Create the target instance.
213 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
214 Clang.getTargetOpts()));
215 if (!Clang.hasTarget())
216 goto error;
217
218 // Inform the target of the language options.
219 //
220 // FIXME: We shouldn't need to do this, the target should be immutable once
221 // created. This complexity should be lifted elsewhere.
222 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
223
224 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
225 "Invocation must have exactly one source file!");
226 assert(Clang.getFrontendOpts().Inputs[0].first != FrontendOptions::IK_AST &&
227 "FIXME: AST inputs not yet supported here!");
228
229 // Create the AST unit.
230 //
231 // FIXME: Use the provided diagnostic client.
232 AST.reset(new ASTUnit());
233
234 // Create a file manager object to provide access to and cache the filesystem.
235 Clang.setFileManager(&AST->getFileManager());
236
237 // Create the source manager.
238 Clang.setSourceManager(&AST->getSourceManager());
239
240 // Create the preprocessor.
241 Clang.createPreprocessor();
242
243 if (!Act.BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
244 /*IsAST=*/false))
245 goto error;
246
247 Act.Execute();
248
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000249 // Steal the created target, context, and preprocessor, and take back the
250 // source and file managers.
Daniel Dunbar764c0822009-12-01 09:51:01 +0000251 AST->Ctx.reset(Clang.takeASTContext());
252 AST->PP.reset(Clang.takePreprocessor());
253 Clang.takeSourceManager();
254 Clang.takeFileManager();
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000255 AST->Target.reset(Clang.takeTarget());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000256
257 Act.EndSourceFile();
258
259 Clang.takeDiagnosticClient();
260 Clang.takeDiagnostics();
261
262 return AST.take();
263
264error:
265 Clang.takeSourceManager();
266 Clang.takeFileManager();
267 Clang.takeDiagnosticClient();
268 Clang.takeDiagnostics();
269 return 0;
270}
Daniel Dunbar55a17b62009-12-02 03:23:45 +0000271
272ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
273 const char **ArgEnd,
274 Diagnostic &Diags,
275 const char *Argv0,
276 void *MainAddr,
277 bool OnlyLocalDecls,
278 bool UseBumpAllocator) {
279 llvm::SmallVector<const char *, 16> Args;
280 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
281 Args.insert(Args.end(), ArgBegin, ArgEnd);
282
283 // FIXME: Find a cleaner way to force the driver into restricted modes. We
284 // also want to force it to use clang.
285 Args.push_back("-fsyntax-only");
286
287 llvm::sys::Path Path = llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
288 driver::Driver TheDriver(Path.getBasename().c_str(),Path.getDirname().c_str(),
289 llvm::sys::getHostTriple().c_str(),
290 "a.out", false, Diags);
291 llvm::OwningPtr<driver::Compilation> C(
292 TheDriver.BuildCompilation(Args.size(), Args.data()));
293
294 // We expect to get back exactly one command job, if we didn't something
295 // failed.
296 const driver::JobList &Jobs = C->getJobs();
297 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
298 llvm::SmallString<256> Msg;
299 llvm::raw_svector_ostream OS(Msg);
300 C->PrintJob(OS, C->getJobs(), "; ", true);
301 Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
302 return 0;
303 }
304
305 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
306 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
307 Diags.Report(diag::err_fe_expected_clang_command);
308 return 0;
309 }
310
311 const driver::ArgStringList &CCArgs = Cmd->getArguments();
312 CompilerInvocation CI;
313 CompilerInvocation::CreateFromArgs(CI, (const char**) CCArgs.data(),
314 (const char**) CCArgs.data()+CCArgs.size(),
315 Argv0, MainAddr, Diags);
316
317 return LoadFromCompilerInvocation(CI, Diags, OnlyLocalDecls,
318 UseBumpAllocator);
319}