CompilerInstance.cpp revision c39b3079a8b2d69091a368c5f2f7aa2a6a5845ce
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/Lex/HeaderSearch.h" 18#include "clang/Lex/Preprocessor.h" 19#include "clang/Lex/PTHManager.h" 20#include "clang/Frontend/ChainedDiagnosticClient.h" 21#include "clang/Frontend/PCHReader.h" 22#include "clang/Frontend/FrontendDiagnostic.h" 23#include "clang/Frontend/TextDiagnosticPrinter.h" 24#include "clang/Frontend/VerifyDiagnosticsClient.h" 25#include "clang/Frontend/Utils.h" 26#include "clang/Sema/CodeCompleteConsumer.h" 27#include "llvm/LLVMContext.h" 28#include "llvm/Support/MemoryBuffer.h" 29#include "llvm/Support/raw_ostream.h" 30#include "llvm/Support/Timer.h" 31#include "llvm/System/Path.h" 32#include "llvm/System/Program.h" 33using namespace clang; 34 35CompilerInstance::CompilerInstance(llvm::LLVMContext *_LLVMContext, 36 bool _OwnsLLVMContext) 37 : LLVMContext(_LLVMContext), 38 OwnsLLVMContext(_OwnsLLVMContext) { 39 } 40 41CompilerInstance::~CompilerInstance() { 42 if (OwnsLLVMContext) 43 delete LLVMContext; 44} 45 46void 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 74void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 75 Consumer.reset(Value); 76} 77 78void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 79 CompletionConsumer.reset(Value); 80} 81 82// 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) { 118 llvm::OwningPtr<Diagnostic> Diags(new Diagnostic()); 119 120 // Create the diagnostic client for reporting errors or for 121 // implementing -verify. 122 llvm::OwningPtr<DiagnosticClient> DiagClient( 123 new TextDiagnosticPrinter(llvm::errs(), Opts)); 124 125 // Chain in -verify checker, if requested. 126 if (Opts.VerifyDiagnostics) 127 DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take())); 128 129 if (!Opts.DumpBuildInformation.empty()) 130 SetUpBuildDumpLog(Opts, Argc, Argv, DiagClient); 131 132 // Configure our handling of diagnostics. 133 Diags->setClient(DiagClient.take()); 134 if (ProcessWarningOptions(*Diags, Opts)) 135 return 0; 136 137 return Diags.take(); 138} 139 140// File Manager 141 142void CompilerInstance::createFileManager() { 143 FileMgr.reset(new FileManager()); 144} 145 146// Source Manager 147 148void CompilerInstance::createSourceManager() { 149 SourceMgr.reset(new SourceManager()); 150} 151 152// Preprocessor 153 154void 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; 172 if (!PPOpts.TokenCache.empty()) 173 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags); 174 175 // FIXME: Don't fail like this. 176 if (Diags.hasErrorOccurred()) 177 exit(1); 178 179 // Create the Preprocessor. 180 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr); 181 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target, 182 SourceMgr, *HeaderInfo, PTHMgr, 183 /*OwnsHeaderSearch=*/true); 184 185 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 186 // That argument is used as the IdentifierInfoLookup argument to 187 // IdentifierTable's ctor. 188 if (PTHMgr) { 189 PTHMgr->setPreprocessor(PP); 190 PP->setPTHManager(PTHMgr); 191 } 192 193 InitializePreprocessor(*PP, PPOpts, HSOpts); 194 195 // Handle generating dependencies, if requested. 196 if (!DepOpts.OutputFile.empty()) 197 AttachDependencyFileGen(*PP, DepOpts); 198 199 return PP; 200} 201 202// ASTContext 203 204void CompilerInstance::createASTContext() { 205 Preprocessor &PP = getPreprocessor(); 206 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(), 207 getTarget(), PP.getIdentifierTable(), 208 PP.getSelectorTable(), PP.getBuiltinInfo(), 209 /*FreeMemory=*/ !getFrontendOpts().DisableFree, 210 /*size_reserve=*/ 0)); 211} 212 213// ExternalASTSource 214 215void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) { 216 llvm::OwningPtr<ExternalASTSource> Source; 217 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 218 getPreprocessor(), getASTContext())); 219 getASTContext().setExternalSource(Source); 220} 221 222ExternalASTSource * 223CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path, 224 const std::string &Sysroot, 225 Preprocessor &PP, 226 ASTContext &Context) { 227 llvm::OwningPtr<PCHReader> Reader; 228 Reader.reset(new PCHReader(PP, &Context, 229 Sysroot.empty() ? 0 : Sysroot.c_str())); 230 231 switch (Reader->ReadPCH(Path)) { 232 case PCHReader::Success: 233 // Set the predefines buffer as suggested by the PCH reader. Typically, the 234 // predefines buffer will be empty. 235 PP.setPredefines(Reader->getSuggestedPredefines()); 236 return Reader.take(); 237 238 case PCHReader::Failure: 239 // Unrecoverable failure: don't even try to process the input file. 240 break; 241 242 case PCHReader::IgnorePCH: 243 // No suitable PCH file could be found. Return an error. 244 break; 245 } 246 247 return 0; 248} 249 250// Code Completion 251 252void CompilerInstance::createCodeCompletionConsumer() { 253 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 254 CompletionConsumer.reset( 255 createCodeCompletionConsumer(getPreprocessor(), 256 Loc.FileName, Loc.Line, Loc.Column, 257 getFrontendOpts().DebugCodeCompletionPrinter, 258 getFrontendOpts().ShowMacrosInCodeCompletion, 259 llvm::outs())); 260 261 if (CompletionConsumer->isOutputBinary() && 262 llvm::sys::Program::ChangeStdoutToBinary()) { 263 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 264 CompletionConsumer.reset(); 265 } 266} 267 268void CompilerInstance::createFrontendTimer() { 269 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 270} 271 272CodeCompleteConsumer * 273CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 274 const std::string &Filename, 275 unsigned Line, 276 unsigned Column, 277 bool UseDebugPrinter, 278 bool ShowMacros, 279 llvm::raw_ostream &OS) { 280 // Tell the source manager to chop off the given file at a specific 281 // line and column. 282 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 283 if (!Entry) { 284 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 285 << Filename; 286 return 0; 287 } 288 289 // Truncate the named file at the given line/column. 290 PP.SetCodeCompletionPoint(Entry, Line, Column); 291 292 // Set up the creation routine for code-completion. 293 if (UseDebugPrinter) 294 return new PrintingCodeCompleteConsumer(ShowMacros, OS); 295 else 296 return new CIndexCodeCompleteConsumer(ShowMacros, OS); 297} 298 299// Output Files 300 301void CompilerInstance::addOutputFile(llvm::StringRef Path, 302 llvm::raw_ostream *OS) { 303 assert(OS && "Attempt to add empty stream to output list!"); 304 OutputFiles.push_back(std::make_pair(Path, OS)); 305} 306 307void CompilerInstance::ClearOutputFiles(bool EraseFiles) { 308 for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator 309 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 310 delete it->second; 311 if (EraseFiles && !it->first.empty()) 312 llvm::sys::Path(it->first).eraseFromDisk(); 313 } 314 OutputFiles.clear(); 315} 316 317llvm::raw_fd_ostream * 318CompilerInstance::createDefaultOutputFile(bool Binary, 319 llvm::StringRef InFile, 320 llvm::StringRef Extension) { 321 return createOutputFile(getFrontendOpts().OutputFile, Binary, 322 InFile, Extension); 323} 324 325llvm::raw_fd_ostream * 326CompilerInstance::createOutputFile(llvm::StringRef OutputPath, 327 bool Binary, 328 llvm::StringRef InFile, 329 llvm::StringRef Extension) { 330 std::string Error, OutputPathName; 331 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 332 InFile, Extension, 333 &OutputPathName); 334 if (!OS) { 335 // FIXME: Don't fail this way. 336 llvm::errs() << "error: " << Error << "\n"; 337 ::exit(1); 338 } 339 340 // Add the output file -- but don't try to remove "-", since this means we are 341 // using stdin. 342 addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS); 343 344 return OS; 345} 346 347llvm::raw_fd_ostream * 348CompilerInstance::createOutputFile(llvm::StringRef OutputPath, 349 std::string &Error, 350 bool Binary, 351 llvm::StringRef InFile, 352 llvm::StringRef Extension, 353 std::string *ResultPathName) { 354 std::string OutFile; 355 if (!OutputPath.empty()) { 356 OutFile = OutputPath; 357 } else if (InFile == "-") { 358 OutFile = "-"; 359 } else if (!Extension.empty()) { 360 llvm::sys::Path Path(InFile); 361 Path.eraseSuffix(); 362 Path.appendSuffix(Extension); 363 OutFile = Path.str(); 364 } else { 365 OutFile = "-"; 366 } 367 368 llvm::OwningPtr<llvm::raw_fd_ostream> OS( 369 new llvm::raw_fd_ostream(OutFile.c_str(), Error, 370 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 371 if (!Error.empty()) 372 return 0; 373 374 if (ResultPathName) 375 *ResultPathName = OutFile; 376 377 return OS.take(); 378} 379 380// Initialization Utilities 381 382bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) { 383 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(), 384 getSourceManager(), getFrontendOpts()); 385} 386 387bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile, 388 Diagnostic &Diags, 389 FileManager &FileMgr, 390 SourceManager &SourceMgr, 391 const FrontendOptions &Opts) { 392 // Figure out where to get and map in the main file. 393 if (Opts.EmptyInputOnly) { 394 const char *EmptyStr = ""; 395 llvm::MemoryBuffer *SB = 396 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>"); 397 SourceMgr.createMainFileIDForMemBuffer(SB); 398 } else if (InputFile != "-") { 399 const FileEntry *File = FileMgr.getFile(InputFile); 400 if (File) SourceMgr.createMainFileID(File, SourceLocation()); 401 if (SourceMgr.getMainFileID().isInvalid()) { 402 Diags.Report(diag::err_fe_error_reading) << InputFile; 403 return false; 404 } 405 } else { 406 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN(); 407 SourceMgr.createMainFileIDForMemBuffer(SB); 408 if (SourceMgr.getMainFileID().isInvalid()) { 409 Diags.Report(diag::err_fe_error_reading_stdin); 410 return false; 411 } 412 } 413 414 return true; 415} 416