CompilerInstance.cpp revision ffaab3e2bb13991bb3357e80f14bcae3745b2347
1//===--- 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"
11#include "clang/AST/ASTConsumer.h"
12#include "clang/AST/ASTContext.h"
13#include "clang/Basic/Diagnostic.h"
14#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Basic/Version.h"
18#include "clang/Lex/HeaderSearch.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/PTHManager.h"
21#include "clang/Frontend/ChainedDiagnosticClient.h"
22#include "clang/Frontend/FrontendAction.h"
23#include "clang/Frontend/PCHReader.h"
24#include "clang/Frontend/FrontendDiagnostic.h"
25#include "clang/Frontend/TextDiagnosticPrinter.h"
26#include "clang/Frontend/VerifyDiagnosticsClient.h"
27#include "clang/Frontend/Utils.h"
28#include "clang/Sema/CodeCompleteConsumer.h"
29#include "llvm/LLVMContext.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Support/Timer.h"
34#include "llvm/System/Host.h"
35#include "llvm/System/Path.h"
36#include "llvm/System/Program.h"
37using namespace clang;
38
39CompilerInstance::CompilerInstance()
40  : Invocation(new CompilerInvocation()) {
41}
42
43CompilerInstance::~CompilerInstance() {
44}
45
46void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
47  LLVMContext.reset(Value);
48}
49
50void CompilerInstance::setInvocation(CompilerInvocation *Value) {
51  Invocation.reset(Value);
52}
53
54void CompilerInstance::setDiagnostics(Diagnostic *Value) {
55  Diagnostics = Value;
56}
57
58void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) {
59  DiagClient.reset(Value);
60}
61
62void CompilerInstance::setTarget(TargetInfo *Value) {
63  Target.reset(Value);
64}
65
66void CompilerInstance::setFileManager(FileManager *Value) {
67  FileMgr.reset(Value);
68}
69
70void CompilerInstance::setSourceManager(SourceManager *Value) {
71  SourceMgr.reset(Value);
72}
73
74void CompilerInstance::setPreprocessor(Preprocessor *Value) {
75  PP.reset(Value);
76}
77
78void CompilerInstance::setASTContext(ASTContext *Value) {
79  Context.reset(Value);
80}
81
82void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
83  Consumer.reset(Value);
84}
85
86void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
87  CompletionConsumer.reset(Value);
88}
89
90// Diagnostics
91namespace {
92  class BinaryDiagnosticSerializer : public DiagnosticClient {
93    llvm::raw_ostream &OS;
94    SourceManager *SourceMgr;
95  public:
96    explicit BinaryDiagnosticSerializer(llvm::raw_ostream &OS)
97      : OS(OS), SourceMgr(0) { }
98
99    virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
100                                  const DiagnosticInfo &Info);
101  };
102}
103
104void BinaryDiagnosticSerializer::HandleDiagnostic(Diagnostic::Level DiagLevel,
105                                                  const DiagnosticInfo &Info) {
106  StoredDiagnostic(DiagLevel, Info).Serialize(OS);
107}
108
109static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
110                              unsigned argc, char **argv,
111                              Diagnostic &Diags) {
112  std::string ErrorInfo;
113  llvm::OwningPtr<llvm::raw_ostream> OS(
114    new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
115  if (!ErrorInfo.empty()) {
116    Diags.Report(diag::err_fe_unable_to_open_logfile)
117                 << DiagOpts.DumpBuildInformation << ErrorInfo;
118    return;
119  }
120
121  (*OS) << "clang -cc1 command line arguments: ";
122  for (unsigned i = 0; i != argc; ++i)
123    (*OS) << argv[i] << ' ';
124  (*OS) << '\n';
125
126  // Chain in a diagnostic client which will log the diagnostics.
127  DiagnosticClient *Logger =
128    new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
129  Diags.setClient(new ChainedDiagnosticClient(Diags.getClient(), Logger));
130}
131
132void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
133  Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv);
134
135  if (Diagnostics)
136    DiagClient.reset(Diagnostics->getClient());
137}
138
139llvm::IntrusiveRefCntPtr<Diagnostic>
140CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
141                                    int Argc, char **Argv) {
142  llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic());
143
144  // Create the diagnostic client for reporting errors or for
145  // implementing -verify.
146  llvm::OwningPtr<DiagnosticClient> DiagClient;
147  if (Opts.BinaryOutput) {
148    if (llvm::sys::Program::ChangeStderrToBinary()) {
149      // We weren't able to set standard error to binary, which is a
150      // bit of a problem. So, just create a text diagnostic printer
151      // to complain about this problem, and pretend that the user
152      // didn't try to use binary output.
153      DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
154      Diags->setClient(DiagClient.take());
155      Diags->Report(diag::err_fe_stderr_binary);
156      return Diags;
157    } else {
158      DiagClient.reset(new BinaryDiagnosticSerializer(llvm::errs()));
159    }
160  } else {
161    DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
162  }
163
164  // Chain in -verify checker, if requested.
165  if (Opts.VerifyDiagnostics)
166    DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take()));
167
168  Diags->setClient(DiagClient.take());
169  if (!Opts.DumpBuildInformation.empty())
170    SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
171
172  // Configure our handling of diagnostics.
173  ProcessWarningOptions(*Diags, Opts);
174
175  return Diags;
176}
177
178// File Manager
179
180void CompilerInstance::createFileManager() {
181  FileMgr.reset(new FileManager());
182}
183
184// Source Manager
185
186void CompilerInstance::createSourceManager() {
187  SourceMgr.reset(new SourceManager(getDiagnostics()));
188}
189
190// Preprocessor
191
192void CompilerInstance::createPreprocessor() {
193  PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
194                              getPreprocessorOpts(), getHeaderSearchOpts(),
195                              getDependencyOutputOpts(), getTarget(),
196                              getFrontendOpts(), getSourceManager(),
197                              getFileManager()));
198}
199
200Preprocessor *
201CompilerInstance::createPreprocessor(Diagnostic &Diags,
202                                     const LangOptions &LangInfo,
203                                     const PreprocessorOptions &PPOpts,
204                                     const HeaderSearchOptions &HSOpts,
205                                     const DependencyOutputOptions &DepOpts,
206                                     const TargetInfo &Target,
207                                     const FrontendOptions &FEOpts,
208                                     SourceManager &SourceMgr,
209                                     FileManager &FileMgr) {
210  // Create a PTH manager if we are using some form of a token cache.
211  PTHManager *PTHMgr = 0;
212  if (!PPOpts.TokenCache.empty())
213    PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
214
215  // Create the Preprocessor.
216  HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
217  Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
218                                      SourceMgr, *HeaderInfo, PTHMgr,
219                                      /*OwnsHeaderSearch=*/true);
220
221  // Note that this is different then passing PTHMgr to Preprocessor's ctor.
222  // That argument is used as the IdentifierInfoLookup argument to
223  // IdentifierTable's ctor.
224  if (PTHMgr) {
225    PTHMgr->setPreprocessor(PP);
226    PP->setPTHManager(PTHMgr);
227  }
228
229  if (PPOpts.DetailedRecord)
230    PP->createPreprocessingRecord();
231
232  InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
233
234  // Handle generating dependencies, if requested.
235  if (!DepOpts.OutputFile.empty())
236    AttachDependencyFileGen(*PP, DepOpts);
237
238  return PP;
239}
240
241// ASTContext
242
243void CompilerInstance::createASTContext() {
244  Preprocessor &PP = getPreprocessor();
245  Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
246                               getTarget(), PP.getIdentifierTable(),
247                               PP.getSelectorTable(), PP.getBuiltinInfo(),
248                               /*size_reserve=*/ 0));
249}
250
251// ExternalASTSource
252
253void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
254                                                  bool DisablePCHValidation,
255                                                 void *DeserializationListener){
256  llvm::OwningPtr<ExternalASTSource> Source;
257  Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
258                                          DisablePCHValidation,
259                                          getPreprocessor(), getASTContext(),
260                                          DeserializationListener));
261  getASTContext().setExternalSource(Source);
262}
263
264ExternalASTSource *
265CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
266                                             const std::string &Sysroot,
267                                             bool DisablePCHValidation,
268                                             Preprocessor &PP,
269                                             ASTContext &Context,
270                                             void *DeserializationListener) {
271  llvm::OwningPtr<PCHReader> Reader;
272  Reader.reset(new PCHReader(PP, &Context,
273                             Sysroot.empty() ? 0 : Sysroot.c_str(),
274                             DisablePCHValidation));
275
276  Reader->setDeserializationListener(
277            static_cast<PCHDeserializationListener *>(DeserializationListener));
278  switch (Reader->ReadPCH(Path)) {
279  case PCHReader::Success:
280    // Set the predefines buffer as suggested by the PCH reader. Typically, the
281    // predefines buffer will be empty.
282    PP.setPredefines(Reader->getSuggestedPredefines());
283    return Reader.take();
284
285  case PCHReader::Failure:
286    // Unrecoverable failure: don't even try to process the input file.
287    break;
288
289  case PCHReader::IgnorePCH:
290    // No suitable PCH file could be found. Return an error.
291    break;
292  }
293
294  return 0;
295}
296
297// Code Completion
298
299void CompilerInstance::createCodeCompletionConsumer() {
300  const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
301  CompletionConsumer.reset(
302    createCodeCompletionConsumer(getPreprocessor(),
303                                 Loc.FileName, Loc.Line, Loc.Column,
304                                 getFrontendOpts().DebugCodeCompletionPrinter,
305                                 getFrontendOpts().ShowMacrosInCodeCompletion,
306                             getFrontendOpts().ShowCodePatternsInCodeCompletion,
307                                 llvm::outs()));
308  if (!CompletionConsumer)
309    return;
310
311  if (CompletionConsumer->isOutputBinary() &&
312      llvm::sys::Program::ChangeStdoutToBinary()) {
313    getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
314    CompletionConsumer.reset();
315  }
316}
317
318void CompilerInstance::createFrontendTimer() {
319  FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
320}
321
322CodeCompleteConsumer *
323CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
324                                               const std::string &Filename,
325                                               unsigned Line,
326                                               unsigned Column,
327                                               bool UseDebugPrinter,
328                                               bool ShowMacros,
329                                               bool ShowCodePatterns,
330                                               llvm::raw_ostream &OS) {
331  // Tell the source manager to chop off the given file at a specific
332  // line and column.
333  const FileEntry *Entry = PP.getFileManager().getFile(Filename);
334  if (!Entry) {
335    PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
336      << Filename;
337    return 0;
338  }
339
340  // Truncate the named file at the given line/column.
341  PP.SetCodeCompletionPoint(Entry, Line, Column);
342
343  // Set up the creation routine for code-completion.
344  if (UseDebugPrinter)
345    return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns, OS);
346  else
347    return new CIndexCodeCompleteConsumer(ShowMacros, ShowCodePatterns, OS);
348}
349
350// Output Files
351
352void CompilerInstance::addOutputFile(llvm::StringRef Path,
353                                     llvm::raw_ostream *OS) {
354  assert(OS && "Attempt to add empty stream to output list!");
355  OutputFiles.push_back(std::make_pair(Path, OS));
356}
357
358void CompilerInstance::clearOutputFiles(bool EraseFiles) {
359  for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
360         it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
361    delete it->second;
362    if (EraseFiles && !it->first.empty())
363      llvm::sys::Path(it->first).eraseFromDisk();
364  }
365  OutputFiles.clear();
366}
367
368llvm::raw_fd_ostream *
369CompilerInstance::createDefaultOutputFile(bool Binary,
370                                          llvm::StringRef InFile,
371                                          llvm::StringRef Extension) {
372  return createOutputFile(getFrontendOpts().OutputFile, Binary,
373                          InFile, Extension);
374}
375
376llvm::raw_fd_ostream *
377CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
378                                   bool Binary,
379                                   llvm::StringRef InFile,
380                                   llvm::StringRef Extension) {
381  std::string Error, OutputPathName;
382  llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
383                                              InFile, Extension,
384                                              &OutputPathName);
385  if (!OS) {
386    getDiagnostics().Report(diag::err_fe_unable_to_open_output)
387      << OutputPath << Error;
388    return 0;
389  }
390
391  // Add the output file -- but don't try to remove "-", since this means we are
392  // using stdin.
393  addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
394
395  return OS;
396}
397
398llvm::raw_fd_ostream *
399CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
400                                   std::string &Error,
401                                   bool Binary,
402                                   llvm::StringRef InFile,
403                                   llvm::StringRef Extension,
404                                   std::string *ResultPathName) {
405  std::string OutFile;
406  if (!OutputPath.empty()) {
407    OutFile = OutputPath;
408  } else if (InFile == "-") {
409    OutFile = "-";
410  } else if (!Extension.empty()) {
411    llvm::sys::Path Path(InFile);
412    Path.eraseSuffix();
413    Path.appendSuffix(Extension);
414    OutFile = Path.str();
415  } else {
416    OutFile = "-";
417  }
418
419  llvm::OwningPtr<llvm::raw_fd_ostream> OS(
420    new llvm::raw_fd_ostream(OutFile.c_str(), Error,
421                             (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
422  if (!Error.empty())
423    return 0;
424
425  if (ResultPathName)
426    *ResultPathName = OutFile;
427
428  return OS.take();
429}
430
431// Initialization Utilities
432
433bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
434  return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
435                                 getSourceManager(), getFrontendOpts());
436}
437
438bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
439                                               Diagnostic &Diags,
440                                               FileManager &FileMgr,
441                                               SourceManager &SourceMgr,
442                                               const FrontendOptions &Opts) {
443  // Figure out where to get and map in the main file.
444  if (InputFile != "-") {
445    const FileEntry *File = FileMgr.getFile(InputFile);
446    if (File) SourceMgr.createMainFileID(File, SourceLocation());
447    if (SourceMgr.getMainFileID().isInvalid()) {
448      Diags.Report(diag::err_fe_error_reading) << InputFile;
449      return false;
450    }
451  } else {
452    llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
453    if (SB) SourceMgr.createMainFileIDForMemBuffer(SB);
454    if (SourceMgr.getMainFileID().isInvalid()) {
455      Diags.Report(diag::err_fe_error_reading_stdin);
456      return false;
457    }
458  }
459
460  return true;
461}
462
463// High-Level Operations
464
465bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
466  assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
467  assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
468  assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
469
470  // FIXME: Take this as an argument, once all the APIs we used have moved to
471  // taking it as an input instead of hard-coding llvm::errs.
472  llvm::raw_ostream &OS = llvm::errs();
473
474  // Create the target instance.
475  setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
476  if (!hasTarget())
477    return false;
478
479  // Inform the target of the language options.
480  //
481  // FIXME: We shouldn't need to do this, the target should be immutable once
482  // created. This complexity should be lifted elsewhere.
483  getTarget().setForcedLangOptions(getLangOpts());
484
485  // Validate/process some options.
486  if (getHeaderSearchOpts().Verbose)
487    OS << "clang -cc1 version " CLANG_VERSION_STRING
488       << " based upon " << PACKAGE_STRING
489       << " hosted on " << llvm::sys::getHostTriple() << "\n";
490
491  if (getFrontendOpts().ShowTimers)
492    createFrontendTimer();
493
494  if (getFrontendOpts().ShowStats)
495    llvm::EnableStatistics();
496
497  for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
498    const std::string &InFile = getFrontendOpts().Inputs[i].second;
499
500    // Reset the ID tables if we are reusing the SourceManager.
501    if (hasSourceManager())
502      getSourceManager().clearIDTables();
503
504    if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
505      Act.Execute();
506      Act.EndSourceFile();
507    }
508  }
509
510  if (getDiagnosticOpts().ShowCarets) {
511    unsigned NumWarnings = getDiagnostics().getNumWarnings();
512    unsigned NumErrors = getDiagnostics().getNumErrors() -
513                               getDiagnostics().getNumErrorsSuppressed();
514
515    if (NumWarnings)
516      OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
517    if (NumWarnings && NumErrors)
518      OS << " and ";
519    if (NumErrors)
520      OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
521    if (NumWarnings || NumErrors)
522      OS << " generated.\n";
523  }
524
525  if (getFrontendOpts().ShowStats && hasFileManager()) {
526    getFileManager().PrintStats();
527    OS << "\n";
528  }
529
530  // Return the appropriate status when verifying diagnostics.
531  //
532  // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
533  // this.
534  if (getDiagnosticOpts().VerifyDiagnostics)
535    return !static_cast<VerifyDiagnosticsClient&>(
536      getDiagnosticClient()).HadErrors();
537
538  return !getDiagnostics().getNumErrors();
539}
540
541
542