CompilerInstance.cpp revision 199482
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/System/Path.h" 31using namespace clang; 32 33CompilerInstance::CompilerInstance(llvm::LLVMContext *_LLVMContext, 34 bool _OwnsLLVMContext) 35 : LLVMContext(_LLVMContext), 36 OwnsLLVMContext(_OwnsLLVMContext) { 37 } 38 39CompilerInstance::~CompilerInstance() { 40 if (OwnsLLVMContext) 41 delete LLVMContext; 42} 43 44void 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 72void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 73 Consumer.reset(Value); 74} 75 76void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 77 CompletionConsumer.reset(Value); 78} 79 80// 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) { 116 llvm::OwningPtr<Diagnostic> Diags(new Diagnostic()); 117 118 // Create the diagnostic client for reporting errors or for 119 // implementing -verify. 120 llvm::OwningPtr<DiagnosticClient> DiagClient( 121 new TextDiagnosticPrinter(llvm::errs(), Opts)); 122 123 // Chain in -verify checker, if requested. 124 if (Opts.VerifyDiagnostics) 125 DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take())); 126 127 if (!Opts.DumpBuildInformation.empty()) 128 SetUpBuildDumpLog(Opts, Argc, Argv, DiagClient); 129 130 // Configure our handling of diagnostics. 131 Diags->setClient(DiagClient.take()); 132 if (ProcessWarningOptions(*Diags, Opts)) 133 return 0; 134 135 return Diags.take(); 136} 137 138// File Manager 139 140void CompilerInstance::createFileManager() { 141 FileMgr.reset(new FileManager()); 142} 143 144// Source Manager 145 146void CompilerInstance::createSourceManager() { 147 SourceMgr.reset(new SourceManager()); 148} 149 150// Preprocessor 151 152void 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; 170 if (!PPOpts.TokenCache.empty()) 171 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags); 172 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} 199 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} 210 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} 247 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} 286 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 305llvm::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} 367 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} 404