blob: 0365761c840e022845d0dc221720cdc0e8f57f47 [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"
Daniel Dunbara9204832009-11-13 10:37:48 +000030#include "llvm/System/Path.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000031using namespace clang;
32
33CompilerInstance::CompilerInstance(llvm::LLVMContext *_LLVMContext,
34 bool _OwnsLLVMContext)
35 : LLVMContext(_LLVMContext),
36 OwnsLLVMContext(_OwnsLLVMContext) {
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000037 }
Daniel Dunbar2a79e162009-11-13 03:51:44 +000038
39CompilerInstance::~CompilerInstance() {
40 if (OwnsLLVMContext)
41 delete LLVMContext;
42}
Daniel Dunbar16b74492009-11-13 04:12:06 +000043
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000044void CompilerInstance::setDiagnostics(Diagnostic *Value) {
45 Diagnostics.reset(Value);
46}
47
48void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) {
49 DiagClient.reset(Value);
50}
51
52void CompilerInstance::setTarget(TargetInfo *Value) {
53 Target.reset(Value);
54}
55
56void CompilerInstance::setFileManager(FileManager *Value) {
57 FileMgr.reset(Value);
58}
59
60void CompilerInstance::setSourceManager(SourceManager *Value) {
61 SourceMgr.reset(Value);
62}
63
64void CompilerInstance::setPreprocessor(Preprocessor *Value) {
65 PP.reset(Value);
66}
67
68void CompilerInstance::setASTContext(ASTContext *Value) {
69 Context.reset(Value);
70}
71
Daniel Dunbar12ce6942009-11-14 02:47:17 +000072void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
73 Consumer.reset(Value);
74}
75
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000076void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
77 CompletionConsumer.reset(Value);
78}
79
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000080// Diagnostics
81
82static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
83 unsigned argc, char **argv,
84 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
85 std::string ErrorInfo;
86 llvm::raw_ostream *OS =
87 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
88 if (!ErrorInfo.empty()) {
89 // FIXME: Do not fail like this.
90 llvm::errs() << "error opening -dump-build-information file '"
91 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
92 delete OS;
93 return;
94 }
95
96 (*OS) << "clang-cc command line arguments: ";
97 for (unsigned i = 0; i != argc; ++i)
98 (*OS) << argv[i] << ' ';
99 (*OS) << '\n';
100
101 // Chain in a diagnostic client which will log the diagnostics.
102 DiagnosticClient *Logger =
103 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
104 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
105}
106
107void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
108 Diagnostics.reset(createDiagnostics(getDiagnosticOpts(), Argc, Argv));
109
110 if (Diagnostics)
111 DiagClient.reset(Diagnostics->getClient());
112}
113
114Diagnostic *CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
115 int Argc, char **Argv) {
Daniel Dunbar221c7212009-11-14 07:53:24 +0000116 llvm::OwningPtr<Diagnostic> Diags(new Diagnostic());
117
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000118 // Create the diagnostic client for reporting errors or for
119 // implementing -verify.
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000120 llvm::OwningPtr<DiagnosticClient> DiagClient(
121 new TextDiagnosticPrinter(llvm::errs(), Opts));
122
123 // Chain in -verify checker, if requested.
124 if (Opts.VerifyDiagnostics)
Daniel Dunbar221c7212009-11-14 07:53:24 +0000125 DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000126
127 if (!Opts.DumpBuildInformation.empty())
128 SetUpBuildDumpLog(Opts, Argc, Argv, DiagClient);
129
130 // Configure our handling of diagnostics.
Daniel Dunbar221c7212009-11-14 07:53:24 +0000131 Diags->setClient(DiagClient.take());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000132 if (ProcessWarningOptions(*Diags, Opts))
133 return 0;
134
Daniel Dunbar221c7212009-11-14 07:53:24 +0000135 return Diags.take();
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000136}
137
138// File Manager
139
Daniel Dunbar16b74492009-11-13 04:12:06 +0000140void CompilerInstance::createFileManager() {
141 FileMgr.reset(new FileManager());
142}
143
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000144// Source Manager
145
Daniel Dunbar16b74492009-11-13 04:12:06 +0000146void CompilerInstance::createSourceManager() {
147 SourceMgr.reset(new SourceManager());
148}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000149
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000150// Preprocessor
151
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000152void CompilerInstance::createPreprocessor() {
153 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
154 getPreprocessorOpts(), getHeaderSearchOpts(),
155 getDependencyOutputOpts(), getTarget(),
156 getSourceManager(), getFileManager()));
157}
158
159Preprocessor *
160CompilerInstance::createPreprocessor(Diagnostic &Diags,
161 const LangOptions &LangInfo,
162 const PreprocessorOptions &PPOpts,
163 const HeaderSearchOptions &HSOpts,
164 const DependencyOutputOptions &DepOpts,
165 const TargetInfo &Target,
166 SourceManager &SourceMgr,
167 FileManager &FileMgr) {
168 // Create a PTH manager if we are using some form of a token cache.
169 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000170 if (!PPOpts.TokenCache.empty())
171 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000172
173 // FIXME: Don't fail like this.
174 if (Diags.hasErrorOccurred())
175 exit(1);
176
177 // Create the Preprocessor.
178 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
179 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
180 SourceMgr, *HeaderInfo, PTHMgr,
181 /*OwnsHeaderSearch=*/true);
182
183 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
184 // That argument is used as the IdentifierInfoLookup argument to
185 // IdentifierTable's ctor.
186 if (PTHMgr) {
187 PTHMgr->setPreprocessor(PP);
188 PP->setPTHManager(PTHMgr);
189 }
190
191 InitializePreprocessor(*PP, PPOpts, HSOpts);
192
193 // Handle generating dependencies, if requested.
194 if (!DepOpts.OutputFile.empty())
195 AttachDependencyFileGen(*PP, DepOpts);
196
197 return PP;
198}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000199
200// ASTContext
201
202void CompilerInstance::createASTContext() {
203 Preprocessor &PP = getPreprocessor();
204 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
205 getTarget(), PP.getIdentifierTable(),
206 PP.getSelectorTable(), PP.getBuiltinInfo(),
207 /*FreeMemory=*/ !getFrontendOpts().DisableFree,
208 /*size_reserve=*/ 0));
209}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000210
211// ExternalASTSource
212
213void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) {
214 llvm::OwningPtr<ExternalASTSource> Source;
215 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
216 getPreprocessor(), getASTContext()));
217 getASTContext().setExternalSource(Source);
218}
219
220ExternalASTSource *
221CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
222 const std::string &Sysroot,
223 Preprocessor &PP,
224 ASTContext &Context) {
225 llvm::OwningPtr<PCHReader> Reader;
226 Reader.reset(new PCHReader(PP, &Context,
227 Sysroot.empty() ? 0 : Sysroot.c_str()));
228
229 switch (Reader->ReadPCH(Path)) {
230 case PCHReader::Success:
231 // Set the predefines buffer as suggested by the PCH reader. Typically, the
232 // predefines buffer will be empty.
233 PP.setPredefines(Reader->getSuggestedPredefines());
234 return Reader.take();
235
236 case PCHReader::Failure:
237 // Unrecoverable failure: don't even try to process the input file.
238 break;
239
240 case PCHReader::IgnorePCH:
241 // No suitable PCH file could be found. Return an error.
242 break;
243 }
244
245 return 0;
246}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000247
248// Code Completion
249
250void CompilerInstance::createCodeCompletionConsumer() {
251 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
252 CompletionConsumer.reset(
253 createCodeCompletionConsumer(getPreprocessor(),
254 Loc.FileName, Loc.Line, Loc.Column,
255 getFrontendOpts().DebugCodeCompletionPrinter,
256 getFrontendOpts().ShowMacrosInCodeCompletion,
257 llvm::outs()));
258}
259
260CodeCompleteConsumer *
261CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
262 const std::string &Filename,
263 unsigned Line,
264 unsigned Column,
265 bool UseDebugPrinter,
266 bool ShowMacros,
267 llvm::raw_ostream &OS) {
268 // Tell the source manager to chop off the given file at a specific
269 // line and column.
270 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
271 if (!Entry) {
272 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
273 << Filename;
274 return 0;
275 }
276
277 // Truncate the named file at the given line/column.
278 PP.getSourceManager().truncateFileAt(Entry, Line, Column);
279
280 // Set up the creation routine for code-completion.
281 if (UseDebugPrinter)
282 return new PrintingCodeCompleteConsumer(ShowMacros, OS);
283 else
284 return new CIndexCodeCompleteConsumer(ShowMacros, OS);
285}
Daniel Dunbara9204832009-11-13 10:37:48 +0000286
287// Output Files
288
289void CompilerInstance::addOutputFile(llvm::StringRef Path,
290 llvm::raw_ostream *OS) {
291 assert(OS && "Attempt to add empty stream to output list!");
292 OutputFiles.push_back(std::make_pair(Path, OS));
293}
294
295void CompilerInstance::ClearOutputFiles(bool EraseFiles) {
296 for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
297 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
298 delete it->second;
299 if (EraseFiles && !it->first.empty())
300 llvm::sys::Path(it->first).eraseFromDisk();
301 }
302 OutputFiles.clear();
303}
304
Daniel Dunbarf482d592009-11-13 18:32:08 +0000305llvm::raw_fd_ostream *
306CompilerInstance::createDefaultOutputFile(bool Binary,
307 llvm::StringRef InFile,
308 llvm::StringRef Extension) {
309 return createOutputFile(getFrontendOpts().OutputFile, Binary,
310 InFile, Extension);
311}
312
313llvm::raw_fd_ostream *
314CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
315 bool Binary,
316 llvm::StringRef InFile,
317 llvm::StringRef Extension) {
318 std::string Error, OutputPathName;
319 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
320 InFile, Extension,
321 &OutputPathName);
322 if (!OS) {
323 // FIXME: Don't fail this way.
324 llvm::errs() << "ERROR: " << Error << "\n";
325 ::exit(1);
326 }
327
328 // Add the output file -- but don't try to remove "-", since this means we are
329 // using stdin.
330 addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
331
332 return OS;
333}
334
335llvm::raw_fd_ostream *
336CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
337 std::string &Error,
338 bool Binary,
339 llvm::StringRef InFile,
340 llvm::StringRef Extension,
341 std::string *ResultPathName) {
342 std::string OutFile;
343 if (!OutputPath.empty()) {
344 OutFile = OutputPath;
345 } else if (InFile == "-") {
346 OutFile = "-";
347 } else if (!Extension.empty()) {
348 llvm::sys::Path Path(InFile);
349 Path.eraseSuffix();
350 Path.appendSuffix(Extension);
351 OutFile = Path.str();
352 } else {
353 OutFile = "-";
354 }
355
356 llvm::raw_fd_ostream *OS =
357 new llvm::raw_fd_ostream(OutFile.c_str(), Error,
358 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
359 if (!OS)
360 return 0;
361
362 if (ResultPathName)
363 *ResultPathName = OutFile;
364
365 return OS;
366}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000367
368// Initialization Utilities
369
370bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
371 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
372 getSourceManager(), getFrontendOpts());
373}
374
375bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
376 Diagnostic &Diags,
377 FileManager &FileMgr,
378 SourceManager &SourceMgr,
379 const FrontendOptions &Opts) {
380 // Figure out where to get and map in the main file.
381 if (Opts.EmptyInputOnly) {
382 const char *EmptyStr = "";
383 llvm::MemoryBuffer *SB =
384 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
385 SourceMgr.createMainFileIDForMemBuffer(SB);
386 } else if (InputFile != "-") {
387 const FileEntry *File = FileMgr.getFile(InputFile);
388 if (File) SourceMgr.createMainFileID(File, SourceLocation());
389 if (SourceMgr.getMainFileID().isInvalid()) {
390 Diags.Report(diag::err_fe_error_reading) << InputFile;
391 return false;
392 }
393 } else {
394 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
395 SourceMgr.createMainFileIDForMemBuffer(SB);
396 if (SourceMgr.getMainFileID().isInvalid()) {
397 Diags.Report(diag::err_fe_error_reading_stdin);
398 return false;
399 }
400 }
401
402 return true;
403}