clang API Documentation

CompilerInstance.cpp
Go to the documentation of this file.
00001 //===--- CompilerInstance.cpp ---------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/Frontend/CompilerInstance.h"
00011 #include "clang/AST/ASTConsumer.h"
00012 #include "clang/AST/ASTContext.h"
00013 #include "clang/AST/Decl.h"
00014 #include "clang/Basic/Diagnostic.h"
00015 #include "clang/Basic/FileManager.h"
00016 #include "clang/Basic/SourceManager.h"
00017 #include "clang/Basic/TargetInfo.h"
00018 #include "clang/Basic/Version.h"
00019 #include "clang/Config/config.h"
00020 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
00021 #include "clang/Frontend/FrontendAction.h"
00022 #include "clang/Frontend/FrontendActions.h"
00023 #include "clang/Frontend/FrontendDiagnostic.h"
00024 #include "clang/Frontend/LogDiagnosticPrinter.h"
00025 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
00026 #include "clang/Frontend/TextDiagnosticPrinter.h"
00027 #include "clang/Frontend/Utils.h"
00028 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
00029 #include "clang/Lex/HeaderSearch.h"
00030 #include "clang/Lex/PTHManager.h"
00031 #include "clang/Lex/Preprocessor.h"
00032 #include "clang/Sema/CodeCompleteConsumer.h"
00033 #include "clang/Sema/Sema.h"
00034 #include "clang/Serialization/ASTReader.h"
00035 #include "clang/Serialization/GlobalModuleIndex.h"
00036 #include "llvm/ADT/Statistic.h"
00037 #include "llvm/Support/CrashRecoveryContext.h"
00038 #include "llvm/Support/Errc.h"
00039 #include "llvm/Support/FileSystem.h"
00040 #include "llvm/Support/Host.h"
00041 #include "llvm/Support/LockFileManager.h"
00042 #include "llvm/Support/MemoryBuffer.h"
00043 #include "llvm/Support/Path.h"
00044 #include "llvm/Support/Program.h"
00045 #include "llvm/Support/Signals.h"
00046 #include "llvm/Support/Timer.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include <sys/stat.h>
00049 #include <system_error>
00050 #include <time.h>
00051 
00052 using namespace clang;
00053 
00054 CompilerInstance::CompilerInstance(bool BuildingModule)
00055   : ModuleLoader(BuildingModule),
00056     Invocation(new CompilerInvocation()), ModuleManager(nullptr),
00057     BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
00058     ModuleBuildFailed(false) {
00059 }
00060 
00061 CompilerInstance::~CompilerInstance() {
00062   assert(OutputFiles.empty() && "Still output files in flight?");
00063 }
00064 
00065 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
00066   Invocation = Value;
00067 }
00068 
00069 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
00070   return (BuildGlobalModuleIndex ||
00071           (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
00072            getFrontendOpts().GenerateGlobalModuleIndex)) &&
00073          !ModuleBuildFailed;
00074 }
00075 
00076 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
00077   Diagnostics = Value;
00078 }
00079 
00080 void CompilerInstance::setTarget(TargetInfo *Value) {
00081   Target = Value;
00082 }
00083 
00084 void CompilerInstance::setFileManager(FileManager *Value) {
00085   FileMgr = Value;
00086   if (Value)
00087     VirtualFileSystem = Value->getVirtualFileSystem();
00088   else
00089     VirtualFileSystem.reset();
00090 }
00091 
00092 void CompilerInstance::setSourceManager(SourceManager *Value) {
00093   SourceMgr = Value;
00094 }
00095 
00096 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
00097 
00098 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
00099 
00100 void CompilerInstance::setSema(Sema *S) {
00101   TheSema.reset(S);
00102 }
00103 
00104 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
00105   Consumer = std::move(Value);
00106 }
00107 
00108 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
00109   CompletionConsumer.reset(Value);
00110 }
00111 
00112 std::unique_ptr<Sema> CompilerInstance::takeSema() {
00113   return std::move(TheSema);
00114 }
00115 
00116 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
00117   return ModuleManager;
00118 }
00119 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
00120   ModuleManager = Reader;
00121 }
00122 
00123 std::shared_ptr<ModuleDependencyCollector>
00124 CompilerInstance::getModuleDepCollector() const {
00125   return ModuleDepCollector;
00126 }
00127 
00128 void CompilerInstance::setModuleDepCollector(
00129     std::shared_ptr<ModuleDependencyCollector> Collector) {
00130   ModuleDepCollector = Collector;
00131 }
00132 
00133 // Diagnostics
00134 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
00135                                const CodeGenOptions *CodeGenOpts,
00136                                DiagnosticsEngine &Diags) {
00137   std::error_code EC;
00138   std::unique_ptr<raw_ostream> StreamOwner;
00139   raw_ostream *OS = &llvm::errs();
00140   if (DiagOpts->DiagnosticLogFile != "-") {
00141     // Create the output stream.
00142     auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
00143         DiagOpts->DiagnosticLogFile, EC,
00144         llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
00145     if (EC) {
00146       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
00147           << DiagOpts->DiagnosticLogFile << EC.message();
00148     } else {
00149       FileOS->SetUnbuffered();
00150       FileOS->SetUseAtomicWrites(true);
00151       OS = FileOS.get();
00152       StreamOwner = std::move(FileOS);
00153     }
00154   }
00155 
00156   // Chain in the diagnostic client which will log the diagnostics.
00157   auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
00158                                                         std::move(StreamOwner));
00159   if (CodeGenOpts)
00160     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
00161   assert(Diags.ownsClient());
00162   Diags.setClient(
00163       new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
00164 }
00165 
00166 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
00167                                        DiagnosticsEngine &Diags,
00168                                        StringRef OutputFile) {
00169   auto SerializedConsumer =
00170       clang::serialized_diags::create(OutputFile, DiagOpts);
00171 
00172   if (Diags.ownsClient()) {
00173     Diags.setClient(new ChainedDiagnosticConsumer(
00174         Diags.takeClient(), std::move(SerializedConsumer)));
00175   } else {
00176     Diags.setClient(new ChainedDiagnosticConsumer(
00177         Diags.getClient(), std::move(SerializedConsumer)));
00178   }
00179 }
00180 
00181 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
00182                                          bool ShouldOwnClient) {
00183   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
00184                                   ShouldOwnClient, &getCodeGenOpts());
00185 }
00186 
00187 IntrusiveRefCntPtr<DiagnosticsEngine>
00188 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
00189                                     DiagnosticConsumer *Client,
00190                                     bool ShouldOwnClient,
00191                                     const CodeGenOptions *CodeGenOpts) {
00192   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
00193   IntrusiveRefCntPtr<DiagnosticsEngine>
00194       Diags(new DiagnosticsEngine(DiagID, Opts));
00195 
00196   // Create the diagnostic client for reporting errors or for
00197   // implementing -verify.
00198   if (Client) {
00199     Diags->setClient(Client, ShouldOwnClient);
00200   } else
00201     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
00202 
00203   // Chain in -verify checker, if requested.
00204   if (Opts->VerifyDiagnostics)
00205     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
00206 
00207   // Chain in -diagnostic-log-file dumper, if requested.
00208   if (!Opts->DiagnosticLogFile.empty())
00209     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
00210 
00211   if (!Opts->DiagnosticSerializationFile.empty())
00212     SetupSerializedDiagnostics(Opts, *Diags,
00213                                Opts->DiagnosticSerializationFile);
00214   
00215   // Configure our handling of diagnostics.
00216   ProcessWarningOptions(*Diags, *Opts);
00217 
00218   return Diags;
00219 }
00220 
00221 // File Manager
00222 
00223 void CompilerInstance::createFileManager() {
00224   if (!hasVirtualFileSystem()) {
00225     // TODO: choose the virtual file system based on the CompilerInvocation.
00226     setVirtualFileSystem(vfs::getRealFileSystem());
00227   }
00228   FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
00229 }
00230 
00231 // Source Manager
00232 
00233 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
00234   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
00235 }
00236 
00237 // Initialize the remapping of files to alternative contents, e.g.,
00238 // those specified through other files.
00239 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
00240                                     SourceManager &SourceMgr,
00241                                     FileManager &FileMgr,
00242                                     const PreprocessorOptions &InitOpts) {
00243   // Remap files in the source manager (with buffers).
00244   for (const auto &RB : InitOpts.RemappedFileBuffers) {
00245     // Create the file entry for the file that we're mapping from.
00246     const FileEntry *FromFile =
00247         FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
00248     if (!FromFile) {
00249       Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
00250       if (!InitOpts.RetainRemappedFileBuffers)
00251         delete RB.second;
00252       continue;
00253     }
00254 
00255     // Override the contents of the "from" file with the contents of
00256     // the "to" file.
00257     SourceMgr.overrideFileContents(FromFile, RB.second,
00258                                    InitOpts.RetainRemappedFileBuffers);
00259   }
00260 
00261   // Remap files in the source manager (with other files).
00262   for (const auto &RF : InitOpts.RemappedFiles) {
00263     // Find the file that we're mapping to.
00264     const FileEntry *ToFile = FileMgr.getFile(RF.second);
00265     if (!ToFile) {
00266       Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
00267       continue;
00268     }
00269 
00270     // Create the file entry for the file that we're mapping from.
00271     const FileEntry *FromFile =
00272         FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
00273     if (!FromFile) {
00274       Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
00275       continue;
00276     }
00277 
00278     // Override the contents of the "from" file with the contents of
00279     // the "to" file.
00280     SourceMgr.overrideFileContents(FromFile, ToFile);
00281   }
00282 
00283   SourceMgr.setOverridenFilesKeepOriginalName(
00284       InitOpts.RemappedFilesKeepOriginalName);
00285 }
00286 
00287 // Preprocessor
00288 
00289 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
00290   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
00291 
00292   // Create a PTH manager if we are using some form of a token cache.
00293   PTHManager *PTHMgr = nullptr;
00294   if (!PPOpts.TokenCache.empty())
00295     PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
00296 
00297   // Create the Preprocessor.
00298   HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
00299                                               getSourceManager(),
00300                                               getDiagnostics(),
00301                                               getLangOpts(),
00302                                               &getTarget());
00303   PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
00304                         getSourceManager(), *HeaderInfo, *this, PTHMgr,
00305                         /*OwnsHeaderSearch=*/true, TUKind);
00306   PP->Initialize(getTarget());
00307 
00308   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
00309   // That argument is used as the IdentifierInfoLookup argument to
00310   // IdentifierTable's ctor.
00311   if (PTHMgr) {
00312     PTHMgr->setPreprocessor(&*PP);
00313     PP->setPTHManager(PTHMgr);
00314   }
00315 
00316   if (PPOpts.DetailedRecord)
00317     PP->createPreprocessingRecord();
00318 
00319   // Apply remappings to the source manager.
00320   InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
00321                           PP->getFileManager(), PPOpts);
00322 
00323   // Predefine macros and configure the preprocessor.
00324   InitializePreprocessor(*PP, PPOpts, getFrontendOpts());
00325 
00326   // Initialize the header search object.
00327   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
00328                            PP->getLangOpts(), PP->getTargetInfo().getTriple());
00329 
00330   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
00331 
00332   // Set up the module path, including the hash for the
00333   // module-creation options.
00334   SmallString<256> SpecificModuleCache(
00335                            getHeaderSearchOpts().ModuleCachePath);
00336   if (!getHeaderSearchOpts().DisableModuleHash)
00337     llvm::sys::path::append(SpecificModuleCache,
00338                             getInvocation().getModuleHash());
00339   PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
00340 
00341   // Handle generating dependencies, if requested.
00342   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
00343   if (!DepOpts.OutputFile.empty())
00344     TheDependencyFileGenerator.reset(
00345         DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
00346   if (!DepOpts.DOTOutputFile.empty())
00347     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
00348                              getHeaderSearchOpts().Sysroot);
00349 
00350   for (auto &Listener : DependencyCollectors)
00351     Listener->attachToPreprocessor(*PP);
00352 
00353   // If we don't have a collector, but we are collecting module dependencies,
00354   // then we're the top level compiler instance and need to create one.
00355   if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty())
00356     ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
00357         DepOpts.ModuleDependencyOutputDir);
00358 
00359   // Handle generating header include information, if requested.
00360   if (DepOpts.ShowHeaderIncludes)
00361     AttachHeaderIncludeGen(*PP);
00362   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
00363     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
00364     if (OutputPath == "-")
00365       OutputPath = "";
00366     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
00367                            /*ShowDepth=*/false);
00368   }
00369 
00370   if (DepOpts.PrintShowIncludes) {
00371     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
00372                            /*ShowDepth=*/true, /*MSStyle=*/true);
00373   }
00374 }
00375 
00376 // ASTContext
00377 
00378 void CompilerInstance::createASTContext() {
00379   Preprocessor &PP = getPreprocessor();
00380   Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
00381                            PP.getIdentifierTable(), PP.getSelectorTable(),
00382                            PP.getBuiltinInfo());
00383   Context->InitBuiltinTypes(getTarget());
00384 }
00385 
00386 // ExternalASTSource
00387 
00388 void CompilerInstance::createPCHExternalASTSource(
00389     StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
00390     void *DeserializationListener, bool OwnDeserializationListener) {
00391   IntrusiveRefCntPtr<ExternalASTSource> Source;
00392   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
00393   Source = createPCHExternalASTSource(
00394       Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
00395       AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
00396       DeserializationListener, OwnDeserializationListener, Preamble,
00397       getFrontendOpts().UseGlobalModuleIndex);
00398   ModuleManager = static_cast<ASTReader*>(Source.get());
00399   getASTContext().setExternalSource(Source);
00400 }
00401 
00402 ExternalASTSource *CompilerInstance::createPCHExternalASTSource(
00403     StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
00404     bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
00405     void *DeserializationListener, bool OwnDeserializationListener,
00406     bool Preamble, bool UseGlobalModuleIndex) {
00407   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
00408 
00409   std::unique_ptr<ASTReader> Reader;
00410   Reader.reset(new ASTReader(PP, Context,
00411                              Sysroot.empty() ? "" : Sysroot.c_str(),
00412                              DisablePCHValidation,
00413                              AllowPCHWithCompilerErrors,
00414                              /*AllowConfigurationMismatch*/false,
00415                              HSOpts.ModulesValidateSystemHeaders,
00416                              UseGlobalModuleIndex));
00417 
00418   Reader->setDeserializationListener(
00419       static_cast<ASTDeserializationListener *>(DeserializationListener),
00420       /*TakeOwnership=*/OwnDeserializationListener);
00421   switch (Reader->ReadAST(Path,
00422                           Preamble ? serialization::MK_Preamble
00423                                    : serialization::MK_PCH,
00424                           SourceLocation(),
00425                           ASTReader::ARR_None)) {
00426   case ASTReader::Success:
00427     // Set the predefines buffer as suggested by the PCH reader. Typically, the
00428     // predefines buffer will be empty.
00429     PP.setPredefines(Reader->getSuggestedPredefines());
00430     return Reader.release();
00431 
00432   case ASTReader::Failure:
00433     // Unrecoverable failure: don't even try to process the input file.
00434     break;
00435 
00436   case ASTReader::Missing:
00437   case ASTReader::OutOfDate:
00438   case ASTReader::VersionMismatch:
00439   case ASTReader::ConfigurationMismatch:
00440   case ASTReader::HadErrors:
00441     // No suitable PCH file could be found. Return an error.
00442     break;
00443   }
00444 
00445   return nullptr;
00446 }
00447 
00448 // Code Completion
00449 
00450 static bool EnableCodeCompletion(Preprocessor &PP,
00451                                  const std::string &Filename,
00452                                  unsigned Line,
00453                                  unsigned Column) {
00454   // Tell the source manager to chop off the given file at a specific
00455   // line and column.
00456   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
00457   if (!Entry) {
00458     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
00459       << Filename;
00460     return true;
00461   }
00462 
00463   // Truncate the named file at the given line/column.
00464   PP.SetCodeCompletionPoint(Entry, Line, Column);
00465   return false;
00466 }
00467 
00468 void CompilerInstance::createCodeCompletionConsumer() {
00469   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
00470   if (!CompletionConsumer) {
00471     setCodeCompletionConsumer(
00472       createCodeCompletionConsumer(getPreprocessor(),
00473                                    Loc.FileName, Loc.Line, Loc.Column,
00474                                    getFrontendOpts().CodeCompleteOpts,
00475                                    llvm::outs()));
00476     if (!CompletionConsumer)
00477       return;
00478   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
00479                                   Loc.Line, Loc.Column)) {
00480     setCodeCompletionConsumer(nullptr);
00481     return;
00482   }
00483 
00484   if (CompletionConsumer->isOutputBinary() &&
00485       llvm::sys::ChangeStdoutToBinary()) {
00486     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
00487     setCodeCompletionConsumer(nullptr);
00488   }
00489 }
00490 
00491 void CompilerInstance::createFrontendTimer() {
00492   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
00493 }
00494 
00495 CodeCompleteConsumer *
00496 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
00497                                                const std::string &Filename,
00498                                                unsigned Line,
00499                                                unsigned Column,
00500                                                const CodeCompleteOptions &Opts,
00501                                                raw_ostream &OS) {
00502   if (EnableCodeCompletion(PP, Filename, Line, Column))
00503     return nullptr;
00504 
00505   // Set up the creation routine for code-completion.
00506   return new PrintingCodeCompleteConsumer(Opts, OS);
00507 }
00508 
00509 void CompilerInstance::createSema(TranslationUnitKind TUKind,
00510                                   CodeCompleteConsumer *CompletionConsumer) {
00511   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
00512                          TUKind, CompletionConsumer));
00513 }
00514 
00515 // Output Files
00516 
00517 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
00518   assert(OutFile.OS && "Attempt to add empty stream to output list!");
00519   OutputFiles.push_back(OutFile);
00520 }
00521 
00522 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
00523   for (std::list<OutputFile>::iterator
00524          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
00525     delete it->OS;
00526     if (!it->TempFilename.empty()) {
00527       if (EraseFiles) {
00528         llvm::sys::fs::remove(it->TempFilename);
00529       } else {
00530         SmallString<128> NewOutFile(it->Filename);
00531 
00532         // If '-working-directory' was passed, the output filename should be
00533         // relative to that.
00534         FileMgr->FixupRelativePath(NewOutFile);
00535         if (std::error_code ec =
00536                 llvm::sys::fs::rename(it->TempFilename, NewOutFile.str())) {
00537           getDiagnostics().Report(diag::err_unable_to_rename_temp)
00538             << it->TempFilename << it->Filename << ec.message();
00539 
00540           llvm::sys::fs::remove(it->TempFilename);
00541         }
00542       }
00543     } else if (!it->Filename.empty() && EraseFiles)
00544       llvm::sys::fs::remove(it->Filename);
00545 
00546   }
00547   OutputFiles.clear();
00548 }
00549 
00550 llvm::raw_fd_ostream *
00551 CompilerInstance::createDefaultOutputFile(bool Binary,
00552                                           StringRef InFile,
00553                                           StringRef Extension) {
00554   return createOutputFile(getFrontendOpts().OutputFile, Binary,
00555                           /*RemoveFileOnSignal=*/true, InFile, Extension,
00556                           /*UseTemporary=*/true);
00557 }
00558 
00559 llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
00560   llvm::raw_null_ostream *OS = new llvm::raw_null_ostream();
00561   addOutputFile(OutputFile("", "", OS));
00562   return OS;
00563 }
00564 
00565 llvm::raw_fd_ostream *
00566 CompilerInstance::createOutputFile(StringRef OutputPath,
00567                                    bool Binary, bool RemoveFileOnSignal,
00568                                    StringRef InFile,
00569                                    StringRef Extension,
00570                                    bool UseTemporary,
00571                                    bool CreateMissingDirectories) {
00572   std::string OutputPathName, TempPathName;
00573   std::error_code EC;
00574   llvm::raw_fd_ostream *OS = createOutputFile(
00575       OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
00576       UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
00577   if (!OS) {
00578     getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
00579                                                                 << EC.message();
00580     return nullptr;
00581   }
00582 
00583   // Add the output file -- but don't try to remove "-", since this means we are
00584   // using stdin.
00585   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
00586                 TempPathName, OS));
00587 
00588   return OS;
00589 }
00590 
00591 llvm::raw_fd_ostream *CompilerInstance::createOutputFile(
00592     StringRef OutputPath, std::error_code &Error, bool Binary,
00593     bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
00594     bool UseTemporary, bool CreateMissingDirectories,
00595     std::string *ResultPathName, std::string *TempPathName) {
00596   assert((!CreateMissingDirectories || UseTemporary) &&
00597          "CreateMissingDirectories is only allowed when using temporary files");
00598 
00599   std::string OutFile, TempFile;
00600   if (!OutputPath.empty()) {
00601     OutFile = OutputPath;
00602   } else if (InFile == "-") {
00603     OutFile = "-";
00604   } else if (!Extension.empty()) {
00605     SmallString<128> Path(InFile);
00606     llvm::sys::path::replace_extension(Path, Extension);
00607     OutFile = Path.str();
00608   } else {
00609     OutFile = "-";
00610   }
00611 
00612   std::unique_ptr<llvm::raw_fd_ostream> OS;
00613   std::string OSFile;
00614 
00615   if (UseTemporary) {
00616     if (OutFile == "-")
00617       UseTemporary = false;
00618     else {
00619       llvm::sys::fs::file_status Status;
00620       llvm::sys::fs::status(OutputPath, Status);
00621       if (llvm::sys::fs::exists(Status)) {
00622         // Fail early if we can't write to the final destination.
00623         if (!llvm::sys::fs::can_write(OutputPath))
00624           return nullptr;
00625 
00626         // Don't use a temporary if the output is a special file. This handles
00627         // things like '-o /dev/null'
00628         if (!llvm::sys::fs::is_regular_file(Status))
00629           UseTemporary = false;
00630       }
00631     }
00632   }
00633 
00634   if (UseTemporary) {
00635     // Create a temporary file.
00636     SmallString<128> TempPath;
00637     TempPath = OutFile;
00638     TempPath += "-%%%%%%%%";
00639     int fd;
00640     std::error_code EC =
00641         llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
00642 
00643     if (CreateMissingDirectories &&
00644         EC == llvm::errc::no_such_file_or_directory) {
00645       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
00646       EC = llvm::sys::fs::create_directories(Parent);
00647       if (!EC) {
00648         EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
00649       }
00650     }
00651 
00652     if (!EC) {
00653       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
00654       OSFile = TempFile = TempPath.str();
00655     }
00656     // If we failed to create the temporary, fallback to writing to the file
00657     // directly. This handles the corner case where we cannot write to the
00658     // directory, but can write to the file.
00659   }
00660 
00661   if (!OS) {
00662     OSFile = OutFile;
00663     OS.reset(new llvm::raw_fd_ostream(
00664         OSFile, Error,
00665         (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
00666     if (Error)
00667       return nullptr;
00668   }
00669 
00670   // Make sure the out stream file gets removed if we crash.
00671   if (RemoveFileOnSignal)
00672     llvm::sys::RemoveFileOnSignal(OSFile);
00673 
00674   if (ResultPathName)
00675     *ResultPathName = OutFile;
00676   if (TempPathName)
00677     *TempPathName = TempFile;
00678 
00679   return OS.release();
00680 }
00681 
00682 // Initialization Utilities
00683 
00684 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
00685   return InitializeSourceManager(Input, getDiagnostics(),
00686                                  getFileManager(), getSourceManager(), 
00687                                  getFrontendOpts());
00688 }
00689 
00690 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
00691                                                DiagnosticsEngine &Diags,
00692                                                FileManager &FileMgr,
00693                                                SourceManager &SourceMgr,
00694                                                const FrontendOptions &Opts) {
00695   SrcMgr::CharacteristicKind
00696     Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
00697 
00698   if (Input.isBuffer()) {
00699     SourceMgr.setMainFileID(SourceMgr.createFileID(
00700         std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
00701     assert(!SourceMgr.getMainFileID().isInvalid() &&
00702            "Couldn't establish MainFileID!");
00703     return true;
00704   }
00705 
00706   StringRef InputFile = Input.getFile();
00707 
00708   // Figure out where to get and map in the main file.
00709   if (InputFile != "-") {
00710     const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
00711     if (!File) {
00712       Diags.Report(diag::err_fe_error_reading) << InputFile;
00713       return false;
00714     }
00715 
00716     // The natural SourceManager infrastructure can't currently handle named
00717     // pipes, but we would at least like to accept them for the main
00718     // file. Detect them here, read them with the volatile flag so FileMgr will
00719     // pick up the correct size, and simply override their contents as we do for
00720     // STDIN.
00721     if (File->isNamedPipe()) {
00722       auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
00723       if (MB) {
00724         // Create a new virtual file that will have the correct size.
00725         File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
00726         SourceMgr.overrideFileContents(File, std::move(*MB));
00727       } else {
00728         Diags.Report(diag::err_cannot_open_file) << InputFile
00729                                                  << MB.getError().message();
00730         return false;
00731       }
00732     }
00733 
00734     SourceMgr.setMainFileID(
00735         SourceMgr.createFileID(File, SourceLocation(), Kind));
00736   } else {
00737     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
00738         llvm::MemoryBuffer::getSTDIN();
00739     if (std::error_code EC = SBOrErr.getError()) {
00740       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
00741       return false;
00742     }
00743     std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
00744 
00745     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
00746                                                    SB->getBufferSize(), 0);
00747     SourceMgr.setMainFileID(
00748         SourceMgr.createFileID(File, SourceLocation(), Kind));
00749     SourceMgr.overrideFileContents(File, std::move(SB));
00750   }
00751 
00752   assert(!SourceMgr.getMainFileID().isInvalid() &&
00753          "Couldn't establish MainFileID!");
00754   return true;
00755 }
00756 
00757 // High-Level Operations
00758 
00759 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
00760   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
00761   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
00762   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
00763 
00764   // FIXME: Take this as an argument, once all the APIs we used have moved to
00765   // taking it as an input instead of hard-coding llvm::errs.
00766   raw_ostream &OS = llvm::errs();
00767 
00768   // Create the target instance.
00769   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
00770                                          getInvocation().TargetOpts));
00771   if (!hasTarget())
00772     return false;
00773 
00774   // Inform the target of the language options.
00775   //
00776   // FIXME: We shouldn't need to do this, the target should be immutable once
00777   // created. This complexity should be lifted elsewhere.
00778   getTarget().adjust(getLangOpts());
00779 
00780   // rewriter project will change target built-in bool type from its default. 
00781   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
00782     getTarget().noSignedCharForObjCBool();
00783 
00784   // Validate/process some options.
00785   if (getHeaderSearchOpts().Verbose)
00786     OS << "clang -cc1 version " CLANG_VERSION_STRING
00787        << " based upon " << BACKEND_PACKAGE_STRING
00788        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
00789 
00790   if (getFrontendOpts().ShowTimers)
00791     createFrontendTimer();
00792 
00793   if (getFrontendOpts().ShowStats)
00794     llvm::EnableStatistics();
00795 
00796   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
00797     // Reset the ID tables if we are reusing the SourceManager and parsing
00798     // regular files.
00799     if (hasSourceManager() && !Act.isModelParsingAction())
00800       getSourceManager().clearIDTables();
00801 
00802     if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
00803       Act.Execute();
00804       Act.EndSourceFile();
00805     }
00806   }
00807 
00808   // Notify the diagnostic client that all files were processed.
00809   getDiagnostics().getClient()->finish();
00810 
00811   if (getDiagnosticOpts().ShowCarets) {
00812     // We can have multiple diagnostics sharing one diagnostic client.
00813     // Get the total number of warnings/errors from the client.
00814     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
00815     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
00816 
00817     if (NumWarnings)
00818       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
00819     if (NumWarnings && NumErrors)
00820       OS << " and ";
00821     if (NumErrors)
00822       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
00823     if (NumWarnings || NumErrors)
00824       OS << " generated.\n";
00825   }
00826 
00827   if (getFrontendOpts().ShowStats && hasFileManager()) {
00828     getFileManager().PrintStats();
00829     OS << "\n";
00830   }
00831 
00832   return !getDiagnostics().getClient()->getNumErrors();
00833 }
00834 
00835 /// \brief Determine the appropriate source input kind based on language
00836 /// options.
00837 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
00838   if (LangOpts.OpenCL)
00839     return IK_OpenCL;
00840   if (LangOpts.CUDA)
00841     return IK_CUDA;
00842   if (LangOpts.ObjC1)
00843     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
00844   return LangOpts.CPlusPlus? IK_CXX : IK_C;
00845 }
00846 
00847 /// \brief Compile a module file for the given module, using the options 
00848 /// provided by the importing compiler instance. Returns true if the module
00849 /// was built without errors.
00850 static bool compileModuleImpl(CompilerInstance &ImportingInstance,
00851                               SourceLocation ImportLoc,
00852                               Module *Module,
00853                               StringRef ModuleFileName) {
00854   ModuleMap &ModMap 
00855     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
00856     
00857   // Construct a compiler invocation for creating this module.
00858   IntrusiveRefCntPtr<CompilerInvocation> Invocation
00859     (new CompilerInvocation(ImportingInstance.getInvocation()));
00860 
00861   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
00862   
00863   // For any options that aren't intended to affect how a module is built,
00864   // reset them to their default values.
00865   Invocation->getLangOpts()->resetNonModularOptions();
00866   PPOpts.resetNonModularOptions();
00867 
00868   // Remove any macro definitions that are explicitly ignored by the module.
00869   // They aren't supposed to affect how the module is built anyway.
00870   const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
00871   PPOpts.Macros.erase(
00872       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
00873                      [&HSOpts](const std::pair<std::string, bool> &def) {
00874         StringRef MacroDef = def.first;
00875         return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
00876       }),
00877       PPOpts.Macros.end());
00878 
00879   // Note the name of the module we're building.
00880   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
00881 
00882   // Make sure that the failed-module structure has been allocated in
00883   // the importing instance, and propagate the pointer to the newly-created
00884   // instance.
00885   PreprocessorOptions &ImportingPPOpts
00886     = ImportingInstance.getInvocation().getPreprocessorOpts();
00887   if (!ImportingPPOpts.FailedModules)
00888     ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
00889   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
00890 
00891   // If there is a module map file, build the module using the module map.
00892   // Set up the inputs/outputs so that we build the module from its umbrella
00893   // header.
00894   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
00895   FrontendOpts.OutputFile = ModuleFileName.str();
00896   FrontendOpts.DisableFree = false;
00897   FrontendOpts.GenerateGlobalModuleIndex = false;
00898   FrontendOpts.Inputs.clear();
00899   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
00900 
00901   // Don't free the remapped file buffers; they are owned by our caller.
00902   PPOpts.RetainRemappedFileBuffers = true;
00903     
00904   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
00905   assert(ImportingInstance.getInvocation().getModuleHash() ==
00906          Invocation->getModuleHash() && "Module hash mismatch!");
00907   
00908   // Construct a compiler instance that will be used to actually create the
00909   // module.
00910   CompilerInstance Instance(/*BuildingModule=*/true);
00911   Instance.setInvocation(&*Invocation);
00912 
00913   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
00914                                    ImportingInstance.getDiagnosticClient()),
00915                              /*ShouldOwnClient=*/true);
00916 
00917   Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
00918 
00919   // Note that this module is part of the module build stack, so that we
00920   // can detect cycles in the module graph.
00921   Instance.setFileManager(&ImportingInstance.getFileManager());
00922   Instance.createSourceManager(Instance.getFileManager());
00923   SourceManager &SourceMgr = Instance.getSourceManager();
00924   SourceMgr.setModuleBuildStack(
00925     ImportingInstance.getSourceManager().getModuleBuildStack());
00926   SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
00927     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
00928 
00929   // If we're collecting module dependencies, we need to share a collector
00930   // between all of the module CompilerInstances.
00931   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
00932 
00933   // Get or create the module map that we'll use to build this module.
00934   std::string InferredModuleMapContent;
00935   if (const FileEntry *ModuleMapFile =
00936           ModMap.getContainingModuleMapFile(Module)) {
00937     // Use the module map where this module resides.
00938     FrontendOpts.Inputs.push_back(
00939         FrontendInputFile(ModuleMapFile->getName(), IK));
00940   } else {
00941     llvm::raw_string_ostream OS(InferredModuleMapContent);
00942     Module->print(OS);
00943     OS.flush();
00944     FrontendOpts.Inputs.push_back(
00945         FrontendInputFile("__inferred_module.map", IK));
00946 
00947     std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
00948         llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
00949     ModuleMapFile = Instance.getFileManager().getVirtualFile(
00950         "__inferred_module.map", InferredModuleMapContent.size(), 0);
00951     SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer));
00952   }
00953 
00954   // Construct a module-generating action. Passing through the module map is
00955   // safe because the FileManager is shared between the compiler instances.
00956   GenerateModuleAction CreateModuleAction(
00957       ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
00958 
00959   ImportingInstance.getDiagnostics().Report(ImportLoc,
00960                                             diag::remark_module_build)
00961     << Module->Name << ModuleFileName;
00962 
00963   // Execute the action to actually build the module in-place. Use a separate
00964   // thread so that we get a stack large enough.
00965   const unsigned ThreadStackSize = 8 << 20;
00966   llvm::CrashRecoveryContext CRC;
00967   CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
00968                         ThreadStackSize);
00969 
00970   ImportingInstance.getDiagnostics().Report(ImportLoc,
00971                                             diag::remark_module_build_done)
00972     << Module->Name;
00973 
00974   // Delete the temporary module map file.
00975   // FIXME: Even though we're executing under crash protection, it would still
00976   // be nice to do this with RemoveFileOnSignal when we can. However, that
00977   // doesn't make sense for all clients, so clean this up manually.
00978   Instance.clearOutputFiles(/*EraseFiles=*/true);
00979 
00980   // We've rebuilt a module. If we're allowed to generate or update the global
00981   // module index, record that fact in the importing compiler instance.
00982   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
00983     ImportingInstance.setBuildGlobalModuleIndex(true);
00984   }
00985 
00986   return !Instance.getDiagnostics().hasErrorOccurred();
00987 }
00988 
00989 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
00990                                  SourceLocation ImportLoc,
00991                                  SourceLocation ModuleNameLoc, Module *Module,
00992                                  StringRef ModuleFileName) {
00993   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
00994 
00995   auto diagnoseBuildFailure = [&] {
00996     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
00997         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
00998   };
00999 
01000   // FIXME: have LockFileManager return an error_code so that we can
01001   // avoid the mkdir when the directory already exists.
01002   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
01003   llvm::sys::fs::create_directories(Dir);
01004 
01005   while (1) {
01006     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
01007     llvm::LockFileManager Locked(ModuleFileName);
01008     switch (Locked) {
01009     case llvm::LockFileManager::LFS_Error:
01010       Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
01011           << Module->Name;
01012       return false;
01013 
01014     case llvm::LockFileManager::LFS_Owned:
01015       // We're responsible for building the module ourselves.
01016       if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
01017                              ModuleFileName)) {
01018         diagnoseBuildFailure();
01019         return false;
01020       }
01021       break;
01022 
01023     case llvm::LockFileManager::LFS_Shared:
01024       // Someone else is responsible for building the module. Wait for them to
01025       // finish.
01026       if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
01027         continue; // try again to get the lock.
01028       ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
01029       break;
01030     }
01031 
01032     // Try to read the module file, now that we've compiled it.
01033     ASTReader::ASTReadResult ReadResult =
01034         ImportingInstance.getModuleManager()->ReadAST(
01035             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
01036             ModuleLoadCapabilities);
01037 
01038     if (ReadResult == ASTReader::OutOfDate &&
01039         Locked == llvm::LockFileManager::LFS_Shared) {
01040       // The module may be out of date in the presence of file system races,
01041       // or if one of its imports depends on header search paths that are not
01042       // consistent with this ImportingInstance.  Try again...
01043       continue;
01044     } else if (ReadResult == ASTReader::Missing) {
01045       diagnoseBuildFailure();
01046     } else if (ReadResult != ASTReader::Success &&
01047                !Diags.hasErrorOccurred()) {
01048       // The ASTReader didn't diagnose the error, so conservatively report it.
01049       diagnoseBuildFailure();
01050     }
01051     return ReadResult == ASTReader::Success;
01052   }
01053 }
01054 
01055 /// \brief Diagnose differences between the current definition of the given
01056 /// configuration macro and the definition provided on the command line.
01057 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
01058                              Module *Mod, SourceLocation ImportLoc) {
01059   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
01060   SourceManager &SourceMgr = PP.getSourceManager();
01061   
01062   // If this identifier has never had a macro definition, then it could
01063   // not have changed.
01064   if (!Id->hadMacroDefinition())
01065     return;
01066 
01067   // If this identifier does not currently have a macro definition,
01068   // check whether it had one on the command line.
01069   if (!Id->hasMacroDefinition()) {
01070     MacroDirective::DefInfo LatestDef =
01071         PP.getMacroDirectiveHistory(Id)->getDefinition();
01072     for (MacroDirective::DefInfo Def = LatestDef; Def;
01073            Def = Def.getPreviousDefinition()) {
01074       FileID FID = SourceMgr.getFileID(Def.getLocation());
01075       if (FID.isInvalid())
01076         continue;
01077 
01078       // We only care about the predefines buffer.
01079       if (FID != PP.getPredefinesFileID())
01080         continue;
01081 
01082       // This macro was defined on the command line, then #undef'd later.
01083       // Complain.
01084       PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
01085         << true << ConfigMacro << Mod->getFullModuleName();
01086       if (LatestDef.isUndefined())
01087         PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
01088           << true;
01089       return;
01090     }
01091 
01092     // Okay: no definition in the predefines buffer.
01093     return;
01094   }
01095 
01096   // This identifier has a macro definition. Check whether we had a definition
01097   // on the command line.
01098   MacroDirective::DefInfo LatestDef =
01099       PP.getMacroDirectiveHistory(Id)->getDefinition();
01100   MacroDirective::DefInfo PredefinedDef;
01101   for (MacroDirective::DefInfo Def = LatestDef; Def;
01102          Def = Def.getPreviousDefinition()) {
01103     FileID FID = SourceMgr.getFileID(Def.getLocation());
01104     if (FID.isInvalid())
01105       continue;
01106 
01107     // We only care about the predefines buffer.
01108     if (FID != PP.getPredefinesFileID())
01109       continue;
01110 
01111     PredefinedDef = Def;
01112     break;
01113   }
01114 
01115   // If there was no definition for this macro in the predefines buffer,
01116   // complain.
01117   if (!PredefinedDef ||
01118       (!PredefinedDef.getLocation().isValid() &&
01119        PredefinedDef.getUndefLocation().isValid())) {
01120     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
01121       << false << ConfigMacro << Mod->getFullModuleName();
01122     PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
01123       << false;
01124     return;
01125   }
01126 
01127   // If the current macro definition is the same as the predefined macro
01128   // definition, it's okay.
01129   if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
01130       LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
01131                                               /*Syntactically=*/true))
01132     return;
01133 
01134   // The macro definitions differ.
01135   PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
01136     << false << ConfigMacro << Mod->getFullModuleName();
01137   PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
01138     << false;
01139 }
01140 
01141 /// \brief Write a new timestamp file with the given path.
01142 static void writeTimestampFile(StringRef TimestampFile) {
01143   std::error_code EC;
01144   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
01145 }
01146 
01147 /// \brief Prune the module cache of modules that haven't been accessed in
01148 /// a long time.
01149 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
01150   struct stat StatBuf;
01151   llvm::SmallString<128> TimestampFile;
01152   TimestampFile = HSOpts.ModuleCachePath;
01153   llvm::sys::path::append(TimestampFile, "modules.timestamp");
01154 
01155   // Try to stat() the timestamp file.
01156   if (::stat(TimestampFile.c_str(), &StatBuf)) {
01157     // If the timestamp file wasn't there, create one now.
01158     if (errno == ENOENT) {
01159       writeTimestampFile(TimestampFile);
01160     }
01161     return;
01162   }
01163 
01164   // Check whether the time stamp is older than our pruning interval.
01165   // If not, do nothing.
01166   time_t TimeStampModTime = StatBuf.st_mtime;
01167   time_t CurrentTime = time(nullptr);
01168   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
01169     return;
01170 
01171   // Write a new timestamp file so that nobody else attempts to prune.
01172   // There is a benign race condition here, if two Clang instances happen to
01173   // notice at the same time that the timestamp is out-of-date.
01174   writeTimestampFile(TimestampFile);
01175 
01176   // Walk the entire module cache, looking for unused module files and module
01177   // indices.
01178   std::error_code EC;
01179   SmallString<128> ModuleCachePathNative;
01180   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
01181   for (llvm::sys::fs::directory_iterator
01182          Dir(ModuleCachePathNative.str(), EC), DirEnd;
01183        Dir != DirEnd && !EC; Dir.increment(EC)) {
01184     // If we don't have a directory, there's nothing to look into.
01185     if (!llvm::sys::fs::is_directory(Dir->path()))
01186       continue;
01187 
01188     // Walk all of the files within this directory.
01189     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
01190          File != FileEnd && !EC; File.increment(EC)) {
01191       // We only care about module and global module index files.
01192       StringRef Extension = llvm::sys::path::extension(File->path());
01193       if (Extension != ".pcm" && Extension != ".timestamp" &&
01194           llvm::sys::path::filename(File->path()) != "modules.idx")
01195         continue;
01196 
01197       // Look at this file. If we can't stat it, there's nothing interesting
01198       // there.
01199       if (::stat(File->path().c_str(), &StatBuf))
01200         continue;
01201 
01202       // If the file has been used recently enough, leave it there.
01203       time_t FileAccessTime = StatBuf.st_atime;
01204       if (CurrentTime - FileAccessTime <=
01205               time_t(HSOpts.ModuleCachePruneAfter)) {
01206         continue;
01207       }
01208 
01209       // Remove the file.
01210       llvm::sys::fs::remove(File->path());
01211 
01212       // Remove the timestamp file.
01213       std::string TimpestampFilename = File->path() + ".timestamp";
01214       llvm::sys::fs::remove(TimpestampFilename);
01215     }
01216 
01217     // If we removed all of the files in the directory, remove the directory
01218     // itself.
01219     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
01220             llvm::sys::fs::directory_iterator() && !EC)
01221       llvm::sys::fs::remove(Dir->path());
01222   }
01223 }
01224 
01225 void CompilerInstance::createModuleManager() {
01226   if (!ModuleManager) {
01227     if (!hasASTContext())
01228       createASTContext();
01229 
01230     // If we're not recursively building a module, check whether we
01231     // need to prune the module cache.
01232     if (getSourceManager().getModuleBuildStack().empty() &&
01233         getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
01234         getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
01235       pruneModuleCache(getHeaderSearchOpts());
01236     }
01237 
01238     HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
01239     std::string Sysroot = HSOpts.Sysroot;
01240     const PreprocessorOptions &PPOpts = getPreprocessorOpts();
01241     ModuleManager = new ASTReader(getPreprocessor(), *Context,
01242                                   Sysroot.empty() ? "" : Sysroot.c_str(),
01243                                   PPOpts.DisablePCHValidation,
01244                                   /*AllowASTWithCompilerErrors=*/false,
01245                                   /*AllowConfigurationMismatch=*/false,
01246                                   HSOpts.ModulesValidateSystemHeaders,
01247                                   getFrontendOpts().UseGlobalModuleIndex);
01248     if (hasASTConsumer()) {
01249       ModuleManager->setDeserializationListener(
01250         getASTConsumer().GetASTDeserializationListener());
01251       getASTContext().setASTMutationListener(
01252         getASTConsumer().GetASTMutationListener());
01253     }
01254     getASTContext().setExternalSource(ModuleManager);
01255     if (hasSema())
01256       ModuleManager->InitializeSema(getSema());
01257     if (hasASTConsumer())
01258       ModuleManager->StartTranslationUnit(&getASTConsumer());
01259   }
01260 }
01261 
01262 bool CompilerInstance::loadModuleFile(StringRef FileName) {
01263   // Helper to recursively read the module names for all modules we're adding.
01264   // We mark these as known and redirect any attempt to load that module to
01265   // the files we were handed.
01266   struct ReadModuleNames : ASTReaderListener {
01267     CompilerInstance &CI;
01268     std::vector<StringRef> ModuleFileStack;
01269     bool Failed;
01270     bool TopFileIsModule;
01271 
01272     ReadModuleNames(CompilerInstance &CI)
01273         : CI(CI), Failed(false), TopFileIsModule(false) {}
01274 
01275     bool needsImportVisitation() const override { return true; }
01276 
01277     void visitImport(StringRef FileName) override {
01278       ModuleFileStack.push_back(FileName);
01279       if (ASTReader::readASTFileControlBlock(FileName, CI.getFileManager(),
01280                                              *this)) {
01281         CI.getDiagnostics().Report(SourceLocation(),
01282                                    diag::err_module_file_not_found)
01283             << FileName;
01284         // FIXME: Produce a note stack explaining how we got here.
01285         Failed = true;
01286       }
01287       ModuleFileStack.pop_back();
01288     }
01289 
01290     void ReadModuleName(StringRef ModuleName) override {
01291       if (ModuleFileStack.size() == 1)
01292         TopFileIsModule = true;
01293 
01294       auto &ModuleFile = CI.ModuleFileOverrides[ModuleName];
01295       if (!ModuleFile.empty() && ModuleFile != ModuleFileStack.back())
01296         CI.getDiagnostics().Report(SourceLocation(),
01297                                    diag::err_conflicting_module_files)
01298             << ModuleName << ModuleFile << ModuleFileStack.back();
01299       ModuleFile = ModuleFileStack.back();
01300     }
01301   } RMN(*this);
01302 
01303   RMN.visitImport(FileName);
01304 
01305   if (RMN.Failed)
01306     return false;
01307 
01308   // If we never found a module name for the top file, then it's not a module,
01309   // it's a PCH or preamble or something.
01310   if (!RMN.TopFileIsModule) {
01311     getDiagnostics().Report(SourceLocation(), diag::err_module_file_not_module)
01312       << FileName;
01313     return false;
01314   }
01315 
01316   return true;
01317 }
01318 
01319 ModuleLoadResult
01320 CompilerInstance::loadModule(SourceLocation ImportLoc,
01321                              ModuleIdPath Path,
01322                              Module::NameVisibilityKind Visibility,
01323                              bool IsInclusionDirective) {
01324   // Determine what file we're searching from.
01325   StringRef ModuleName = Path[0].first->getName();
01326   SourceLocation ModuleNameLoc = Path[0].second;
01327 
01328   // If we've already handled this import, just return the cached result.
01329   // This one-element cache is important to eliminate redundant diagnostics
01330   // when both the preprocessor and parser see the same import declaration.
01331   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
01332     // Make the named module visible.
01333     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
01334         ModuleName != getLangOpts().ImplementationOfModule)
01335       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
01336                                        ImportLoc, /*Complain=*/false);
01337     return LastModuleImportResult;
01338   }
01339 
01340   clang::Module *Module = nullptr;
01341 
01342   // If we don't already have information on this module, load the module now.
01343   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
01344     = KnownModules.find(Path[0].first);
01345   if (Known != KnownModules.end()) {
01346     // Retrieve the cached top-level module.
01347     Module = Known->second;    
01348   } else if (ModuleName == getLangOpts().CurrentModule ||
01349              ModuleName == getLangOpts().ImplementationOfModule) {
01350     // This is the module we're building. 
01351     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
01352     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
01353   } else {
01354     // Search for a module with the given name.
01355     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
01356     if (!Module) {
01357       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
01358       << ModuleName
01359       << SourceRange(ImportLoc, ModuleNameLoc);
01360       ModuleBuildFailed = true;
01361       return ModuleLoadResult();
01362     }
01363 
01364     auto Override = ModuleFileOverrides.find(ModuleName);
01365     bool Explicit = Override != ModuleFileOverrides.end();
01366 
01367     std::string ModuleFileName =
01368         Explicit ? Override->second
01369                  : PP->getHeaderSearchInfo().getModuleFileName(Module);
01370 
01371     // If we don't already have an ASTReader, create one now.
01372     if (!ModuleManager)
01373       createModuleManager();
01374 
01375     if (TheDependencyFileGenerator)
01376       TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
01377 
01378     if (ModuleDepCollector)
01379       ModuleDepCollector->attachToASTReader(*ModuleManager);
01380 
01381     for (auto &Listener : DependencyCollectors)
01382       Listener->attachToASTReader(*ModuleManager);
01383 
01384     // Try to load the module file.
01385     unsigned ARRFlags =
01386         Explicit ? 0 : ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
01387     switch (ModuleManager->ReadAST(ModuleFileName,
01388                                    Explicit ? serialization::MK_ExplicitModule
01389                                             : serialization::MK_ImplicitModule,
01390                                    ImportLoc, ARRFlags)) {
01391     case ASTReader::Success:
01392       break;
01393 
01394     case ASTReader::OutOfDate:
01395     case ASTReader::Missing: {
01396       if (Explicit) {
01397         // ReadAST has already complained for us.
01398         ModuleLoader::HadFatalFailure = true;
01399         KnownModules[Path[0].first] = nullptr;
01400         return ModuleLoadResult();
01401       }
01402 
01403       // The module file is missing or out-of-date. Build it.
01404       assert(Module && "missing module file");
01405       // Check whether there is a cycle in the module graph.
01406       ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
01407       ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
01408       for (; Pos != PosEnd; ++Pos) {
01409         if (Pos->first == ModuleName)
01410           break;
01411       }
01412 
01413       if (Pos != PosEnd) {
01414         SmallString<256> CyclePath;
01415         for (; Pos != PosEnd; ++Pos) {
01416           CyclePath += Pos->first;
01417           CyclePath += " -> ";
01418         }
01419         CyclePath += ModuleName;
01420 
01421         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
01422           << ModuleName << CyclePath;
01423         return ModuleLoadResult();
01424       }
01425 
01426       // Check whether we have already attempted to build this module (but
01427       // failed).
01428       if (getPreprocessorOpts().FailedModules &&
01429           getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
01430         getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
01431           << ModuleName
01432           << SourceRange(ImportLoc, ModuleNameLoc);
01433         ModuleBuildFailed = true;
01434         return ModuleLoadResult();
01435       }
01436 
01437       // Try to compile and then load the module.
01438       if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
01439                                 ModuleFileName)) {
01440         assert(getDiagnostics().hasErrorOccurred() &&
01441                "undiagnosed error in compileAndLoadModule");
01442         if (getPreprocessorOpts().FailedModules)
01443           getPreprocessorOpts().FailedModules->addFailed(ModuleName);
01444         KnownModules[Path[0].first] = nullptr;
01445         ModuleBuildFailed = true;
01446         return ModuleLoadResult();
01447       }
01448 
01449       // Okay, we've rebuilt and now loaded the module.
01450       break;
01451     }
01452 
01453     case ASTReader::VersionMismatch:
01454     case ASTReader::ConfigurationMismatch:
01455     case ASTReader::HadErrors:
01456       ModuleLoader::HadFatalFailure = true;
01457       // FIXME: The ASTReader will already have complained, but can we showhorn
01458       // that diagnostic information into a more useful form?
01459       KnownModules[Path[0].first] = nullptr;
01460       return ModuleLoadResult();
01461 
01462     case ASTReader::Failure:
01463       ModuleLoader::HadFatalFailure = true;
01464       // Already complained, but note now that we failed.
01465       KnownModules[Path[0].first] = nullptr;
01466       ModuleBuildFailed = true;
01467       return ModuleLoadResult();
01468     }
01469 
01470     // Cache the result of this top-level module lookup for later.
01471     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
01472   }
01473   
01474   // If we never found the module, fail.
01475   if (!Module)
01476     return ModuleLoadResult();
01477   
01478   // Verify that the rest of the module path actually corresponds to
01479   // a submodule.
01480   if (Path.size() > 1) {
01481     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
01482       StringRef Name = Path[I].first->getName();
01483       clang::Module *Sub = Module->findSubmodule(Name);
01484       
01485       if (!Sub) {
01486         // Attempt to perform typo correction to find a module name that works.
01487         SmallVector<StringRef, 2> Best;
01488         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
01489         
01490         for (clang::Module::submodule_iterator J = Module->submodule_begin(), 
01491                                             JEnd = Module->submodule_end();
01492              J != JEnd; ++J) {
01493           unsigned ED = Name.edit_distance((*J)->Name,
01494                                            /*AllowReplacements=*/true,
01495                                            BestEditDistance);
01496           if (ED <= BestEditDistance) {
01497             if (ED < BestEditDistance) {
01498               Best.clear();
01499               BestEditDistance = ED;
01500             }
01501             
01502             Best.push_back((*J)->Name);
01503           }
01504         }
01505         
01506         // If there was a clear winner, user it.
01507         if (Best.size() == 1) {
01508           getDiagnostics().Report(Path[I].second, 
01509                                   diag::err_no_submodule_suggest)
01510             << Path[I].first << Module->getFullModuleName() << Best[0]
01511             << SourceRange(Path[0].second, Path[I-1].second)
01512             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
01513                                             Best[0]);
01514           
01515           Sub = Module->findSubmodule(Best[0]);
01516         }
01517       }
01518       
01519       if (!Sub) {
01520         // No submodule by this name. Complain, and don't look for further
01521         // submodules.
01522         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
01523           << Path[I].first << Module->getFullModuleName()
01524           << SourceRange(Path[0].second, Path[I-1].second);
01525         break;
01526       }
01527       
01528       Module = Sub;
01529     }
01530   }
01531 
01532   // Don't make the module visible if we are in the implementation.
01533   if (ModuleName == getLangOpts().ImplementationOfModule)
01534     return ModuleLoadResult(Module, false);
01535   
01536   // Make the named module visible, if it's not already part of the module
01537   // we are parsing.
01538   if (ModuleName != getLangOpts().CurrentModule) {
01539     if (!Module->IsFromModuleFile) {
01540       // We have an umbrella header or directory that doesn't actually include
01541       // all of the headers within the directory it covers. Complain about
01542       // this missing submodule and recover by forgetting that we ever saw
01543       // this submodule.
01544       // FIXME: Should we detect this at module load time? It seems fairly
01545       // expensive (and rare).
01546       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
01547         << Module->getFullModuleName()
01548         << SourceRange(Path.front().second, Path.back().second);
01549 
01550       return ModuleLoadResult(nullptr, true);
01551     }
01552 
01553     // Check whether this module is available.
01554     clang::Module::Requirement Requirement;
01555     clang::Module::HeaderDirective MissingHeader;
01556     if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
01557                              MissingHeader)) {
01558       if (MissingHeader.FileNameLoc.isValid()) {
01559         getDiagnostics().Report(MissingHeader.FileNameLoc,
01560                                 diag::err_module_header_missing)
01561           << MissingHeader.IsUmbrella << MissingHeader.FileName;
01562       } else {
01563         getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
01564           << Module->getFullModuleName()
01565           << Requirement.second << Requirement.first
01566           << SourceRange(Path.front().second, Path.back().second);
01567       }
01568       LastModuleImportLoc = ImportLoc;
01569       LastModuleImportResult = ModuleLoadResult();
01570       return ModuleLoadResult();
01571     }
01572 
01573     ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
01574                                      /*Complain=*/true);
01575   }
01576 
01577   // Check for any configuration macros that have changed.
01578   clang::Module *TopModule = Module->getTopLevelModule();
01579   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
01580     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
01581                      Module, ImportLoc);
01582   }
01583 
01584   // If this module import was due to an inclusion directive, create an 
01585   // implicit import declaration to capture it in the AST.
01586   if (IsInclusionDirective && hasASTContext()) {
01587     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
01588     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
01589                                                      ImportLoc, Module,
01590                                                      Path.back().second);
01591     TU->addDecl(ImportD);
01592     if (Consumer)
01593       Consumer->HandleImplicitImportDecl(ImportD);
01594   }
01595   
01596   LastModuleImportLoc = ImportLoc;
01597   LastModuleImportResult = ModuleLoadResult(Module, false);
01598   return LastModuleImportResult;
01599 }
01600 
01601 void CompilerInstance::makeModuleVisible(Module *Mod,
01602                                          Module::NameVisibilityKind Visibility,
01603                                          SourceLocation ImportLoc,
01604                                          bool Complain){
01605   ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
01606 }
01607 
01608 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
01609     SourceLocation TriggerLoc) {
01610   if (!ModuleManager)
01611     createModuleManager();
01612   // Can't do anything if we don't have the module manager.
01613   if (!ModuleManager)
01614     return nullptr;
01615   // Get an existing global index.  This loads it if not already
01616   // loaded.
01617   ModuleManager->loadGlobalIndex();
01618   GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
01619   // If the global index doesn't exist, create it.
01620   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
01621       hasPreprocessor()) {
01622     llvm::sys::fs::create_directories(
01623       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
01624     GlobalModuleIndex::writeIndex(
01625       getFileManager(),
01626       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
01627     ModuleManager->resetForReload();
01628     ModuleManager->loadGlobalIndex();
01629     GlobalIndex = ModuleManager->getGlobalIndex();
01630   }
01631   // For finding modules needing to be imported for fixit messages,
01632   // we need to make the global index cover all modules, so we do that here.
01633   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
01634     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
01635     bool RecreateIndex = false;
01636     for (ModuleMap::module_iterator I = MMap.module_begin(),
01637         E = MMap.module_end(); I != E; ++I) {
01638       Module *TheModule = I->second;
01639       const FileEntry *Entry = TheModule->getASTFile();
01640       if (!Entry) {
01641         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
01642         Path.push_back(std::make_pair(
01643           getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
01644         std::reverse(Path.begin(), Path.end());
01645         // Load a module as hidden.  This also adds it to the global index.
01646         loadModule(TheModule->DefinitionLoc, Path,
01647                                              Module::Hidden, false);
01648         RecreateIndex = true;
01649       }
01650     }
01651     if (RecreateIndex) {
01652       GlobalModuleIndex::writeIndex(
01653         getFileManager(),
01654         getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
01655       ModuleManager->resetForReload();
01656       ModuleManager->loadGlobalIndex();
01657       GlobalIndex = ModuleManager->getGlobalIndex();
01658     }
01659     HaveFullGlobalModuleIndex = true;
01660   }
01661   return GlobalIndex;
01662 }
01663 
01664 // Check global module index for missing imports.
01665 bool
01666 CompilerInstance::lookupMissingImports(StringRef Name,
01667                                        SourceLocation TriggerLoc) {
01668   // Look for the symbol in non-imported modules, but only if an error
01669   // actually occurred.
01670   if (!buildingModule()) {
01671     // Load global module index, or retrieve a previously loaded one.
01672     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
01673       TriggerLoc);
01674 
01675     // Only if we have a global index.
01676     if (GlobalIndex) {
01677       GlobalModuleIndex::HitSet FoundModules;
01678 
01679       // Find the modules that reference the identifier.
01680       // Note that this only finds top-level modules.
01681       // We'll let diagnoseTypo find the actual declaration module.
01682       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
01683         return true;
01684     }
01685   }
01686 
01687   return false;
01688 }
01689 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }