blob: f36a56032b29dcc95ca37c83cec5de4c5ca0f368 [file] [log] [blame]
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001//===--- CompilerInstance.cpp ---------------------------------------------===//
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#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000012#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000013#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000014#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000016#include "clang/Basic/TargetInfo.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000017#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/PTHManager.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000020#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0f800392009-11-13 08:21:10 +000021#include "clang/Frontend/PCHReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000023#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000024#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000025#include "clang/Frontend/Utils.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000026#include "clang/Sema/CodeCompleteConsumer.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000027#include "llvm/LLVMContext.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000028#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000029#include "llvm/Support/raw_ostream.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000030#include "llvm/Support/Timer.h"
Daniel Dunbara9204832009-11-13 10:37:48 +000031#include "llvm/System/Path.h"
Douglas Gregor2b4074f2009-12-01 05:55:20 +000032#include "llvm/System/Program.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000033using namespace clang;
34
35CompilerInstance::CompilerInstance(llvm::LLVMContext *_LLVMContext,
36 bool _OwnsLLVMContext)
37 : LLVMContext(_LLVMContext),
38 OwnsLLVMContext(_OwnsLLVMContext) {
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000039 }
Daniel Dunbar2a79e162009-11-13 03:51:44 +000040
41CompilerInstance::~CompilerInstance() {
42 if (OwnsLLVMContext)
43 delete LLVMContext;
44}
Daniel Dunbar16b74492009-11-13 04:12:06 +000045
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000046void CompilerInstance::setDiagnostics(Diagnostic *Value) {
47 Diagnostics.reset(Value);
48}
49
50void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) {
51 DiagClient.reset(Value);
52}
53
54void CompilerInstance::setTarget(TargetInfo *Value) {
55 Target.reset(Value);
56}
57
58void CompilerInstance::setFileManager(FileManager *Value) {
59 FileMgr.reset(Value);
60}
61
62void CompilerInstance::setSourceManager(SourceManager *Value) {
63 SourceMgr.reset(Value);
64}
65
66void CompilerInstance::setPreprocessor(Preprocessor *Value) {
67 PP.reset(Value);
68}
69
70void CompilerInstance::setASTContext(ASTContext *Value) {
71 Context.reset(Value);
72}
73
Daniel Dunbar12ce6942009-11-14 02:47:17 +000074void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
75 Consumer.reset(Value);
76}
77
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000078void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
79 CompletionConsumer.reset(Value);
80}
81
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000082// Diagnostics
83
84static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
85 unsigned argc, char **argv,
86 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
87 std::string ErrorInfo;
88 llvm::raw_ostream *OS =
89 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
90 if (!ErrorInfo.empty()) {
91 // FIXME: Do not fail like this.
92 llvm::errs() << "error opening -dump-build-information file '"
93 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
94 delete OS;
95 return;
96 }
97
98 (*OS) << "clang-cc command line arguments: ";
99 for (unsigned i = 0; i != argc; ++i)
100 (*OS) << argv[i] << ' ';
101 (*OS) << '\n';
102
103 // Chain in a diagnostic client which will log the diagnostics.
104 DiagnosticClient *Logger =
105 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
106 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
107}
108
109void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
110 Diagnostics.reset(createDiagnostics(getDiagnosticOpts(), Argc, Argv));
111
112 if (Diagnostics)
113 DiagClient.reset(Diagnostics->getClient());
114}
115
116Diagnostic *CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
117 int Argc, char **Argv) {
Daniel Dunbar221c7212009-11-14 07:53:24 +0000118 llvm::OwningPtr<Diagnostic> Diags(new Diagnostic());
119
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000120 // Create the diagnostic client for reporting errors or for
121 // implementing -verify.
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000122 llvm::OwningPtr<DiagnosticClient> DiagClient(
123 new TextDiagnosticPrinter(llvm::errs(), Opts));
124
125 // Chain in -verify checker, if requested.
126 if (Opts.VerifyDiagnostics)
Daniel Dunbar221c7212009-11-14 07:53:24 +0000127 DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000128
129 if (!Opts.DumpBuildInformation.empty())
130 SetUpBuildDumpLog(Opts, Argc, Argv, DiagClient);
131
132 // Configure our handling of diagnostics.
Daniel Dunbar221c7212009-11-14 07:53:24 +0000133 Diags->setClient(DiagClient.take());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000134 if (ProcessWarningOptions(*Diags, Opts))
135 return 0;
136
Daniel Dunbar221c7212009-11-14 07:53:24 +0000137 return Diags.take();
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000138}
139
140// File Manager
141
Daniel Dunbar16b74492009-11-13 04:12:06 +0000142void CompilerInstance::createFileManager() {
143 FileMgr.reset(new FileManager());
144}
145
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000146// Source Manager
147
Daniel Dunbar16b74492009-11-13 04:12:06 +0000148void CompilerInstance::createSourceManager() {
149 SourceMgr.reset(new SourceManager());
150}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000151
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000152// Preprocessor
153
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000154void CompilerInstance::createPreprocessor() {
155 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
156 getPreprocessorOpts(), getHeaderSearchOpts(),
157 getDependencyOutputOpts(), getTarget(),
158 getSourceManager(), getFileManager()));
159}
160
161Preprocessor *
162CompilerInstance::createPreprocessor(Diagnostic &Diags,
163 const LangOptions &LangInfo,
164 const PreprocessorOptions &PPOpts,
165 const HeaderSearchOptions &HSOpts,
166 const DependencyOutputOptions &DepOpts,
167 const TargetInfo &Target,
168 SourceManager &SourceMgr,
169 FileManager &FileMgr) {
170 // Create a PTH manager if we are using some form of a token cache.
171 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000172 if (!PPOpts.TokenCache.empty())
173 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000174
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000175 // Create the Preprocessor.
176 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
177 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
178 SourceMgr, *HeaderInfo, PTHMgr,
179 /*OwnsHeaderSearch=*/true);
180
181 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
182 // That argument is used as the IdentifierInfoLookup argument to
183 // IdentifierTable's ctor.
184 if (PTHMgr) {
185 PTHMgr->setPreprocessor(PP);
186 PP->setPTHManager(PTHMgr);
187 }
188
189 InitializePreprocessor(*PP, PPOpts, HSOpts);
190
191 // Handle generating dependencies, if requested.
192 if (!DepOpts.OutputFile.empty())
193 AttachDependencyFileGen(*PP, DepOpts);
194
195 return PP;
196}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000197
198// ASTContext
199
200void CompilerInstance::createASTContext() {
201 Preprocessor &PP = getPreprocessor();
202 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
203 getTarget(), PP.getIdentifierTable(),
204 PP.getSelectorTable(), PP.getBuiltinInfo(),
205 /*FreeMemory=*/ !getFrontendOpts().DisableFree,
206 /*size_reserve=*/ 0));
207}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000208
209// ExternalASTSource
210
211void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) {
212 llvm::OwningPtr<ExternalASTSource> Source;
213 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
214 getPreprocessor(), getASTContext()));
215 getASTContext().setExternalSource(Source);
216}
217
218ExternalASTSource *
219CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
220 const std::string &Sysroot,
221 Preprocessor &PP,
222 ASTContext &Context) {
223 llvm::OwningPtr<PCHReader> Reader;
224 Reader.reset(new PCHReader(PP, &Context,
225 Sysroot.empty() ? 0 : Sysroot.c_str()));
226
227 switch (Reader->ReadPCH(Path)) {
228 case PCHReader::Success:
229 // Set the predefines buffer as suggested by the PCH reader. Typically, the
230 // predefines buffer will be empty.
231 PP.setPredefines(Reader->getSuggestedPredefines());
232 return Reader.take();
233
234 case PCHReader::Failure:
235 // Unrecoverable failure: don't even try to process the input file.
236 break;
237
238 case PCHReader::IgnorePCH:
239 // No suitable PCH file could be found. Return an error.
240 break;
241 }
242
243 return 0;
244}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000245
246// Code Completion
247
248void CompilerInstance::createCodeCompletionConsumer() {
249 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
250 CompletionConsumer.reset(
251 createCodeCompletionConsumer(getPreprocessor(),
252 Loc.FileName, Loc.Line, Loc.Column,
253 getFrontendOpts().DebugCodeCompletionPrinter,
254 getFrontendOpts().ShowMacrosInCodeCompletion,
255 llvm::outs()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000256
257 if (CompletionConsumer->isOutputBinary() &&
258 llvm::sys::Program::ChangeStdoutToBinary()) {
259 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
260 CompletionConsumer.reset();
261 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000262}
263
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000264void CompilerInstance::createFrontendTimer() {
265 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
266}
267
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000268CodeCompleteConsumer *
269CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
270 const std::string &Filename,
271 unsigned Line,
272 unsigned Column,
273 bool UseDebugPrinter,
274 bool ShowMacros,
275 llvm::raw_ostream &OS) {
276 // Tell the source manager to chop off the given file at a specific
277 // line and column.
278 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
279 if (!Entry) {
280 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
281 << Filename;
282 return 0;
283 }
284
285 // Truncate the named file at the given line/column.
Douglas Gregor29684422009-12-02 06:49:09 +0000286 PP.SetCodeCompletionPoint(Entry, Line, Column);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000287
288 // Set up the creation routine for code-completion.
289 if (UseDebugPrinter)
290 return new PrintingCodeCompleteConsumer(ShowMacros, OS);
291 else
292 return new CIndexCodeCompleteConsumer(ShowMacros, OS);
293}
Daniel Dunbara9204832009-11-13 10:37:48 +0000294
295// Output Files
296
297void CompilerInstance::addOutputFile(llvm::StringRef Path,
298 llvm::raw_ostream *OS) {
299 assert(OS && "Attempt to add empty stream to output list!");
300 OutputFiles.push_back(std::make_pair(Path, OS));
301}
302
303void CompilerInstance::ClearOutputFiles(bool EraseFiles) {
304 for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
305 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
306 delete it->second;
307 if (EraseFiles && !it->first.empty())
308 llvm::sys::Path(it->first).eraseFromDisk();
309 }
310 OutputFiles.clear();
311}
312
Daniel Dunbarf482d592009-11-13 18:32:08 +0000313llvm::raw_fd_ostream *
314CompilerInstance::createDefaultOutputFile(bool Binary,
315 llvm::StringRef InFile,
316 llvm::StringRef Extension) {
317 return createOutputFile(getFrontendOpts().OutputFile, Binary,
318 InFile, Extension);
319}
320
321llvm::raw_fd_ostream *
322CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
323 bool Binary,
324 llvm::StringRef InFile,
325 llvm::StringRef Extension) {
326 std::string Error, OutputPathName;
327 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
328 InFile, Extension,
329 &OutputPathName);
330 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000331 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
332 << OutputPath << Error;
333 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000334 }
335
336 // Add the output file -- but don't try to remove "-", since this means we are
337 // using stdin.
338 addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
339
340 return OS;
341}
342
343llvm::raw_fd_ostream *
344CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
345 std::string &Error,
346 bool Binary,
347 llvm::StringRef InFile,
348 llvm::StringRef Extension,
349 std::string *ResultPathName) {
350 std::string OutFile;
351 if (!OutputPath.empty()) {
352 OutFile = OutputPath;
353 } else if (InFile == "-") {
354 OutFile = "-";
355 } else if (!Extension.empty()) {
356 llvm::sys::Path Path(InFile);
357 Path.eraseSuffix();
358 Path.appendSuffix(Extension);
359 OutFile = Path.str();
360 } else {
361 OutFile = "-";
362 }
363
Daniel Dunbarfc971022009-11-20 22:32:38 +0000364 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Daniel Dunbarf482d592009-11-13 18:32:08 +0000365 new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000366 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
367 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000368 return 0;
369
370 if (ResultPathName)
371 *ResultPathName = OutFile;
372
Daniel Dunbarfc971022009-11-20 22:32:38 +0000373 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000374}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000375
376// Initialization Utilities
377
378bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
379 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
380 getSourceManager(), getFrontendOpts());
381}
382
383bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
384 Diagnostic &Diags,
385 FileManager &FileMgr,
386 SourceManager &SourceMgr,
387 const FrontendOptions &Opts) {
388 // Figure out where to get and map in the main file.
389 if (Opts.EmptyInputOnly) {
390 const char *EmptyStr = "";
391 llvm::MemoryBuffer *SB =
392 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
393 SourceMgr.createMainFileIDForMemBuffer(SB);
394 } else if (InputFile != "-") {
395 const FileEntry *File = FileMgr.getFile(InputFile);
396 if (File) SourceMgr.createMainFileID(File, SourceLocation());
397 if (SourceMgr.getMainFileID().isInvalid()) {
398 Diags.Report(diag::err_fe_error_reading) << InputFile;
399 return false;
400 }
401 } else {
402 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
403 SourceMgr.createMainFileIDForMemBuffer(SB);
404 if (SourceMgr.getMainFileID().isInvalid()) {
405 Diags.Report(diag::err_fe_error_reading_stdin);
406 return false;
407 }
408 }
409
410 return true;
411}