CompilerInstance.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. #include "clang/Frontend/CompilerInstance.h"
  10. #include "clang/Sema/Sema.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/Lex/HeaderSearch.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Lex/PTHManager.h"
  22. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  23. #include "clang/Frontend/FrontendAction.h"
  24. #include "clang/Frontend/FrontendActions.h"
  25. #include "clang/Frontend/FrontendDiagnostic.h"
  26. #include "clang/Frontend/LogDiagnosticPrinter.h"
  27. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  28. #include "clang/Frontend/TextDiagnosticPrinter.h"
  29. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  30. #include "clang/Frontend/Utils.h"
  31. #include "clang/Serialization/ASTReader.h"
  32. #include "clang/Sema/CodeCompleteConsumer.h"
  33. #include "llvm/Support/FileSystem.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/ADT/Statistic.h"
  37. #include "llvm/Support/Timer.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Program.h"
  41. #include "llvm/Support/Signals.h"
  42. #include "llvm/Support/system_error.h"
  43. #include "llvm/Support/CrashRecoveryContext.h"
  44. #include "llvm/Config/config.h"
  45. // Support for FileLockManager
  46. #include <fstream>
  47. #include <sys/types.h>
  48. #include <sys/stat.h>
  49. #if LLVM_ON_WIN32
  50. #include <windows.h>
  51. #endif
  52. #if LLVM_ON_UNIX
  53. #include <unistd.h>
  54. #endif
  55. using namespace clang;
  56. CompilerInstance::CompilerInstance()
  57. : Invocation(new CompilerInvocation()), ModuleManager(0) {
  58. }
  59. CompilerInstance::~CompilerInstance() {
  60. }
  61. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  62. Invocation = Value;
  63. }
  64. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  65. Diagnostics = Value;
  66. }
  67. void CompilerInstance::setTarget(TargetInfo *Value) {
  68. Target = Value;
  69. }
  70. void CompilerInstance::setFileManager(FileManager *Value) {
  71. FileMgr = Value;
  72. }
  73. void CompilerInstance::setSourceManager(SourceManager *Value) {
  74. SourceMgr = Value;
  75. }
  76. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  77. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  78. void CompilerInstance::setSema(Sema *S) {
  79. TheSema.reset(S);
  80. }
  81. void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
  82. Consumer.reset(Value);
  83. }
  84. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  85. CompletionConsumer.reset(Value);
  86. }
  87. // Diagnostics
  88. static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
  89. unsigned argc, const char* const *argv,
  90. DiagnosticsEngine &Diags) {
  91. std::string ErrorInfo;
  92. llvm::OwningPtr<raw_ostream> OS(
  93. new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
  94. if (!ErrorInfo.empty()) {
  95. Diags.Report(diag::err_fe_unable_to_open_logfile)
  96. << DiagOpts.DumpBuildInformation << ErrorInfo;
  97. return;
  98. }
  99. (*OS) << "clang -cc1 command line arguments: ";
  100. for (unsigned i = 0; i != argc; ++i)
  101. (*OS) << argv[i] << ' ';
  102. (*OS) << '\n';
  103. // Chain in a diagnostic client which will log the diagnostics.
  104. DiagnosticConsumer *Logger =
  105. new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
  106. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  107. }
  108. static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
  109. const CodeGenOptions *CodeGenOpts,
  110. DiagnosticsEngine &Diags) {
  111. std::string ErrorInfo;
  112. bool OwnsStream = false;
  113. raw_ostream *OS = &llvm::errs();
  114. if (DiagOpts.DiagnosticLogFile != "-") {
  115. // Create the output stream.
  116. llvm::raw_fd_ostream *FileOS(
  117. new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
  118. ErrorInfo, llvm::raw_fd_ostream::F_Append));
  119. if (!ErrorInfo.empty()) {
  120. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  121. << DiagOpts.DumpBuildInformation << ErrorInfo;
  122. } else {
  123. FileOS->SetUnbuffered();
  124. FileOS->SetUseAtomicWrites(true);
  125. OS = FileOS;
  126. OwnsStream = true;
  127. }
  128. }
  129. // Chain in the diagnostic client which will log the diagnostics.
  130. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  131. OwnsStream);
  132. if (CodeGenOpts)
  133. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  134. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  135. }
  136. static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
  137. DiagnosticsEngine &Diags,
  138. StringRef OutputFile) {
  139. std::string ErrorInfo;
  140. llvm::OwningPtr<llvm::raw_fd_ostream> OS;
  141. OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
  142. llvm::raw_fd_ostream::F_Binary));
  143. if (!ErrorInfo.empty()) {
  144. Diags.Report(diag::warn_fe_serialized_diag_failure)
  145. << OutputFile << ErrorInfo;
  146. return;
  147. }
  148. DiagnosticConsumer *SerializedConsumer =
  149. clang::serialized_diags::create(OS.take());
  150. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
  151. SerializedConsumer));
  152. }
  153. void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
  154. DiagnosticConsumer *Client,
  155. bool ShouldOwnClient,
  156. bool ShouldCloneClient) {
  157. Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
  158. ShouldOwnClient, ShouldCloneClient,
  159. &getCodeGenOpts());
  160. }
  161. llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
  162. CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
  163. int Argc, const char* const *Argv,
  164. DiagnosticConsumer *Client,
  165. bool ShouldOwnClient,
  166. bool ShouldCloneClient,
  167. const CodeGenOptions *CodeGenOpts) {
  168. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  169. llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
  170. Diags(new DiagnosticsEngine(DiagID));
  171. // Create the diagnostic client for reporting errors or for
  172. // implementing -verify.
  173. if (Client) {
  174. if (ShouldCloneClient)
  175. Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
  176. else
  177. Diags->setClient(Client, ShouldOwnClient);
  178. } else
  179. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  180. // Chain in -verify checker, if requested.
  181. if (Opts.VerifyDiagnostics)
  182. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  183. // Chain in -diagnostic-log-file dumper, if requested.
  184. if (!Opts.DiagnosticLogFile.empty())
  185. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  186. if (!Opts.DumpBuildInformation.empty())
  187. SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
  188. if (!Opts.DiagnosticSerializationFile.empty())
  189. SetupSerializedDiagnostics(Opts, *Diags,
  190. Opts.DiagnosticSerializationFile);
  191. // Configure our handling of diagnostics.
  192. ProcessWarningOptions(*Diags, Opts);
  193. return Diags;
  194. }
  195. // File Manager
  196. void CompilerInstance::createFileManager() {
  197. FileMgr = new FileManager(getFileSystemOpts());
  198. }
  199. // Source Manager
  200. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  201. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  202. }
  203. // Preprocessor
  204. void CompilerInstance::createPreprocessor() {
  205. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  206. // Create a PTH manager if we are using some form of a token cache.
  207. PTHManager *PTHMgr = 0;
  208. if (!PPOpts.TokenCache.empty())
  209. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  210. // Create the Preprocessor.
  211. HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
  212. getDiagnostics());
  213. PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
  214. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  215. /*OwnsHeaderSearch=*/true);
  216. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  217. // That argument is used as the IdentifierInfoLookup argument to
  218. // IdentifierTable's ctor.
  219. if (PTHMgr) {
  220. PTHMgr->setPreprocessor(&*PP);
  221. PP->setPTHManager(PTHMgr);
  222. }
  223. if (PPOpts.DetailedRecord)
  224. PP->createPreprocessingRecord(
  225. PPOpts.DetailedRecordIncludesNestedMacroExpansions);
  226. InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
  227. // Set up the module path, including the hash for the
  228. // module-creation options.
  229. llvm::SmallString<256> SpecificModuleCache(
  230. getHeaderSearchOpts().ModuleCachePath);
  231. if (!getHeaderSearchOpts().DisableModuleHash)
  232. llvm::sys::path::append(SpecificModuleCache,
  233. getInvocation().getModuleHash());
  234. PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
  235. getLangOpts().CurrentModule);
  236. // Handle generating dependencies, if requested.
  237. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  238. if (!DepOpts.OutputFile.empty())
  239. AttachDependencyFileGen(*PP, DepOpts);
  240. // Handle generating header include information, if requested.
  241. if (DepOpts.ShowHeaderIncludes)
  242. AttachHeaderIncludeGen(*PP);
  243. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  244. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  245. if (OutputPath == "-")
  246. OutputPath = "";
  247. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  248. /*ShowDepth=*/false);
  249. }
  250. }
  251. // ASTContext
  252. void CompilerInstance::createASTContext() {
  253. Preprocessor &PP = getPreprocessor();
  254. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  255. &getTarget(), PP.getIdentifierTable(),
  256. PP.getSelectorTable(), PP.getBuiltinInfo(),
  257. /*size_reserve=*/ 0);
  258. }
  259. // ExternalASTSource
  260. void CompilerInstance::createPCHExternalASTSource(StringRef Path,
  261. bool DisablePCHValidation,
  262. bool DisableStatCache,
  263. void *DeserializationListener){
  264. llvm::OwningPtr<ExternalASTSource> Source;
  265. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  266. Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  267. DisablePCHValidation,
  268. DisableStatCache,
  269. getPreprocessor(), getASTContext(),
  270. DeserializationListener,
  271. Preamble));
  272. ModuleManager = static_cast<ASTReader*>(Source.get());
  273. getASTContext().setExternalSource(Source);
  274. }
  275. ExternalASTSource *
  276. CompilerInstance::createPCHExternalASTSource(StringRef Path,
  277. const std::string &Sysroot,
  278. bool DisablePCHValidation,
  279. bool DisableStatCache,
  280. Preprocessor &PP,
  281. ASTContext &Context,
  282. void *DeserializationListener,
  283. bool Preamble) {
  284. llvm::OwningPtr<ASTReader> Reader;
  285. Reader.reset(new ASTReader(PP, Context,
  286. Sysroot.empty() ? "" : Sysroot.c_str(),
  287. DisablePCHValidation, DisableStatCache));
  288. Reader->setDeserializationListener(
  289. static_cast<ASTDeserializationListener *>(DeserializationListener));
  290. switch (Reader->ReadAST(Path,
  291. Preamble ? serialization::MK_Preamble
  292. : serialization::MK_PCH)) {
  293. case ASTReader::Success:
  294. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  295. // predefines buffer will be empty.
  296. PP.setPredefines(Reader->getSuggestedPredefines());
  297. return Reader.take();
  298. case ASTReader::Failure:
  299. // Unrecoverable failure: don't even try to process the input file.
  300. break;
  301. case ASTReader::IgnorePCH:
  302. // No suitable PCH file could be found. Return an error.
  303. break;
  304. }
  305. return 0;
  306. }
  307. // Code Completion
  308. static bool EnableCodeCompletion(Preprocessor &PP,
  309. const std::string &Filename,
  310. unsigned Line,
  311. unsigned Column) {
  312. // Tell the source manager to chop off the given file at a specific
  313. // line and column.
  314. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  315. if (!Entry) {
  316. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  317. << Filename;
  318. return true;
  319. }
  320. // Truncate the named file at the given line/column.
  321. PP.SetCodeCompletionPoint(Entry, Line, Column);
  322. return false;
  323. }
  324. void CompilerInstance::createCodeCompletionConsumer() {
  325. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  326. if (!CompletionConsumer) {
  327. CompletionConsumer.reset(
  328. createCodeCompletionConsumer(getPreprocessor(),
  329. Loc.FileName, Loc.Line, Loc.Column,
  330. getFrontendOpts().ShowMacrosInCodeCompletion,
  331. getFrontendOpts().ShowCodePatternsInCodeCompletion,
  332. getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
  333. llvm::outs()));
  334. if (!CompletionConsumer)
  335. return;
  336. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  337. Loc.Line, Loc.Column)) {
  338. CompletionConsumer.reset();
  339. return;
  340. }
  341. if (CompletionConsumer->isOutputBinary() &&
  342. llvm::sys::Program::ChangeStdoutToBinary()) {
  343. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  344. CompletionConsumer.reset();
  345. }
  346. }
  347. void CompilerInstance::createFrontendTimer() {
  348. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  349. }
  350. CodeCompleteConsumer *
  351. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  352. const std::string &Filename,
  353. unsigned Line,
  354. unsigned Column,
  355. bool ShowMacros,
  356. bool ShowCodePatterns,
  357. bool ShowGlobals,
  358. raw_ostream &OS) {
  359. if (EnableCodeCompletion(PP, Filename, Line, Column))
  360. return 0;
  361. // Set up the creation routine for code-completion.
  362. return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
  363. ShowGlobals, OS);
  364. }
  365. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  366. CodeCompleteConsumer *CompletionConsumer) {
  367. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  368. TUKind, CompletionConsumer));
  369. }
  370. // Output Files
  371. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  372. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  373. OutputFiles.push_back(OutFile);
  374. }
  375. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  376. for (std::list<OutputFile>::iterator
  377. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  378. delete it->OS;
  379. if (!it->TempFilename.empty()) {
  380. if (EraseFiles) {
  381. bool existed;
  382. llvm::sys::fs::remove(it->TempFilename, existed);
  383. } else {
  384. llvm::SmallString<128> NewOutFile(it->Filename);
  385. // If '-working-directory' was passed, the output filename should be
  386. // relative to that.
  387. FileMgr->FixupRelativePath(NewOutFile);
  388. if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
  389. NewOutFile.str())) {
  390. getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
  391. << it->TempFilename << it->Filename << ec.message();
  392. bool existed;
  393. llvm::sys::fs::remove(it->TempFilename, existed);
  394. }
  395. }
  396. } else if (!it->Filename.empty() && EraseFiles)
  397. llvm::sys::Path(it->Filename).eraseFromDisk();
  398. }
  399. OutputFiles.clear();
  400. }
  401. llvm::raw_fd_ostream *
  402. CompilerInstance::createDefaultOutputFile(bool Binary,
  403. StringRef InFile,
  404. StringRef Extension) {
  405. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  406. /*RemoveFileOnSignal=*/true, InFile, Extension);
  407. }
  408. llvm::raw_fd_ostream *
  409. CompilerInstance::createOutputFile(StringRef OutputPath,
  410. bool Binary, bool RemoveFileOnSignal,
  411. StringRef InFile,
  412. StringRef Extension,
  413. bool UseTemporary) {
  414. std::string Error, OutputPathName, TempPathName;
  415. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  416. RemoveFileOnSignal,
  417. InFile, Extension,
  418. UseTemporary,
  419. &OutputPathName,
  420. &TempPathName);
  421. if (!OS) {
  422. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  423. << OutputPath << Error;
  424. return 0;
  425. }
  426. // Add the output file -- but don't try to remove "-", since this means we are
  427. // using stdin.
  428. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  429. TempPathName, OS));
  430. return OS;
  431. }
  432. llvm::raw_fd_ostream *
  433. CompilerInstance::createOutputFile(StringRef OutputPath,
  434. std::string &Error,
  435. bool Binary,
  436. bool RemoveFileOnSignal,
  437. StringRef InFile,
  438. StringRef Extension,
  439. bool UseTemporary,
  440. std::string *ResultPathName,
  441. std::string *TempPathName) {
  442. std::string OutFile, TempFile;
  443. if (!OutputPath.empty()) {
  444. OutFile = OutputPath;
  445. } else if (InFile == "-") {
  446. OutFile = "-";
  447. } else if (!Extension.empty()) {
  448. llvm::sys::Path Path(InFile);
  449. Path.eraseSuffix();
  450. Path.appendSuffix(Extension);
  451. OutFile = Path.str();
  452. } else {
  453. OutFile = "-";
  454. }
  455. llvm::OwningPtr<llvm::raw_fd_ostream> OS;
  456. std::string OSFile;
  457. if (UseTemporary && OutFile != "-") {
  458. llvm::sys::Path OutPath(OutFile);
  459. // Only create the temporary if we can actually write to OutPath, otherwise
  460. // we want to fail early.
  461. bool Exists;
  462. if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
  463. (OutPath.isRegularFile() && OutPath.canWrite())) {
  464. // Create a temporary file.
  465. llvm::SmallString<128> TempPath;
  466. TempPath = OutFile;
  467. TempPath += "-%%%%%%%%";
  468. int fd;
  469. if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
  470. /*makeAbsolute=*/false) == llvm::errc::success) {
  471. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  472. OSFile = TempFile = TempPath.str();
  473. }
  474. }
  475. }
  476. if (!OS) {
  477. OSFile = OutFile;
  478. OS.reset(
  479. new llvm::raw_fd_ostream(OSFile.c_str(), Error,
  480. (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
  481. if (!Error.empty())
  482. return 0;
  483. }
  484. // Make sure the out stream file gets removed if we crash.
  485. if (RemoveFileOnSignal)
  486. llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
  487. if (ResultPathName)
  488. *ResultPathName = OutFile;
  489. if (TempPathName)
  490. *TempPathName = TempFile;
  491. return OS.take();
  492. }
  493. // Initialization Utilities
  494. bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
  495. return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
  496. getSourceManager(), getFrontendOpts());
  497. }
  498. bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
  499. DiagnosticsEngine &Diags,
  500. FileManager &FileMgr,
  501. SourceManager &SourceMgr,
  502. const FrontendOptions &Opts) {
  503. // Figure out where to get and map in the main file.
  504. if (InputFile != "-") {
  505. const FileEntry *File = FileMgr.getFile(InputFile);
  506. if (!File) {
  507. Diags.Report(diag::err_fe_error_reading) << InputFile;
  508. return false;
  509. }
  510. SourceMgr.createMainFileID(File);
  511. } else {
  512. llvm::OwningPtr<llvm::MemoryBuffer> SB;
  513. if (llvm::MemoryBuffer::getSTDIN(SB)) {
  514. // FIXME: Give ec.message() in this diag.
  515. Diags.Report(diag::err_fe_error_reading_stdin);
  516. return false;
  517. }
  518. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  519. SB->getBufferSize(), 0);
  520. SourceMgr.createMainFileID(File);
  521. SourceMgr.overrideFileContents(File, SB.take());
  522. }
  523. assert(!SourceMgr.getMainFileID().isInvalid() &&
  524. "Couldn't establish MainFileID!");
  525. return true;
  526. }
  527. // High-Level Operations
  528. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  529. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  530. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  531. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  532. // FIXME: Take this as an argument, once all the APIs we used have moved to
  533. // taking it as an input instead of hard-coding llvm::errs.
  534. raw_ostream &OS = llvm::errs();
  535. // Create the target instance.
  536. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
  537. if (!hasTarget())
  538. return false;
  539. // Inform the target of the language options.
  540. //
  541. // FIXME: We shouldn't need to do this, the target should be immutable once
  542. // created. This complexity should be lifted elsewhere.
  543. getTarget().setForcedLangOptions(getLangOpts());
  544. // Validate/process some options.
  545. if (getHeaderSearchOpts().Verbose)
  546. OS << "clang -cc1 version " CLANG_VERSION_STRING
  547. << " based upon " << PACKAGE_STRING
  548. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  549. if (getFrontendOpts().ShowTimers)
  550. createFrontendTimer();
  551. if (getFrontendOpts().ShowStats)
  552. llvm::EnableStatistics();
  553. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  554. const std::string &InFile = getFrontendOpts().Inputs[i].second;
  555. // Reset the ID tables if we are reusing the SourceManager.
  556. if (hasSourceManager())
  557. getSourceManager().clearIDTables();
  558. if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
  559. Act.Execute();
  560. Act.EndSourceFile();
  561. }
  562. }
  563. // Notify the diagnostic client that all files were processed.
  564. getDiagnostics().getClient()->finish();
  565. if (getDiagnosticOpts().ShowCarets) {
  566. // We can have multiple diagnostics sharing one diagnostic client.
  567. // Get the total number of warnings/errors from the client.
  568. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  569. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  570. if (NumWarnings)
  571. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  572. if (NumWarnings && NumErrors)
  573. OS << " and ";
  574. if (NumErrors)
  575. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  576. if (NumWarnings || NumErrors)
  577. OS << " generated.\n";
  578. }
  579. if (getFrontendOpts().ShowStats && hasFileManager()) {
  580. getFileManager().PrintStats();
  581. OS << "\n";
  582. }
  583. return !getDiagnostics().getClient()->getNumErrors();
  584. }
  585. /// \brief Determine the appropriate source input kind based on language
  586. /// options.
  587. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  588. if (LangOpts.OpenCL)
  589. return IK_OpenCL;
  590. if (LangOpts.CUDA)
  591. return IK_CUDA;
  592. if (LangOpts.ObjC1)
  593. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  594. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  595. }
  596. namespace {
  597. struct CompileModuleMapData {
  598. CompilerInstance &Instance;
  599. GenerateModuleAction &CreateModuleAction;
  600. };
  601. }
  602. /// \brief Helper function that executes the module-generating action under
  603. /// a crash recovery context.
  604. static void doCompileMapModule(void *UserData) {
  605. CompileModuleMapData &Data
  606. = *reinterpret_cast<CompileModuleMapData *>(UserData);
  607. Data.Instance.ExecuteAction(Data.CreateModuleAction);
  608. }
  609. namespace {
  610. /// \brief Class that manages the creation of a lock file to aid
  611. /// implicit coordination between different processes.
  612. ///
  613. /// The implicit coordination works by creating a ".lock" file alongside
  614. /// the file that we're coordinating for, using the atomicity of the file
  615. /// system to ensure that only a single process can create that ".lock" file.
  616. /// When the lock file is removed, the owning process has finished the
  617. /// operation.
  618. class LockFileManager {
  619. public:
  620. /// \brief Describes the state of a lock file.
  621. enum LockFileState {
  622. /// \brief The lock file has been created and is owned by this instance
  623. /// of the object.
  624. LFS_Owned,
  625. /// \brief The lock file already exists and is owned by some other
  626. /// instance.
  627. LFS_Shared,
  628. /// \brief An error occurred while trying to create or find the lock
  629. /// file.
  630. LFS_Error
  631. };
  632. private:
  633. llvm::SmallString<128> LockFileName;
  634. llvm::SmallString<128> UniqueLockFileName;
  635. llvm::Optional<std::pair<std::string, int> > Owner;
  636. llvm::Optional<llvm::error_code> Error;
  637. LockFileManager(const LockFileManager &);
  638. LockFileManager &operator=(const LockFileManager &);
  639. static llvm::Optional<std::pair<std::string, int> >
  640. readLockFile(StringRef LockFileName);
  641. static bool processStillExecuting(StringRef Hostname, int PID);
  642. public:
  643. LockFileManager(StringRef FileName);
  644. ~LockFileManager();
  645. /// \brief Determine the state of the lock file.
  646. LockFileState getState() const;
  647. operator LockFileState() const { return getState(); }
  648. /// \brief For a shared lock, wait until the owner releases the lock.
  649. void waitForUnlock();
  650. };
  651. }
  652. /// \brief Attempt to read the lock file with the given name, if it exists.
  653. ///
  654. /// \param LockFileName The name of the lock file to read.
  655. ///
  656. /// \returns The process ID of the process that owns this lock file
  657. llvm::Optional<std::pair<std::string, int> >
  658. LockFileManager::readLockFile(StringRef LockFileName) {
  659. // Check whether the lock file exists. If not, clearly there's nothing
  660. // to read, so we just return.
  661. bool Exists = false;
  662. if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
  663. return llvm::Optional<std::pair<std::string, int> >();
  664. // Read the owning host and PID out of the lock file. If it appears that the
  665. // owning process is dead, the lock file is invalid.
  666. int PID = 0;
  667. std::string Hostname;
  668. std::ifstream Input(LockFileName.str().c_str());
  669. if (Input >> Hostname >> PID && PID > 0 &&
  670. processStillExecuting(Hostname, PID))
  671. return std::make_pair(Hostname, PID);
  672. // Delete the lock file. It's invalid anyway.
  673. bool Existed;
  674. llvm::sys::fs::remove(LockFileName, Existed);
  675. return llvm::Optional<std::pair<std::string, int> >();
  676. }
  677. bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
  678. #if LLVM_ON_UNIX
  679. char MyHostname[256];
  680. MyHostname[255] = 0;
  681. MyHostname[0] = 0;
  682. gethostname(MyHostname, 255);
  683. // Check whether the process is dead. If so, we're done.
  684. if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
  685. return false;
  686. #endif
  687. return true;
  688. }
  689. LockFileManager::LockFileManager(StringRef FileName)
  690. {
  691. LockFileName = FileName;
  692. LockFileName += ".lock";
  693. // If the lock file already exists, don't bother to try to create our own
  694. // lock file; it won't work anyway. Just figure out who owns this lock file.
  695. if ((Owner = readLockFile(LockFileName)))
  696. return;
  697. // Create a lock file that is unique to this instance.
  698. UniqueLockFileName = LockFileName;
  699. UniqueLockFileName += "-%%%%%%%%";
  700. int UniqueLockFileID;
  701. if (llvm::error_code EC
  702. = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
  703. UniqueLockFileID,
  704. UniqueLockFileName,
  705. /*makeAbsolute=*/false)) {
  706. Error = EC;
  707. return;
  708. }
  709. // Write our process ID to our unique lock file.
  710. {
  711. llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
  712. #if LLVM_ON_UNIX
  713. // FIXME: move getpid() call into LLVM
  714. char hostname[256];
  715. hostname[255] = 0;
  716. hostname[0] = 0;
  717. gethostname(hostname, 255);
  718. Out << hostname << ' ' << getpid();
  719. #else
  720. Out << "localhost 1";
  721. #endif
  722. Out.close();
  723. if (Out.has_error()) {
  724. // We failed to write out PID, so make up an excuse, remove the
  725. // unique lock file, and fail.
  726. Error = llvm::make_error_code(llvm::errc::no_space_on_device);
  727. bool Existed;
  728. llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
  729. return;
  730. }
  731. }
  732. // Create a hard link from the lock file name. If this succeeds, we're done.
  733. llvm::error_code EC
  734. = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
  735. LockFileName.str());
  736. if (EC == llvm::errc::success)
  737. return;
  738. // Creating the hard link failed.
  739. #ifdef LLVM_ON_UNIX
  740. // The creation of the hard link may appear to fail, but if stat'ing the
  741. // unique file returns a link count of 2, then we can still declare success.
  742. struct stat StatBuf;
  743. if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
  744. StatBuf.st_nlink == 2)
  745. return;
  746. #endif
  747. // Someone else managed to create the lock file first. Wipe out our unique
  748. // lock file (it's useless now) and read the process ID from the lock file.
  749. bool Existed;
  750. llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
  751. if ((Owner = readLockFile(LockFileName)))
  752. return;
  753. // There is a lock file that nobody owns; try to clean it up and report
  754. // an error.
  755. llvm::sys::fs::remove(LockFileName.str(), Existed);
  756. Error = EC;
  757. }
  758. LockFileManager::LockFileState LockFileManager::getState() const {
  759. if (Owner)
  760. return LFS_Shared;
  761. if (Error)
  762. return LFS_Error;
  763. return LFS_Owned;
  764. }
  765. LockFileManager::~LockFileManager() {
  766. if (getState() != LFS_Owned)
  767. return;
  768. // Since we own the lock, remove the lock file and our own unique lock file.
  769. bool Existed;
  770. llvm::sys::fs::remove(LockFileName.str(), Existed);
  771. llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
  772. }
  773. void LockFileManager::waitForUnlock() {
  774. if (getState() != LFS_Shared)
  775. return;
  776. #if LLVM_ON_WIN32
  777. unsigned long Interval = 1;
  778. #else
  779. struct timespec Interval;
  780. Interval.tv_sec = 0;
  781. Interval.tv_nsec = 1000000;
  782. #endif
  783. // Don't wait more than an hour for the file to appear.
  784. const unsigned MaxSeconds = 3600;
  785. do {
  786. // Sleep for the designated interval, to allow the owning process time to
  787. // finish up and
  788. // FIXME: Should we hook in to system APIs to get a notification when the
  789. // lock file is deleted?
  790. #if LLVM_ON_WIN32
  791. Sleep(Interval);
  792. #else
  793. nanosleep(&Interval, NULL);
  794. #endif
  795. // If the file no longer exists, we're done.
  796. bool Exists = false;
  797. if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
  798. return;
  799. if (!processStillExecuting((*Owner).first, (*Owner).second))
  800. return;
  801. // Exponentially increase the time we wait for the lock to be removed.
  802. #if LLVM_ON_WIN32
  803. Interval *= 2;
  804. #else
  805. Interval.tv_sec *= 2;
  806. Interval.tv_nsec *= 2;
  807. if (Interval.tv_nsec >= 1000000000) {
  808. ++Interval.tv_sec;
  809. Interval.tv_nsec -= 1000000000;
  810. }
  811. #endif
  812. } while (
  813. #if LLVM_ON_WIN32
  814. Interval < MaxSeconds * 1000
  815. #else
  816. Interval.tv_sec < (time_t)MaxSeconds
  817. #endif
  818. );
  819. // Give up.
  820. }
  821. /// \brief Compile a module file for the given module, using the options
  822. /// provided by the importing compiler instance.
  823. static void compileModule(CompilerInstance &ImportingInstance,
  824. Module *Module,
  825. StringRef ModuleFileName) {
  826. LockFileManager Locked(ModuleFileName);
  827. switch (Locked) {
  828. case LockFileManager::LFS_Error:
  829. return;
  830. case LockFileManager::LFS_Owned:
  831. // We're responsible for building the module ourselves. Do so below.
  832. break;
  833. case LockFileManager::LFS_Shared:
  834. // Someone else is responsible for building the module. Wait for them to
  835. // finish.
  836. Locked.waitForUnlock();
  837. break;
  838. }
  839. ModuleMap &ModMap
  840. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  841. // Construct a compiler invocation for creating this module.
  842. llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
  843. (new CompilerInvocation(ImportingInstance.getInvocation()));
  844. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  845. // For any options that aren't intended to affect how a module is built,
  846. // reset them to their default values.
  847. Invocation->getLangOpts()->resetNonModularOptions();
  848. PPOpts.resetNonModularOptions();
  849. // Note the name of the module we're building.
  850. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  851. // Note that this module is part of the module build path, so that we
  852. // can detect cycles in the module graph.
  853. PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
  854. // If there is a module map file, build the module using the module map.
  855. // Set up the inputs/outputs so that we build the module from its umbrella
  856. // header.
  857. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  858. FrontendOpts.OutputFile = ModuleFileName.str();
  859. FrontendOpts.DisableFree = false;
  860. FrontendOpts.Inputs.clear();
  861. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  862. // Get or create the module map that we'll use to build this module.
  863. llvm::SmallString<128> TempModuleMapFileName;
  864. if (const FileEntry *ModuleMapFile
  865. = ModMap.getContainingModuleMapFile(Module)) {
  866. // Use the module map where this module resides.
  867. FrontendOpts.Inputs.push_back(std::make_pair(IK, ModuleMapFile->getName()));
  868. } else {
  869. // Create a temporary module map file.
  870. TempModuleMapFileName = Module->Name;
  871. TempModuleMapFileName += "-%%%%%%%%.map";
  872. int FD;
  873. if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
  874. TempModuleMapFileName,
  875. /*makeAbsolute=*/true)
  876. != llvm::errc::success) {
  877. ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
  878. << TempModuleMapFileName;
  879. return;
  880. }
  881. // Print the module map to this file.
  882. llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
  883. Module->print(OS);
  884. FrontendOpts.Inputs.push_back(
  885. std::make_pair(IK, TempModuleMapFileName.str().str()));
  886. }
  887. // Don't free the remapped file buffers; they are owned by our caller.
  888. PPOpts.RetainRemappedFileBuffers = true;
  889. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  890. assert(ImportingInstance.getInvocation().getModuleHash() ==
  891. Invocation->getModuleHash() && "Module hash mismatch!");
  892. // Construct a compiler instance that will be used to actually create the
  893. // module.
  894. CompilerInstance Instance;
  895. Instance.setInvocation(&*Invocation);
  896. Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
  897. &ImportingInstance.getDiagnosticClient(),
  898. /*ShouldOwnClient=*/true,
  899. /*ShouldCloneClient=*/true);
  900. // Construct a module-generating action.
  901. GenerateModuleAction CreateModuleAction;
  902. // Execute the action to actually build the module in-place. Use a separate
  903. // thread so that we get a stack large enough.
  904. const unsigned ThreadStackSize = 8 << 20;
  905. llvm::CrashRecoveryContext CRC;
  906. CompileModuleMapData Data = { Instance, CreateModuleAction };
  907. CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
  908. // Delete the temporary module map file.
  909. // FIXME: Even though we're executing under crash protection, it would still
  910. // be nice to do this with RemoveFileOnSignal when we can. However, that
  911. // doesn't make sense for all clients, so clean this up manually.
  912. if (!TempModuleMapFileName.empty())
  913. llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
  914. }
  915. Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
  916. ModuleIdPath Path,
  917. Module::NameVisibilityKind Visibility,
  918. bool IsInclusionDirective) {
  919. // If we've already handled this import, just return the cached result.
  920. // This one-element cache is important to eliminate redundant diagnostics
  921. // when both the preprocessor and parser see the same import declaration.
  922. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  923. // Make the named module visible.
  924. if (LastModuleImportResult)
  925. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
  926. return LastModuleImportResult;
  927. }
  928. // Determine what file we're searching from.
  929. SourceManager &SourceMgr = getSourceManager();
  930. SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
  931. const FileEntry *CurFile
  932. = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
  933. if (!CurFile)
  934. CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
  935. StringRef ModuleName = Path[0].first->getName();
  936. SourceLocation ModuleNameLoc = Path[0].second;
  937. clang::Module *Module = 0;
  938. const FileEntry *ModuleFile = 0;
  939. // If we don't already have information on this module, load the module now.
  940. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  941. = KnownModules.find(Path[0].first);
  942. if (Known == KnownModules.end()) {
  943. // Search for a module with the given name.
  944. std::string ModuleFileName;
  945. ModuleFile
  946. = PP->getHeaderSearchInfo().lookupModule(ModuleName, Module,
  947. &ModuleFileName);
  948. bool BuildingModule = false;
  949. if (!ModuleFile && Module) {
  950. // The module is not cached, but we have a module map from which we can
  951. // build the module.
  952. // Check whether there is a cycle in the module graph.
  953. SmallVectorImpl<std::string> &ModuleBuildPath
  954. = getPreprocessorOpts().ModuleBuildPath;
  955. SmallVectorImpl<std::string>::iterator Pos
  956. = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
  957. if (Pos != ModuleBuildPath.end()) {
  958. llvm::SmallString<256> CyclePath;
  959. for (; Pos != ModuleBuildPath.end(); ++Pos) {
  960. CyclePath += *Pos;
  961. CyclePath += " -> ";
  962. }
  963. CyclePath += ModuleName;
  964. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  965. << ModuleName << CyclePath;
  966. return 0;
  967. }
  968. getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
  969. << ModuleName;
  970. BuildingModule = true;
  971. compileModule(*this, Module, ModuleFileName);
  972. ModuleFile = FileMgr->getFile(ModuleFileName);
  973. }
  974. if (!ModuleFile) {
  975. getDiagnostics().Report(ModuleNameLoc,
  976. BuildingModule? diag::err_module_not_built
  977. : diag::err_module_not_found)
  978. << ModuleName
  979. << SourceRange(ImportLoc, ModuleNameLoc);
  980. return 0;
  981. }
  982. // If we don't already have an ASTReader, create one now.
  983. if (!ModuleManager) {
  984. if (!hasASTContext())
  985. createASTContext();
  986. std::string Sysroot = getHeaderSearchOpts().Sysroot;
  987. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  988. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  989. Sysroot.empty() ? "" : Sysroot.c_str(),
  990. PPOpts.DisablePCHValidation,
  991. PPOpts.DisableStatCache);
  992. if (hasASTConsumer()) {
  993. ModuleManager->setDeserializationListener(
  994. getASTConsumer().GetASTDeserializationListener());
  995. getASTContext().setASTMutationListener(
  996. getASTConsumer().GetASTMutationListener());
  997. }
  998. llvm::OwningPtr<ExternalASTSource> Source;
  999. Source.reset(ModuleManager);
  1000. getASTContext().setExternalSource(Source);
  1001. if (hasSema())
  1002. ModuleManager->InitializeSema(getSema());
  1003. if (hasASTConsumer())
  1004. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1005. }
  1006. // Try to load the module we found.
  1007. switch (ModuleManager->ReadAST(ModuleFile->getName(),
  1008. serialization::MK_Module)) {
  1009. case ASTReader::Success:
  1010. break;
  1011. case ASTReader::IgnorePCH:
  1012. // FIXME: The ASTReader will already have complained, but can we showhorn
  1013. // that diagnostic information into a more useful form?
  1014. KnownModules[Path[0].first] = 0;
  1015. return 0;
  1016. case ASTReader::Failure:
  1017. // Already complained, but note now that we failed.
  1018. KnownModules[Path[0].first] = 0;
  1019. return 0;
  1020. }
  1021. if (!Module) {
  1022. // If we loaded the module directly, without finding a module map first,
  1023. // we'll have loaded the module's information from the module itself.
  1024. Module = PP->getHeaderSearchInfo().getModuleMap()
  1025. .findModule((Path[0].first->getName()));
  1026. }
  1027. // Cache the result of this top-level module lookup for later.
  1028. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1029. } else {
  1030. // Retrieve the cached top-level module.
  1031. Module = Known->second;
  1032. }
  1033. // If we never found the module, fail.
  1034. if (!Module)
  1035. return 0;
  1036. // Verify that the rest of the module path actually corresponds to
  1037. // a submodule.
  1038. if (Path.size() > 1) {
  1039. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1040. StringRef Name = Path[I].first->getName();
  1041. llvm::StringMap<clang::Module *>::iterator Pos
  1042. = Module->SubModules.find(Name);
  1043. if (Pos == Module->SubModules.end()) {
  1044. // Attempt to perform typo correction to find a module name that works.
  1045. llvm::SmallVector<StringRef, 2> Best;
  1046. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1047. for (llvm::StringMap<clang::Module *>::iterator
  1048. J = Module->SubModules.begin(),
  1049. JEnd = Module->SubModules.end();
  1050. J != JEnd; ++J) {
  1051. unsigned ED = Name.edit_distance(J->getValue()->Name,
  1052. /*AllowReplacements=*/true,
  1053. BestEditDistance);
  1054. if (ED <= BestEditDistance) {
  1055. if (ED < BestEditDistance)
  1056. Best.clear();
  1057. Best.push_back(J->getValue()->Name);
  1058. }
  1059. }
  1060. // If there was a clear winner, user it.
  1061. if (Best.size() == 1) {
  1062. getDiagnostics().Report(Path[I].second,
  1063. diag::err_no_submodule_suggest)
  1064. << Path[I].first << Module->getFullModuleName() << Best[0]
  1065. << SourceRange(Path[0].second, Path[I-1].second)
  1066. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1067. Best[0]);
  1068. Pos = Module->SubModules.find(Best[0]);
  1069. }
  1070. }
  1071. if (Pos == Module->SubModules.end()) {
  1072. // No submodule by this name. Complain, and don't look for further
  1073. // submodules.
  1074. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1075. << Path[I].first << Module->getFullModuleName()
  1076. << SourceRange(Path[0].second, Path[I-1].second);
  1077. break;
  1078. }
  1079. Module = Pos->getValue();
  1080. }
  1081. }
  1082. // Make the named module visible.
  1083. ModuleManager->makeModuleVisible(Module, Visibility);
  1084. // If this module import was due to an inclusion directive, create an
  1085. // implicit import declaration to capture it in the AST.
  1086. if (IsInclusionDirective && hasASTContext()) {
  1087. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1088. TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU,
  1089. ImportLoc, Module,
  1090. Path.back().second));
  1091. }
  1092. LastModuleImportLoc = ImportLoc;
  1093. LastModuleImportResult = Module;
  1094. return Module;
  1095. }