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