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/AST/Decl.h" 14 #include "clang/Basic/Diagnostic.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/SourceManager.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/Version.h" 19 #include "clang/Frontend/ChainedDiagnosticConsumer.h" 20 #include "clang/Frontend/FrontendAction.h" 21 #include "clang/Frontend/FrontendActions.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Frontend/LogDiagnosticPrinter.h" 24 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 25 #include "clang/Frontend/TextDiagnosticPrinter.h" 26 #include "clang/Frontend/Utils.h" 27 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 28 #include "clang/Lex/HeaderSearch.h" 29 #include "clang/Lex/PTHManager.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CodeCompleteConsumer.h" 32 #include "clang/Sema/Sema.h" 33 #include "clang/Serialization/ASTReader.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Config/config.h" 36 #include "llvm/Support/CrashRecoveryContext.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Host.h" 39 #include "llvm/Support/LockFileManager.h" 40 #include "llvm/Support/MemoryBuffer.h" 41 #include "llvm/Support/Path.h" 42 #include "llvm/Support/Program.h" 43 #include "llvm/Support/Signals.h" 44 #include "llvm/Support/Timer.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Support/system_error.h" 47 48 using namespace clang; 49 50 CompilerInstance::CompilerInstance() 51 : Invocation(new CompilerInvocation()), ModuleManager(0), 52 BuildGlobalModuleIndex(false), ModuleBuildFailed(false) { 53 } 54 55 CompilerInstance::~CompilerInstance() { 56 assert(OutputFiles.empty() && "Still output files in flight?"); 57 } 58 59 void CompilerInstance::setInvocation(CompilerInvocation *Value) { 60 Invocation = Value; 61 } 62 63 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 64 return (BuildGlobalModuleIndex || 65 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() && 66 getFrontendOpts().GenerateGlobalModuleIndex)) && 67 !ModuleBuildFailed; 68 } 69 70 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 71 Diagnostics = Value; 72 } 73 74 void CompilerInstance::setTarget(TargetInfo *Value) { 75 Target = Value; 76 } 77 78 void CompilerInstance::setFileManager(FileManager *Value) { 79 FileMgr = Value; 80 } 81 82 void CompilerInstance::setSourceManager(SourceManager *Value) { 83 SourceMgr = Value; 84 } 85 86 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 87 88 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; } 89 90 void CompilerInstance::setSema(Sema *S) { 91 TheSema.reset(S); 92 } 93 94 void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 95 Consumer.reset(Value); 96 } 97 98 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 99 CompletionConsumer.reset(Value); 100 } 101 102 // Diagnostics 103 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 104 const CodeGenOptions *CodeGenOpts, 105 DiagnosticsEngine &Diags) { 106 std::string ErrorInfo; 107 bool OwnsStream = false; 108 raw_ostream *OS = &llvm::errs(); 109 if (DiagOpts->DiagnosticLogFile != "-") { 110 // Create the output stream. 111 llvm::raw_fd_ostream *FileOS( 112 new llvm::raw_fd_ostream(DiagOpts->DiagnosticLogFile.c_str(), 113 ErrorInfo, llvm::raw_fd_ostream::F_Append)); 114 if (!ErrorInfo.empty()) { 115 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 116 << DiagOpts->DiagnosticLogFile << ErrorInfo; 117 } else { 118 FileOS->SetUnbuffered(); 119 FileOS->SetUseAtomicWrites(true); 120 OS = FileOS; 121 OwnsStream = true; 122 } 123 } 124 125 // Chain in the diagnostic client which will log the diagnostics. 126 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts, 127 OwnsStream); 128 if (CodeGenOpts) 129 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 130 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 131 } 132 133 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 134 DiagnosticsEngine &Diags, 135 StringRef OutputFile) { 136 std::string ErrorInfo; 137 OwningPtr<llvm::raw_fd_ostream> OS; 138 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo, 139 llvm::raw_fd_ostream::F_Binary)); 140 141 if (!ErrorInfo.empty()) { 142 Diags.Report(diag::warn_fe_serialized_diag_failure) 143 << OutputFile << ErrorInfo; 144 return; 145 } 146 147 DiagnosticConsumer *SerializedConsumer = 148 clang::serialized_diags::create(OS.take(), DiagOpts); 149 150 151 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), 152 SerializedConsumer)); 153 } 154 155 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 156 bool ShouldOwnClient, 157 bool ShouldCloneClient) { 158 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 159 ShouldOwnClient, ShouldCloneClient, 160 &getCodeGenOpts()); 161 } 162 163 IntrusiveRefCntPtr<DiagnosticsEngine> 164 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 165 DiagnosticConsumer *Client, 166 bool ShouldOwnClient, 167 bool ShouldCloneClient, 168 const CodeGenOptions *CodeGenOpts) { 169 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 170 IntrusiveRefCntPtr<DiagnosticsEngine> 171 Diags(new DiagnosticsEngine(DiagID, Opts)); 172 173 // Create the diagnostic client for reporting errors or for 174 // implementing -verify. 175 if (Client) { 176 if (ShouldCloneClient) 177 Diags->setClient(Client->clone(*Diags), ShouldOwnClient); 178 else 179 Diags->setClient(Client, ShouldOwnClient); 180 } else 181 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 182 183 // Chain in -verify checker, if requested. 184 if (Opts->VerifyDiagnostics) 185 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 186 187 // Chain in -diagnostic-log-file dumper, if requested. 188 if (!Opts->DiagnosticLogFile.empty()) 189 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 190 191 if (!Opts->DiagnosticSerializationFile.empty()) 192 SetupSerializedDiagnostics(Opts, *Diags, 193 Opts->DiagnosticSerializationFile); 194 195 // Configure our handling of diagnostics. 196 ProcessWarningOptions(*Diags, *Opts); 197 198 return Diags; 199 } 200 201 // File Manager 202 203 void CompilerInstance::createFileManager() { 204 FileMgr = new FileManager(getFileSystemOpts()); 205 } 206 207 // Source Manager 208 209 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 210 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 211 } 212 213 // Preprocessor 214 215 void CompilerInstance::createPreprocessor() { 216 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 217 218 // Create a PTH manager if we are using some form of a token cache. 219 PTHManager *PTHMgr = 0; 220 if (!PPOpts.TokenCache.empty()) 221 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 222 223 // Create the Preprocessor. 224 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(), 225 getFileManager(), 226 getDiagnostics(), 227 getLangOpts(), 228 &getTarget()); 229 PP = new Preprocessor(&getPreprocessorOpts(), 230 getDiagnostics(), getLangOpts(), &getTarget(), 231 getSourceManager(), *HeaderInfo, *this, PTHMgr, 232 /*OwnsHeaderSearch=*/true); 233 234 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 235 // That argument is used as the IdentifierInfoLookup argument to 236 // IdentifierTable's ctor. 237 if (PTHMgr) { 238 PTHMgr->setPreprocessor(&*PP); 239 PP->setPTHManager(PTHMgr); 240 } 241 242 if (PPOpts.DetailedRecord) 243 PP->createPreprocessingRecord(); 244 245 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts()); 246 247 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 248 249 // Set up the module path, including the hash for the 250 // module-creation options. 251 SmallString<256> SpecificModuleCache( 252 getHeaderSearchOpts().ModuleCachePath); 253 if (!getHeaderSearchOpts().DisableModuleHash) 254 llvm::sys::path::append(SpecificModuleCache, 255 getInvocation().getModuleHash()); 256 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache); 257 258 // Handle generating dependencies, if requested. 259 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 260 if (!DepOpts.OutputFile.empty()) 261 AttachDependencyFileGen(*PP, DepOpts); 262 if (!DepOpts.DOTOutputFile.empty()) 263 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 264 getHeaderSearchOpts().Sysroot); 265 266 267 // Handle generating header include information, if requested. 268 if (DepOpts.ShowHeaderIncludes) 269 AttachHeaderIncludeGen(*PP); 270 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 271 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 272 if (OutputPath == "-") 273 OutputPath = ""; 274 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath, 275 /*ShowDepth=*/false); 276 } 277 } 278 279 // ASTContext 280 281 void CompilerInstance::createASTContext() { 282 Preprocessor &PP = getPreprocessor(); 283 Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 284 &getTarget(), PP.getIdentifierTable(), 285 PP.getSelectorTable(), PP.getBuiltinInfo(), 286 /*size_reserve=*/ 0); 287 } 288 289 // ExternalASTSource 290 291 void CompilerInstance::createPCHExternalASTSource(StringRef Path, 292 bool DisablePCHValidation, 293 bool AllowPCHWithCompilerErrors, 294 void *DeserializationListener){ 295 OwningPtr<ExternalASTSource> Source; 296 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 297 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 298 DisablePCHValidation, 299 AllowPCHWithCompilerErrors, 300 getPreprocessor(), getASTContext(), 301 DeserializationListener, 302 Preamble, 303 getFrontendOpts().UseGlobalModuleIndex)); 304 ModuleManager = static_cast<ASTReader*>(Source.get()); 305 getASTContext().setExternalSource(Source); 306 } 307 308 ExternalASTSource * 309 CompilerInstance::createPCHExternalASTSource(StringRef Path, 310 const std::string &Sysroot, 311 bool DisablePCHValidation, 312 bool AllowPCHWithCompilerErrors, 313 Preprocessor &PP, 314 ASTContext &Context, 315 void *DeserializationListener, 316 bool Preamble, 317 bool UseGlobalModuleIndex) { 318 OwningPtr<ASTReader> Reader; 319 Reader.reset(new ASTReader(PP, Context, 320 Sysroot.empty() ? "" : Sysroot.c_str(), 321 DisablePCHValidation, 322 AllowPCHWithCompilerErrors, 323 UseGlobalModuleIndex)); 324 325 Reader->setDeserializationListener( 326 static_cast<ASTDeserializationListener *>(DeserializationListener)); 327 switch (Reader->ReadAST(Path, 328 Preamble ? serialization::MK_Preamble 329 : serialization::MK_PCH, 330 SourceLocation(), 331 ASTReader::ARR_None)) { 332 case ASTReader::Success: 333 // Set the predefines buffer as suggested by the PCH reader. Typically, the 334 // predefines buffer will be empty. 335 PP.setPredefines(Reader->getSuggestedPredefines()); 336 return Reader.take(); 337 338 case ASTReader::Failure: 339 // Unrecoverable failure: don't even try to process the input file. 340 break; 341 342 case ASTReader::Missing: 343 case ASTReader::OutOfDate: 344 case ASTReader::VersionMismatch: 345 case ASTReader::ConfigurationMismatch: 346 case ASTReader::HadErrors: 347 // No suitable PCH file could be found. Return an error. 348 break; 349 } 350 351 return 0; 352 } 353 354 // Code Completion 355 356 static bool EnableCodeCompletion(Preprocessor &PP, 357 const std::string &Filename, 358 unsigned Line, 359 unsigned Column) { 360 // Tell the source manager to chop off the given file at a specific 361 // line and column. 362 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 363 if (!Entry) { 364 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 365 << Filename; 366 return true; 367 } 368 369 // Truncate the named file at the given line/column. 370 PP.SetCodeCompletionPoint(Entry, Line, Column); 371 return false; 372 } 373 374 void CompilerInstance::createCodeCompletionConsumer() { 375 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 376 if (!CompletionConsumer) { 377 setCodeCompletionConsumer( 378 createCodeCompletionConsumer(getPreprocessor(), 379 Loc.FileName, Loc.Line, Loc.Column, 380 getFrontendOpts().CodeCompleteOpts, 381 llvm::outs())); 382 if (!CompletionConsumer) 383 return; 384 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 385 Loc.Line, Loc.Column)) { 386 setCodeCompletionConsumer(0); 387 return; 388 } 389 390 if (CompletionConsumer->isOutputBinary() && 391 llvm::sys::Program::ChangeStdoutToBinary()) { 392 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 393 setCodeCompletionConsumer(0); 394 } 395 } 396 397 void CompilerInstance::createFrontendTimer() { 398 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 399 } 400 401 CodeCompleteConsumer * 402 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 403 const std::string &Filename, 404 unsigned Line, 405 unsigned Column, 406 const CodeCompleteOptions &Opts, 407 raw_ostream &OS) { 408 if (EnableCodeCompletion(PP, Filename, Line, Column)) 409 return 0; 410 411 // Set up the creation routine for code-completion. 412 return new PrintingCodeCompleteConsumer(Opts, OS); 413 } 414 415 void CompilerInstance::createSema(TranslationUnitKind TUKind, 416 CodeCompleteConsumer *CompletionConsumer) { 417 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 418 TUKind, CompletionConsumer)); 419 } 420 421 // Output Files 422 423 void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 424 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 425 OutputFiles.push_back(OutFile); 426 } 427 428 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 429 for (std::list<OutputFile>::iterator 430 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 431 delete it->OS; 432 if (!it->TempFilename.empty()) { 433 if (EraseFiles) { 434 bool existed; 435 llvm::sys::fs::remove(it->TempFilename, existed); 436 } else { 437 SmallString<128> NewOutFile(it->Filename); 438 439 // If '-working-directory' was passed, the output filename should be 440 // relative to that. 441 FileMgr->FixupRelativePath(NewOutFile); 442 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename, 443 NewOutFile.str())) { 444 getDiagnostics().Report(diag::err_unable_to_rename_temp) 445 << it->TempFilename << it->Filename << ec.message(); 446 447 bool existed; 448 llvm::sys::fs::remove(it->TempFilename, existed); 449 } 450 } 451 } else if (!it->Filename.empty() && EraseFiles) 452 llvm::sys::Path(it->Filename).eraseFromDisk(); 453 454 } 455 OutputFiles.clear(); 456 } 457 458 llvm::raw_fd_ostream * 459 CompilerInstance::createDefaultOutputFile(bool Binary, 460 StringRef InFile, 461 StringRef Extension) { 462 return createOutputFile(getFrontendOpts().OutputFile, Binary, 463 /*RemoveFileOnSignal=*/true, InFile, Extension, 464 /*UseTemporary=*/true); 465 } 466 467 llvm::raw_fd_ostream * 468 CompilerInstance::createOutputFile(StringRef OutputPath, 469 bool Binary, bool RemoveFileOnSignal, 470 StringRef InFile, 471 StringRef Extension, 472 bool UseTemporary, 473 bool CreateMissingDirectories) { 474 std::string Error, OutputPathName, TempPathName; 475 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 476 RemoveFileOnSignal, 477 InFile, Extension, 478 UseTemporary, 479 CreateMissingDirectories, 480 &OutputPathName, 481 &TempPathName); 482 if (!OS) { 483 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 484 << OutputPath << Error; 485 return 0; 486 } 487 488 // Add the output file -- but don't try to remove "-", since this means we are 489 // using stdin. 490 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 491 TempPathName, OS)); 492 493 return OS; 494 } 495 496 llvm::raw_fd_ostream * 497 CompilerInstance::createOutputFile(StringRef OutputPath, 498 std::string &Error, 499 bool Binary, 500 bool RemoveFileOnSignal, 501 StringRef InFile, 502 StringRef Extension, 503 bool UseTemporary, 504 bool CreateMissingDirectories, 505 std::string *ResultPathName, 506 std::string *TempPathName) { 507 assert((!CreateMissingDirectories || UseTemporary) && 508 "CreateMissingDirectories is only allowed when using temporary files"); 509 510 std::string OutFile, TempFile; 511 if (!OutputPath.empty()) { 512 OutFile = OutputPath; 513 } else if (InFile == "-") { 514 OutFile = "-"; 515 } else if (!Extension.empty()) { 516 llvm::sys::Path Path(InFile); 517 Path.eraseSuffix(); 518 Path.appendSuffix(Extension); 519 OutFile = Path.str(); 520 } else { 521 OutFile = "-"; 522 } 523 524 OwningPtr<llvm::raw_fd_ostream> OS; 525 std::string OSFile; 526 527 if (UseTemporary && OutFile != "-") { 528 // Only create the temporary if the parent directory exists (or create 529 // missing directories is true) and we can actually write to OutPath, 530 // otherwise we want to fail early. 531 SmallString<256> AbsPath(OutputPath); 532 llvm::sys::fs::make_absolute(AbsPath); 533 llvm::sys::Path OutPath(AbsPath); 534 bool ParentExists = false; 535 if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()), 536 ParentExists)) 537 ParentExists = false; 538 bool Exists; 539 if ((CreateMissingDirectories || ParentExists) && 540 ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) || 541 (OutPath.isRegularFile() && OutPath.canWrite()))) { 542 // Create a temporary file. 543 SmallString<128> TempPath; 544 TempPath = OutFile; 545 TempPath += "-%%%%%%%%"; 546 int fd; 547 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath, 548 /*makeAbsolute=*/false, 0664) 549 == llvm::errc::success) { 550 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 551 OSFile = TempFile = TempPath.str(); 552 } 553 } 554 } 555 556 if (!OS) { 557 OSFile = OutFile; 558 OS.reset( 559 new llvm::raw_fd_ostream(OSFile.c_str(), Error, 560 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 561 if (!Error.empty()) 562 return 0; 563 } 564 565 // Make sure the out stream file gets removed if we crash. 566 if (RemoveFileOnSignal) 567 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile)); 568 569 if (ResultPathName) 570 *ResultPathName = OutFile; 571 if (TempPathName) 572 *TempPathName = TempFile; 573 574 return OS.take(); 575 } 576 577 // Initialization Utilities 578 579 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 580 return InitializeSourceManager(Input, getDiagnostics(), 581 getFileManager(), getSourceManager(), 582 getFrontendOpts()); 583 } 584 585 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 586 DiagnosticsEngine &Diags, 587 FileManager &FileMgr, 588 SourceManager &SourceMgr, 589 const FrontendOptions &Opts) { 590 SrcMgr::CharacteristicKind 591 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 592 593 if (Input.isBuffer()) { 594 SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind); 595 assert(!SourceMgr.getMainFileID().isInvalid() && 596 "Couldn't establish MainFileID!"); 597 return true; 598 } 599 600 StringRef InputFile = Input.getFile(); 601 602 // Figure out where to get and map in the main file. 603 if (InputFile != "-") { 604 const FileEntry *File = FileMgr.getFile(InputFile); 605 if (!File) { 606 Diags.Report(diag::err_fe_error_reading) << InputFile; 607 return false; 608 } 609 610 // The natural SourceManager infrastructure can't currently handle named 611 // pipes, but we would at least like to accept them for the main 612 // file. Detect them here, read them with the more generic MemoryBuffer 613 // function, and simply override their contents as we do for STDIN. 614 if (File->isNamedPipe()) { 615 OwningPtr<llvm::MemoryBuffer> MB; 616 if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) { 617 Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message(); 618 return false; 619 } 620 621 // Create a new virtual file that will have the correct size. 622 File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0); 623 SourceMgr.overrideFileContents(File, MB.take()); 624 } 625 626 SourceMgr.createMainFileID(File, Kind); 627 } else { 628 OwningPtr<llvm::MemoryBuffer> SB; 629 if (llvm::MemoryBuffer::getSTDIN(SB)) { 630 // FIXME: Give ec.message() in this diag. 631 Diags.Report(diag::err_fe_error_reading_stdin); 632 return false; 633 } 634 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 635 SB->getBufferSize(), 0); 636 SourceMgr.createMainFileID(File, Kind); 637 SourceMgr.overrideFileContents(File, SB.take()); 638 } 639 640 assert(!SourceMgr.getMainFileID().isInvalid() && 641 "Couldn't establish MainFileID!"); 642 return true; 643 } 644 645 // High-Level Operations 646 647 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 648 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 649 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 650 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 651 652 // FIXME: Take this as an argument, once all the APIs we used have moved to 653 // taking it as an input instead of hard-coding llvm::errs. 654 raw_ostream &OS = llvm::errs(); 655 656 // Create the target instance. 657 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts())); 658 if (!hasTarget()) 659 return false; 660 661 // Inform the target of the language options. 662 // 663 // FIXME: We shouldn't need to do this, the target should be immutable once 664 // created. This complexity should be lifted elsewhere. 665 getTarget().setForcedLangOptions(getLangOpts()); 666 667 // rewriter project will change target built-in bool type from its default. 668 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 669 getTarget().noSignedCharForObjCBool(); 670 671 // Validate/process some options. 672 if (getHeaderSearchOpts().Verbose) 673 OS << "clang -cc1 version " CLANG_VERSION_STRING 674 << " based upon " << PACKAGE_STRING 675 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 676 677 if (getFrontendOpts().ShowTimers) 678 createFrontendTimer(); 679 680 if (getFrontendOpts().ShowStats) 681 llvm::EnableStatistics(); 682 683 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 684 // Reset the ID tables if we are reusing the SourceManager. 685 if (hasSourceManager()) 686 getSourceManager().clearIDTables(); 687 688 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) { 689 Act.Execute(); 690 Act.EndSourceFile(); 691 } 692 } 693 694 // Notify the diagnostic client that all files were processed. 695 getDiagnostics().getClient()->finish(); 696 697 if (getDiagnosticOpts().ShowCarets) { 698 // We can have multiple diagnostics sharing one diagnostic client. 699 // Get the total number of warnings/errors from the client. 700 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 701 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 702 703 if (NumWarnings) 704 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 705 if (NumWarnings && NumErrors) 706 OS << " and "; 707 if (NumErrors) 708 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 709 if (NumWarnings || NumErrors) 710 OS << " generated.\n"; 711 } 712 713 if (getFrontendOpts().ShowStats && hasFileManager()) { 714 getFileManager().PrintStats(); 715 OS << "\n"; 716 } 717 718 return !getDiagnostics().getClient()->getNumErrors(); 719 } 720 721 /// \brief Determine the appropriate source input kind based on language 722 /// options. 723 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 724 if (LangOpts.OpenCL) 725 return IK_OpenCL; 726 if (LangOpts.CUDA) 727 return IK_CUDA; 728 if (LangOpts.ObjC1) 729 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 730 return LangOpts.CPlusPlus? IK_CXX : IK_C; 731 } 732 733 namespace { 734 struct CompileModuleMapData { 735 CompilerInstance &Instance; 736 GenerateModuleAction &CreateModuleAction; 737 }; 738 } 739 740 /// \brief Helper function that executes the module-generating action under 741 /// a crash recovery context. 742 static void doCompileMapModule(void *UserData) { 743 CompileModuleMapData &Data 744 = *reinterpret_cast<CompileModuleMapData *>(UserData); 745 Data.Instance.ExecuteAction(Data.CreateModuleAction); 746 } 747 748 namespace { 749 /// \brief Function object that checks with the given macro definition should 750 /// be removed, because it is one of the ignored macros. 751 class RemoveIgnoredMacro { 752 const HeaderSearchOptions &HSOpts; 753 754 public: 755 explicit RemoveIgnoredMacro(const HeaderSearchOptions &HSOpts) 756 : HSOpts(HSOpts) { } 757 758 bool operator()(const std::pair<std::string, bool> &def) const { 759 StringRef MacroDef = def.first; 760 return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0; 761 } 762 }; 763 } 764 765 /// \brief Compile a module file for the given module, using the options 766 /// provided by the importing compiler instance. 767 static void compileModule(CompilerInstance &ImportingInstance, 768 SourceLocation ImportLoc, 769 Module *Module, 770 StringRef ModuleFileName) { 771 llvm::LockFileManager Locked(ModuleFileName); 772 switch (Locked) { 773 case llvm::LockFileManager::LFS_Error: 774 return; 775 776 case llvm::LockFileManager::LFS_Owned: 777 // We're responsible for building the module ourselves. Do so below. 778 break; 779 780 case llvm::LockFileManager::LFS_Shared: 781 // Someone else is responsible for building the module. Wait for them to 782 // finish. 783 Locked.waitForUnlock(); 784 return; 785 } 786 787 ModuleMap &ModMap 788 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 789 790 // Construct a compiler invocation for creating this module. 791 IntrusiveRefCntPtr<CompilerInvocation> Invocation 792 (new CompilerInvocation(ImportingInstance.getInvocation())); 793 794 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 795 796 // For any options that aren't intended to affect how a module is built, 797 // reset them to their default values. 798 Invocation->getLangOpts()->resetNonModularOptions(); 799 PPOpts.resetNonModularOptions(); 800 801 // Remove any macro definitions that are explicitly ignored by the module. 802 // They aren't supposed to affect how the module is built anyway. 803 const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 804 PPOpts.Macros.erase(std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(), 805 RemoveIgnoredMacro(HSOpts)), 806 PPOpts.Macros.end()); 807 808 809 // Note the name of the module we're building. 810 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName(); 811 812 // Make sure that the failed-module structure has been allocated in 813 // the importing instance, and propagate the pointer to the newly-created 814 // instance. 815 PreprocessorOptions &ImportingPPOpts 816 = ImportingInstance.getInvocation().getPreprocessorOpts(); 817 if (!ImportingPPOpts.FailedModules) 818 ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet; 819 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 820 821 // If there is a module map file, build the module using the module map. 822 // Set up the inputs/outputs so that we build the module from its umbrella 823 // header. 824 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 825 FrontendOpts.OutputFile = ModuleFileName.str(); 826 FrontendOpts.DisableFree = false; 827 FrontendOpts.GenerateGlobalModuleIndex = false; 828 FrontendOpts.Inputs.clear(); 829 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts()); 830 831 // Get or create the module map that we'll use to build this module. 832 SmallString<128> TempModuleMapFileName; 833 if (const FileEntry *ModuleMapFile 834 = ModMap.getContainingModuleMapFile(Module)) { 835 // Use the module map where this module resides. 836 FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(), 837 IK)); 838 } else { 839 // Create a temporary module map file. 840 TempModuleMapFileName = Module->Name; 841 TempModuleMapFileName += "-%%%%%%%%.map"; 842 int FD; 843 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD, 844 TempModuleMapFileName, 845 /*makeAbsolute=*/true) 846 != llvm::errc::success) { 847 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file) 848 << TempModuleMapFileName; 849 return; 850 } 851 // Print the module map to this file. 852 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true); 853 Module->print(OS); 854 FrontendOpts.Inputs.push_back( 855 FrontendInputFile(TempModuleMapFileName.str().str(), IK)); 856 } 857 858 // Don't free the remapped file buffers; they are owned by our caller. 859 PPOpts.RetainRemappedFileBuffers = true; 860 861 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 862 assert(ImportingInstance.getInvocation().getModuleHash() == 863 Invocation->getModuleHash() && "Module hash mismatch!"); 864 865 // Construct a compiler instance that will be used to actually create the 866 // module. 867 CompilerInstance Instance; 868 Instance.setInvocation(&*Invocation); 869 Instance.createDiagnostics(&ImportingInstance.getDiagnosticClient(), 870 /*ShouldOwnClient=*/true, 871 /*ShouldCloneClient=*/true); 872 873 // Note that this module is part of the module build stack, so that we 874 // can detect cycles in the module graph. 875 Instance.createFileManager(); // FIXME: Adopt file manager from importer? 876 Instance.createSourceManager(Instance.getFileManager()); 877 SourceManager &SourceMgr = Instance.getSourceManager(); 878 SourceMgr.setModuleBuildStack( 879 ImportingInstance.getSourceManager().getModuleBuildStack()); 880 SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(), 881 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 882 883 884 // Construct a module-generating action. 885 GenerateModuleAction CreateModuleAction; 886 887 // Execute the action to actually build the module in-place. Use a separate 888 // thread so that we get a stack large enough. 889 const unsigned ThreadStackSize = 8 << 20; 890 llvm::CrashRecoveryContext CRC; 891 CompileModuleMapData Data = { Instance, CreateModuleAction }; 892 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize); 893 894 // Delete the temporary module map file. 895 // FIXME: Even though we're executing under crash protection, it would still 896 // be nice to do this with RemoveFileOnSignal when we can. However, that 897 // doesn't make sense for all clients, so clean this up manually. 898 Instance.clearOutputFiles(/*EraseFiles=*/true); 899 if (!TempModuleMapFileName.empty()) 900 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk(); 901 902 // We've rebuilt a module. If we're allowed to generate or update the global 903 // module index, record that fact in the importing compiler instance. 904 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 905 ImportingInstance.setBuildGlobalModuleIndex(true); 906 } 907 } 908 909 /// \brief Diagnose differences between the current definition of the given 910 /// configuration macro and the definition provided on the command line. 911 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 912 Module *Mod, SourceLocation ImportLoc) { 913 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 914 SourceManager &SourceMgr = PP.getSourceManager(); 915 916 // If this identifier has never had a macro definition, then it could 917 // not have changed. 918 if (!Id->hadMacroDefinition()) 919 return; 920 921 // If this identifier does not currently have a macro definition, 922 // check whether it had one on the command line. 923 if (!Id->hasMacroDefinition()) { 924 MacroDirective *UndefMD = PP.getMacroDirectiveHistory(Id); 925 for (MacroDirective *MD = UndefMD; MD; MD = MD->getPrevious()) { 926 927 FileID FID = SourceMgr.getFileID(MD->getLocation()); 928 if (FID.isInvalid()) 929 continue; 930 931 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(FID); 932 if (!Buffer) 933 continue; 934 935 // We only care about the predefines buffer. 936 if (!StringRef(Buffer->getBufferIdentifier()).equals("<built-in>")) 937 continue; 938 939 // This macro was defined on the command line, then #undef'd later. 940 // Complain. 941 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 942 << true << ConfigMacro << Mod->getFullModuleName(); 943 if (UndefMD->getUndefLoc().isValid()) 944 PP.Diag(UndefMD->getUndefLoc(), diag::note_module_def_undef_here) 945 << true; 946 return; 947 } 948 949 // Okay: no definition in the predefines buffer. 950 return; 951 } 952 953 // This identifier has a macro definition. Check whether we had a definition 954 // on the command line. 955 MacroDirective *DefMD = PP.getMacroDirective(Id); 956 MacroDirective *PredefinedMD = 0; 957 for (MacroDirective *MD = DefMD; MD; MD = MD->getPrevious()) { 958 FileID FID = SourceMgr.getFileID(MD->getLocation()); 959 if (FID.isInvalid()) 960 continue; 961 962 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(FID); 963 if (!Buffer) 964 continue; 965 966 // We only care about the predefines buffer. 967 if (!StringRef(Buffer->getBufferIdentifier()).equals("<built-in>")) 968 continue; 969 970 PredefinedMD = MD; 971 break; 972 } 973 974 // If there was no definition for this macro in the predefines buffer, 975 // complain. 976 if (!PredefinedMD || 977 (!PredefinedMD->getLocation().isValid() && 978 PredefinedMD->getUndefLoc().isValid())) { 979 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 980 << false << ConfigMacro << Mod->getFullModuleName(); 981 PP.Diag(DefMD->getLocation(), diag::note_module_def_undef_here) 982 << false; 983 return; 984 } 985 986 // If the current macro definition is the same as the predefined macro 987 // definition, it's okay. 988 if (DefMD == PredefinedMD || 989 DefMD->getInfo()->isIdenticalTo(*PredefinedMD->getInfo(), PP)) 990 return; 991 992 // The macro definitions differ. 993 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 994 << false << ConfigMacro << Mod->getFullModuleName(); 995 PP.Diag(DefMD->getLocation(), diag::note_module_def_undef_here) 996 << false; 997 } 998 999 ModuleLoadResult 1000 CompilerInstance::loadModule(SourceLocation ImportLoc, 1001 ModuleIdPath Path, 1002 Module::NameVisibilityKind Visibility, 1003 bool IsInclusionDirective) { 1004 // If we've already handled this import, just return the cached result. 1005 // This one-element cache is important to eliminate redundant diagnostics 1006 // when both the preprocessor and parser see the same import declaration. 1007 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) { 1008 // Make the named module visible. 1009 if (LastModuleImportResult) 1010 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility, 1011 ImportLoc, /*Complain=*/false); 1012 return LastModuleImportResult; 1013 } 1014 1015 // Determine what file we're searching from. 1016 StringRef ModuleName = Path[0].first->getName(); 1017 SourceLocation ModuleNameLoc = Path[0].second; 1018 1019 clang::Module *Module = 0; 1020 1021 // If we don't already have information on this module, load the module now. 1022 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known 1023 = KnownModules.find(Path[0].first); 1024 if (Known != KnownModules.end()) { 1025 // Retrieve the cached top-level module. 1026 Module = Known->second; 1027 } else if (ModuleName == getLangOpts().CurrentModule) { 1028 // This is the module we're building. 1029 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName); 1030 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1031 } else { 1032 // Search for a module with the given name. 1033 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 1034 std::string ModuleFileName; 1035 if (Module) { 1036 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module); 1037 } else 1038 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName); 1039 1040 // If we don't already have an ASTReader, create one now. 1041 if (!ModuleManager) { 1042 if (!hasASTContext()) 1043 createASTContext(); 1044 1045 std::string Sysroot = getHeaderSearchOpts().Sysroot; 1046 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1047 ModuleManager = new ASTReader(getPreprocessor(), *Context, 1048 Sysroot.empty() ? "" : Sysroot.c_str(), 1049 PPOpts.DisablePCHValidation, 1050 /*AllowASTWithCompilerErrors=*/false, 1051 getFrontendOpts().UseGlobalModuleIndex); 1052 if (hasASTConsumer()) { 1053 ModuleManager->setDeserializationListener( 1054 getASTConsumer().GetASTDeserializationListener()); 1055 getASTContext().setASTMutationListener( 1056 getASTConsumer().GetASTMutationListener()); 1057 getPreprocessor().setPPMutationListener( 1058 getASTConsumer().GetPPMutationListener()); 1059 } 1060 OwningPtr<ExternalASTSource> Source; 1061 Source.reset(ModuleManager); 1062 getASTContext().setExternalSource(Source); 1063 if (hasSema()) 1064 ModuleManager->InitializeSema(getSema()); 1065 if (hasASTConsumer()) 1066 ModuleManager->StartTranslationUnit(&getASTConsumer()); 1067 } 1068 1069 // Try to load the module file. 1070 unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing; 1071 switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module, 1072 ImportLoc, ARRFlags)) { 1073 case ASTReader::Success: 1074 break; 1075 1076 case ASTReader::OutOfDate: { 1077 // The module file is out-of-date. Remove it, then rebuild it. 1078 bool Existed; 1079 llvm::sys::fs::remove(ModuleFileName, Existed); 1080 } 1081 // Fall through to build the module again. 1082 1083 case ASTReader::Missing: { 1084 // The module file is (now) missing. Build it. 1085 1086 // If we don't have a module, we don't know how to build the module file. 1087 // Complain and return. 1088 if (!Module) { 1089 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1090 << ModuleName 1091 << SourceRange(ImportLoc, ModuleNameLoc); 1092 ModuleBuildFailed = true; 1093 return ModuleLoadResult(); 1094 } 1095 1096 // Check whether there is a cycle in the module graph. 1097 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1098 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1099 for (; Pos != PosEnd; ++Pos) { 1100 if (Pos->first == ModuleName) 1101 break; 1102 } 1103 1104 if (Pos != PosEnd) { 1105 SmallString<256> CyclePath; 1106 for (; Pos != PosEnd; ++Pos) { 1107 CyclePath += Pos->first; 1108 CyclePath += " -> "; 1109 } 1110 CyclePath += ModuleName; 1111 1112 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1113 << ModuleName << CyclePath; 1114 return ModuleLoadResult(); 1115 } 1116 1117 // Check whether we have already attempted to build this module (but 1118 // failed). 1119 if (getPreprocessorOpts().FailedModules && 1120 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1121 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1122 << ModuleName 1123 << SourceRange(ImportLoc, ModuleNameLoc); 1124 ModuleBuildFailed = true; 1125 return ModuleLoadResult(); 1126 } 1127 1128 // Try to compile the module. 1129 compileModule(*this, ModuleNameLoc, Module, ModuleFileName); 1130 1131 // Try to read the module file, now that we've compiled it. 1132 ASTReader::ASTReadResult ReadResult 1133 = ModuleManager->ReadAST(ModuleFileName, 1134 serialization::MK_Module, ImportLoc, 1135 ASTReader::ARR_Missing); 1136 if (ReadResult != ASTReader::Success) { 1137 if (ReadResult == ASTReader::Missing) { 1138 getDiagnostics().Report(ModuleNameLoc, 1139 Module? diag::err_module_not_built 1140 : diag::err_module_not_found) 1141 << ModuleName 1142 << SourceRange(ImportLoc, ModuleNameLoc); 1143 } 1144 1145 if (getPreprocessorOpts().FailedModules) 1146 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1147 KnownModules[Path[0].first] = 0; 1148 ModuleBuildFailed = true; 1149 return ModuleLoadResult(); 1150 } 1151 1152 // Okay, we've rebuilt and now loaded the module. 1153 break; 1154 } 1155 1156 case ASTReader::VersionMismatch: 1157 case ASTReader::ConfigurationMismatch: 1158 case ASTReader::HadErrors: 1159 // FIXME: The ASTReader will already have complained, but can we showhorn 1160 // that diagnostic information into a more useful form? 1161 KnownModules[Path[0].first] = 0; 1162 return ModuleLoadResult(); 1163 1164 case ASTReader::Failure: 1165 // Already complained, but note now that we failed. 1166 KnownModules[Path[0].first] = 0; 1167 ModuleBuildFailed = true; 1168 return ModuleLoadResult(); 1169 } 1170 1171 if (!Module) { 1172 // If we loaded the module directly, without finding a module map first, 1173 // we'll have loaded the module's information from the module itself. 1174 Module = PP->getHeaderSearchInfo().getModuleMap() 1175 .findModule((Path[0].first->getName())); 1176 } 1177 1178 // Cache the result of this top-level module lookup for later. 1179 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1180 } 1181 1182 // If we never found the module, fail. 1183 if (!Module) 1184 return ModuleLoadResult(); 1185 1186 // Verify that the rest of the module path actually corresponds to 1187 // a submodule. 1188 if (Path.size() > 1) { 1189 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 1190 StringRef Name = Path[I].first->getName(); 1191 clang::Module *Sub = Module->findSubmodule(Name); 1192 1193 if (!Sub) { 1194 // Attempt to perform typo correction to find a module name that works. 1195 SmallVector<StringRef, 2> Best; 1196 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 1197 1198 for (clang::Module::submodule_iterator J = Module->submodule_begin(), 1199 JEnd = Module->submodule_end(); 1200 J != JEnd; ++J) { 1201 unsigned ED = Name.edit_distance((*J)->Name, 1202 /*AllowReplacements=*/true, 1203 BestEditDistance); 1204 if (ED <= BestEditDistance) { 1205 if (ED < BestEditDistance) { 1206 Best.clear(); 1207 BestEditDistance = ED; 1208 } 1209 1210 Best.push_back((*J)->Name); 1211 } 1212 } 1213 1214 // If there was a clear winner, user it. 1215 if (Best.size() == 1) { 1216 getDiagnostics().Report(Path[I].second, 1217 diag::err_no_submodule_suggest) 1218 << Path[I].first << Module->getFullModuleName() << Best[0] 1219 << SourceRange(Path[0].second, Path[I-1].second) 1220 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 1221 Best[0]); 1222 1223 Sub = Module->findSubmodule(Best[0]); 1224 } 1225 } 1226 1227 if (!Sub) { 1228 // No submodule by this name. Complain, and don't look for further 1229 // submodules. 1230 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 1231 << Path[I].first << Module->getFullModuleName() 1232 << SourceRange(Path[0].second, Path[I-1].second); 1233 break; 1234 } 1235 1236 Module = Sub; 1237 } 1238 } 1239 1240 // Make the named module visible, if it's not already part of the module 1241 // we are parsing. 1242 if (ModuleName != getLangOpts().CurrentModule) { 1243 if (!Module->IsFromModuleFile) { 1244 // We have an umbrella header or directory that doesn't actually include 1245 // all of the headers within the directory it covers. Complain about 1246 // this missing submodule and recover by forgetting that we ever saw 1247 // this submodule. 1248 // FIXME: Should we detect this at module load time? It seems fairly 1249 // expensive (and rare). 1250 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 1251 << Module->getFullModuleName() 1252 << SourceRange(Path.front().second, Path.back().second); 1253 1254 return ModuleLoadResult(0, true); 1255 } 1256 1257 // Check whether this module is available. 1258 StringRef Feature; 1259 if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) { 1260 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable) 1261 << Module->getFullModuleName() 1262 << Feature 1263 << SourceRange(Path.front().second, Path.back().second); 1264 LastModuleImportLoc = ImportLoc; 1265 LastModuleImportResult = ModuleLoadResult(); 1266 return ModuleLoadResult(); 1267 } 1268 1269 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc, 1270 /*Complain=*/true); 1271 } 1272 1273 // Check for any configuration macros that have changed. 1274 clang::Module *TopModule = Module->getTopLevelModule(); 1275 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 1276 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 1277 Module, ImportLoc); 1278 } 1279 1280 // If this module import was due to an inclusion directive, create an 1281 // implicit import declaration to capture it in the AST. 1282 if (IsInclusionDirective && hasASTContext()) { 1283 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 1284 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 1285 ImportLoc, Module, 1286 Path.back().second); 1287 TU->addDecl(ImportD); 1288 if (Consumer) 1289 Consumer->HandleImplicitImportDecl(ImportD); 1290 } 1291 1292 LastModuleImportLoc = ImportLoc; 1293 LastModuleImportResult = ModuleLoadResult(Module, false); 1294 return LastModuleImportResult; 1295 } 1296 1297 void CompilerInstance::makeModuleVisible(Module *Mod, 1298 Module::NameVisibilityKind Visibility, 1299 SourceLocation ImportLoc, 1300 bool Complain){ 1301 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain); 1302 } 1303 1304