CompilerInstance.cpp 60 KB

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