clang 22.0.0git
CompilerInstance.cpp
Go to the documentation of this file.
1//===--- CompilerInstance.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "clang/AST/Decl.h"
19#include "clang/Basic/Stack.h"
21#include "clang/Basic/Version.h"
22#include "clang/Config/config.h"
39#include "clang/Sema/Sema.h"
44#include "llvm/ADT/IntrusiveRefCntPtr.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/ADT/Statistic.h"
48#include "llvm/Config/llvm-config.h"
49#include "llvm/Support/AdvisoryLock.h"
50#include "llvm/Support/BuryPointer.h"
51#include "llvm/Support/CrashRecoveryContext.h"
52#include "llvm/Support/Errc.h"
53#include "llvm/Support/FileSystem.h"
54#include "llvm/Support/MemoryBuffer.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/Signals.h"
57#include "llvm/Support/TimeProfiler.h"
58#include "llvm/Support/Timer.h"
59#include "llvm/Support/VirtualFileSystem.h"
60#include "llvm/Support/VirtualOutputBackends.h"
61#include "llvm/Support/VirtualOutputError.h"
62#include "llvm/Support/raw_ostream.h"
63#include "llvm/TargetParser/Host.h"
64#include <optional>
65#include <time.h>
66#include <utility>
67
68using namespace clang;
69
70CompilerInstance::CompilerInstance(
71 std::shared_ptr<CompilerInvocation> Invocation,
72 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
73 ModuleCache *ModCache)
74 : ModuleLoader(/*BuildingModule=*/ModCache),
75 Invocation(std::move(Invocation)),
76 ModCache(ModCache ? ModCache : createCrossProcessModuleCache()),
77 ThePCHContainerOperations(std::move(PCHContainerOps)) {
78 assert(this->Invocation && "Invocation must not be null");
79}
80
82 assert(OutputFiles.empty() && "Still output files in flight?");
83}
84
86 return (BuildGlobalModuleIndex ||
87 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
88 getFrontendOpts().GenerateGlobalModuleIndex)) &&
89 !DisableGeneratingGlobalModuleIndex;
90}
91
96
98 OwnedVerboseOutputStream.reset();
99 VerboseOutputStream = &Value;
100}
101
102void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
103 OwnedVerboseOutputStream.swap(Value);
104 VerboseOutputStream = OwnedVerboseOutputStream.get();
105}
106
109
111 // Create the target instance.
114 if (!hasTarget())
115 return false;
116
117 // Check whether AuxTarget exists, if not, then create TargetInfo for the
118 // other side of CUDA/OpenMP/SYCL compilation.
119 if (!getAuxTarget() &&
120 (getLangOpts().CUDA || getLangOpts().isTargetDevice()) &&
121 !getFrontendOpts().AuxTriple.empty()) {
122 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
123 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
124 if (getFrontendOpts().AuxTargetCPU)
125 TO->CPU = *getFrontendOpts().AuxTargetCPU;
126 if (getFrontendOpts().AuxTargetFeatures)
127 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
128 TO->HostTriple = getTarget().getTriple().str();
130 }
131
132 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
133 if (getLangOpts().RoundingMath) {
134 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
135 getLangOpts().RoundingMath = false;
136 }
137 auto FPExc = getLangOpts().getFPExceptionMode();
138 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
139 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
140 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
141 }
142 // FIXME: can we disable FEnvAccess?
143 }
144
145 // We should do it here because target knows nothing about
146 // language options when it's being created.
147 if (getLangOpts().OpenCL &&
148 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
149 return false;
150
151 // Inform the target of the language options.
152 // FIXME: We shouldn't need to do this, the target should be immutable once
153 // created. This complexity should be lifted elsewhere.
155
156 if (auto *Aux = getAuxTarget())
157 getTarget().setAuxTarget(Aux);
158
159 return true;
160}
161
163 assert(Value == nullptr ||
164 getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr());
165 FileMgr = std::move(Value);
166}
167
172
173void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
174 PP = std::move(Value);
175}
176
179 Context = std::move(Value);
180
181 if (Context && Consumer)
183}
184
186 TheSema.reset(S);
187}
188
189void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
190 Consumer = std::move(Value);
191
192 if (Context && Consumer)
194}
195
199
200std::unique_ptr<Sema> CompilerInstance::takeSema() {
201 return std::move(TheSema);
202}
203
205 return TheASTReader;
206}
208 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
209 "Expected ASTReader to use the same PCM cache");
210 TheASTReader = std::move(Reader);
211}
212
213std::shared_ptr<ModuleDependencyCollector>
215 return ModuleDepCollector;
216}
217
219 std::shared_ptr<ModuleDependencyCollector> Collector) {
220 ModuleDepCollector = std::move(Collector);
221}
222
223static void collectHeaderMaps(const HeaderSearch &HS,
224 std::shared_ptr<ModuleDependencyCollector> MDC) {
225 SmallVector<std::string, 4> HeaderMapFileNames;
226 HS.getHeaderMapFileNames(HeaderMapFileNames);
227 for (auto &Name : HeaderMapFileNames)
228 MDC->addFile(Name);
229}
230
232 std::shared_ptr<ModuleDependencyCollector> MDC) {
233 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
234 if (PPOpts.ImplicitPCHInclude.empty())
235 return;
236
237 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
239 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
240 if (!PCHDir) {
241 MDC->addFile(PCHInclude);
242 return;
243 }
244
245 std::error_code EC;
246 SmallString<128> DirNative;
247 llvm::sys::path::native(PCHDir->getName(), DirNative);
248 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
250 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
251 Dir != DirEnd && !EC; Dir.increment(EC)) {
252 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
253 // used here since we're not interested in validating the PCH at this time,
254 // but only to check whether this is a file containing an AST.
256 Dir->path(), FileMgr, CI.getModuleCache(),
258 /*FindModuleFileExtensions=*/false, Validator,
259 /*ValidateDiagnosticOptions=*/false))
260 MDC->addFile(Dir->path());
261 }
262}
263
265 std::shared_ptr<ModuleDependencyCollector> MDC) {
266 // Collect all VFS found.
268 CI.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &VFS) {
269 if (auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
270 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
271 });
272
273 for (auto &E : VFSEntries)
274 MDC->addFile(E.VPath, E.RPath);
275}
276
279 DiagnosticOptions DiagOpts;
280 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC,
281 /*ShouldOwnClient=*/false);
282
284 std::move(BaseFS));
285 // FIXME: Should this go into createVFSFromCompilerInvocation?
286 if (getFrontendOpts().ShowStats)
287 VFS =
288 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
289}
290
291// Diagnostics
293 const CodeGenOptions *CodeGenOpts,
294 DiagnosticsEngine &Diags) {
295 std::error_code EC;
296 std::unique_ptr<raw_ostream> StreamOwner;
297 raw_ostream *OS = &llvm::errs();
298 if (DiagOpts.DiagnosticLogFile != "-") {
299 // Create the output stream.
300 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
301 DiagOpts.DiagnosticLogFile, EC,
302 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
303 if (EC) {
304 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
305 << DiagOpts.DiagnosticLogFile << EC.message();
306 } else {
307 FileOS->SetUnbuffered();
308 OS = FileOS.get();
309 StreamOwner = std::move(FileOS);
310 }
311 }
312
313 // Chain in the diagnostic client which will log the diagnostics.
314 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
315 std::move(StreamOwner));
316 if (CodeGenOpts)
317 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
318 if (Diags.ownsClient()) {
319 Diags.setClient(
320 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
321 } else {
322 Diags.setClient(
323 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
324 }
325}
326
328 DiagnosticsEngine &Diags,
329 StringRef OutputFile) {
330 auto SerializedConsumer =
331 clang::serialized_diags::create(OutputFile, DiagOpts);
332
333 if (Diags.ownsClient()) {
335 Diags.takeClient(), std::move(SerializedConsumer)));
336 } else {
338 Diags.getClient(), std::move(SerializedConsumer)));
339 }
340}
341
343 bool ShouldOwnClient) {
345 Client, ShouldOwnClient, &getCodeGenOpts());
346}
347
349 llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
350 DiagnosticConsumer *Client, bool ShouldOwnClient,
351 const CodeGenOptions *CodeGenOpts) {
352 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
353 DiagnosticIDs::create(), Opts);
354
355 // Create the diagnostic client for reporting errors or for
356 // implementing -verify.
357 if (Client) {
358 Diags->setClient(Client, ShouldOwnClient);
359 } else if (Opts.getFormat() == DiagnosticOptions::SARIF) {
360 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
361 } else
362 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
363
364 // Chain in -verify checker, if requested.
365 if (Opts.VerifyDiagnostics)
366 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
367
368 // Chain in -diagnostic-log-file dumper, if requested.
369 if (!Opts.DiagnosticLogFile.empty())
370 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
371
372 if (!Opts.DiagnosticSerializationFile.empty())
374
375 // Configure our handling of diagnostics.
376 ProcessWarningOptions(*Diags, Opts, VFS);
377
378 return Diags;
379}
380
381// File Manager
382
384 assert(VFS && "CompilerInstance needs a VFS for creating FileManager");
385 FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(), VFS);
386}
387
388// Source Manager
389
391 assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager");
392 assert(FileMgr && "FileManager needed for creating SourceManager");
393 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(),
395}
396
397// Initialize the remapping of files to alternative contents, e.g.,
398// those specified through other files.
400 SourceManager &SourceMgr,
402 const PreprocessorOptions &InitOpts) {
403 // Remap files in the source manager (with buffers).
404 for (const auto &RB : InitOpts.RemappedFileBuffers) {
405 // Create the file entry for the file that we're mapping from.
406 FileEntryRef FromFile =
407 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
408
409 // Override the contents of the "from" file with the contents of the
410 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
411 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
412 // to the SourceManager.
413 if (InitOpts.RetainRemappedFileBuffers)
414 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
415 else
416 SourceMgr.overrideFileContents(
417 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
418 }
419
420 // Remap files in the source manager (with other files).
421 for (const auto &RF : InitOpts.RemappedFiles) {
422 // Find the file that we're mapping to.
423 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
424 if (!ToFile) {
425 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
426 continue;
427 }
428
429 // Create the file entry for the file that we're mapping from.
430 FileEntryRef FromFile =
431 FileMgr.getVirtualFileRef(RF.first, ToFile->getSize(), 0);
432
433 // Override the contents of the "from" file with the contents of
434 // the "to" file.
435 SourceMgr.overrideFileContents(FromFile, *ToFile);
436 }
437
438 SourceMgr.setOverridenFilesKeepOriginalName(
440}
441
442// Preprocessor
443
446
447 // The AST reader holds a reference to the old preprocessor (if any).
448 TheASTReader.reset();
449
450 // Create the Preprocessor.
451 HeaderSearch *HeaderInfo =
454 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
456 getSourceManager(), *HeaderInfo, *this,
457 /*IdentifierInfoLookup=*/nullptr,
458 /*OwnsHeaderSearch=*/true, TUKind);
460 PP->Initialize(getTarget(), getAuxTarget());
461
462 if (PPOpts.DetailedRecord)
463 PP->createPreprocessingRecord();
464
465 // Apply remappings to the source manager.
466 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
467 PP->getFileManager(), PPOpts);
468
469 // Predefine macros and configure the preprocessor.
472
473 // Initialize the header search object. In CUDA compilations, we use the aux
474 // triple (the host triple) to initialize our header search, since we need to
475 // find the host headers in order to compile the CUDA code.
476 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
477 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
478 PP->getAuxTargetInfo())
479 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
480
481 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
482 PP->getLangOpts(), *HeaderSearchTriple);
483
484 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
485
486 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
487 std::string ModuleHash = getInvocation().getModuleHash();
488 PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
489 PP->getHeaderSearchInfo().setModuleCachePath(
490 getSpecificModuleCachePath(ModuleHash));
491 }
492
493 // Handle generating dependencies, if requested.
495 if (!DepOpts.OutputFile.empty())
496 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
497 if (!DepOpts.DOTOutputFile.empty())
499 getHeaderSearchOpts().Sysroot);
500
501 // If we don't have a collector, but we are collecting module dependencies,
502 // then we're the top level compiler instance and need to create one.
503 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
504 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
506 }
507
508 // If there is a module dep collector, register with other dep collectors
509 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
510 if (ModuleDepCollector) {
511 addDependencyCollector(ModuleDepCollector);
512 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
513 collectIncludePCH(*this, ModuleDepCollector);
514 collectVFSEntries(*this, ModuleDepCollector);
515 }
516
517 // Modules need an output manager.
518 if (!hasOutputManager())
520
521 for (auto &Listener : DependencyCollectors)
522 Listener->attachToPreprocessor(*PP);
523
524 // Handle generating header include information, if requested.
525 if (DepOpts.ShowHeaderIncludes)
526 AttachHeaderIncludeGen(*PP, DepOpts);
527 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
528 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
529 if (OutputPath == "-")
530 OutputPath = "";
531 AttachHeaderIncludeGen(*PP, DepOpts,
532 /*ShowAllHeaders=*/true, OutputPath,
533 /*ShowDepth=*/false);
534 }
535
537 AttachHeaderIncludeGen(*PP, DepOpts,
538 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
539 /*ShowDepth=*/true, /*MSStyle=*/true);
540 }
541
542 if (GetDependencyDirectives)
543 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
544}
545
546std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
547 assert(FileMgr && "Specific module cache path requires a FileManager");
548
549 // Set up the module path, including the hash for the module-creation options.
550 SmallString<256> SpecificModuleCache;
551 normalizeModuleCachePath(*FileMgr, getHeaderSearchOpts().ModuleCachePath,
552 SpecificModuleCache);
553 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
554 llvm::sys::path::append(SpecificModuleCache, ModuleHash);
555 return std::string(SpecificModuleCache);
556}
557
558// ASTContext
559
562 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
563 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
564 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
565 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
566 setASTContext(std::move(Context));
567}
568
569// ExternalASTSource
570
571namespace {
572// Helper to recursively read the module names for all modules we're adding.
573// We mark these as known and redirect any attempt to load that module to
574// the files we were handed.
575struct ReadModuleNames : ASTReaderListener {
576 Preprocessor &PP;
578
579 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
580
581 void ReadModuleName(StringRef ModuleName) override {
582 // Keep the module name as a string for now. It's not safe to create a new
583 // IdentifierInfo from an ASTReader callback.
584 LoadedModules.push_back(ModuleName.str());
585 }
586
587 void registerAll() {
588 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
589 for (const std::string &LoadedModule : LoadedModules)
590 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
591 MM.findOrLoadModule(LoadedModule));
592 LoadedModules.clear();
593 }
594
595 void markAllUnavailable() {
596 for (const std::string &LoadedModule : LoadedModules) {
598 LoadedModule)) {
599 M->HasIncompatibleModuleFile = true;
600
601 // Mark module as available if the only reason it was unavailable
602 // was missing headers.
603 SmallVector<Module *, 2> Stack;
604 Stack.push_back(M);
605 while (!Stack.empty()) {
606 Module *Current = Stack.pop_back_val();
607 if (Current->IsUnimportable) continue;
608 Current->IsAvailable = true;
609 auto SubmodulesRange = Current->submodules();
610 llvm::append_range(Stack, SubmodulesRange);
611 }
612 }
613 }
614 LoadedModules.clear();
615 }
616};
617} // namespace
618
620 StringRef Path, DisableValidationForModuleKind DisableValidation,
621 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
622 bool OwnDeserializationListener) {
624 TheASTReader = createPCHExternalASTSource(
625 Path, getHeaderSearchOpts().Sysroot, DisableValidation,
626 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
628 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
629 DeserializationListener, OwnDeserializationListener, Preamble,
630 getFrontendOpts().UseGlobalModuleIndex);
631}
632
634 StringRef Path, StringRef Sysroot,
635 DisableValidationForModuleKind DisableValidation,
636 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
637 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
638 const CodeGenOptions &CodeGenOpts,
639 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
640 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
641 void *DeserializationListener, bool OwnDeserializationListener,
642 bool Preamble, bool UseGlobalModuleIndex) {
643 const HeaderSearchOptions &HSOpts =
644 PP.getHeaderSearchInfo().getHeaderSearchOpts();
645
646 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
647 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
648 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
649 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
652 HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex);
653
654 // We need the external source to be set up before we read the AST, because
655 // eagerly-deserialized declarations may use it.
656 Context.setExternalSource(Reader);
657
658 Reader->setDeserializationListener(
659 static_cast<ASTDeserializationListener *>(DeserializationListener),
660 /*TakeOwnership=*/OwnDeserializationListener);
661
662 for (auto &Listener : DependencyCollectors)
663 Listener->attachToASTReader(*Reader);
664
665 auto Listener = std::make_unique<ReadModuleNames>(PP);
666 auto &ListenerRef = *Listener;
667 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
668 std::move(Listener));
669
670 switch (Reader->ReadAST(Path,
676 // Set the predefines buffer as suggested by the PCH reader. Typically, the
677 // predefines buffer will be empty.
678 PP.setPredefines(Reader->getSuggestedPredefines());
679 ListenerRef.registerAll();
680 return Reader;
681
683 // Unrecoverable failure: don't even try to process the input file.
684 break;
685
691 // No suitable PCH file could be found. Return an error.
692 break;
693 }
694
695 ListenerRef.markAllUnavailable();
696 Context.setExternalSource(nullptr);
697 return nullptr;
698}
699
700// Code Completion
701
703 StringRef Filename,
704 unsigned Line,
705 unsigned Column) {
706 // Tell the source manager to chop off the given file at a specific
707 // line and column.
708 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
709 if (!Entry) {
710 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
711 << Filename;
712 return true;
713 }
714
715 // Truncate the named file at the given line/column.
717 return false;
718}
719
722 if (!CompletionConsumer) {
724 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
725 getFrontendOpts().CodeCompleteOpts, llvm::outs()));
726 return;
728 Loc.Line, Loc.Column)) {
730 return;
731 }
732}
733
735 timerGroup.reset(new llvm::TimerGroup("clang", "Clang time report"));
736 FrontendTimer.reset(new llvm::Timer("frontend", "Front end", *timerGroup));
737}
738
741 StringRef Filename,
742 unsigned Line,
743 unsigned Column,
744 const CodeCompleteOptions &Opts,
745 raw_ostream &OS) {
746 if (EnableCodeCompletion(PP, Filename, Line, Column))
747 return nullptr;
748
749 // Set up the creation routine for code-completion.
750 return new PrintingCodeCompleteConsumer(Opts, OS);
751}
752
754 CodeCompleteConsumer *CompletionConsumer) {
755 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
756 TUKind, CompletionConsumer));
757
758 // Set up API notes.
759 TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
760
761 // Attach the external sema source if there is any.
762 if (ExternalSemaSrc) {
763 TheSema->addExternalSource(ExternalSemaSrc);
764 ExternalSemaSrc->InitializeSema(*TheSema);
765 }
766
767 // If we're building a module and are supposed to load API notes,
768 // notify the API notes manager.
769 if (auto *currentModule = getPreprocessor().getCurrentModule()) {
770 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
771 currentModule, getLangOpts().APINotesModules,
772 getAPINotesOpts().ModuleSearchPaths);
773 }
774}
775
776// Output Files
777
779 // The ASTConsumer can own streams that write to the output files.
780 assert(!hasASTConsumer() && "ASTConsumer should be reset");
781 if (!EraseFiles) {
782 for (auto &O : OutputFiles)
783 llvm::handleAllErrors(
784 O.keep(),
785 [&](const llvm::vfs::TempFileOutputError &E) {
786 getDiagnostics().Report(diag::err_unable_to_rename_temp)
787 << E.getTempPath() << E.getOutputPath()
788 << E.convertToErrorCode().message();
789 },
790 [&](const llvm::vfs::OutputError &E) {
791 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
792 << E.getOutputPath() << E.convertToErrorCode().message();
793 },
794 [&](const llvm::ErrorInfoBase &EIB) { // Handle any remaining error
795 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
796 << O.getPath() << EIB.message();
797 });
798 }
799 OutputFiles.clear();
800 if (DeleteBuiltModules) {
801 for (auto &Module : BuiltModules)
802 llvm::sys::fs::remove(Module.second);
803 BuiltModules.clear();
804 }
805}
806
807std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
808 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
809 bool CreateMissingDirectories, bool ForceUseTemporary) {
810 StringRef OutputPath = getFrontendOpts().OutputFile;
811 std::optional<SmallString<128>> PathStorage;
812 if (OutputPath.empty()) {
813 if (InFile == "-" || Extension.empty()) {
814 OutputPath = "-";
815 } else {
816 PathStorage.emplace(InFile);
817 llvm::sys::path::replace_extension(*PathStorage, Extension);
818 OutputPath = *PathStorage;
819 }
820 }
821
822 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
823 getFrontendOpts().UseTemporary || ForceUseTemporary,
824 CreateMissingDirectories);
825}
826
827std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
828 return std::make_unique<llvm::raw_null_ostream>();
829}
830
831// Output Manager
832
835 assert(!OutputMgr && "Already has an output manager");
836 OutputMgr = std::move(NewOutputs);
837}
838
840 assert(!OutputMgr && "Already has an output manager");
841 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
842}
843
844llvm::vfs::OutputBackend &CompilerInstance::getOutputManager() {
845 assert(OutputMgr);
846 return *OutputMgr;
847}
848
850 if (!hasOutputManager())
852 return getOutputManager();
853}
854
855std::unique_ptr<raw_pwrite_stream>
857 bool RemoveFileOnSignal, bool UseTemporary,
858 bool CreateMissingDirectories) {
860 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
861 CreateMissingDirectories);
862 if (OS)
863 return std::move(*OS);
864 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
865 << OutputPath << errorToErrorCode(OS.takeError()).message();
866 return nullptr;
867}
868
870CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
871 bool RemoveFileOnSignal,
872 bool UseTemporary,
873 bool CreateMissingDirectories) {
874 assert((!CreateMissingDirectories || UseTemporary) &&
875 "CreateMissingDirectories is only allowed when using temporary files");
876
877 // If '-working-directory' was passed, the output filename should be
878 // relative to that.
879 std::optional<SmallString<128>> AbsPath;
880 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
881 assert(hasFileManager() &&
882 "File Manager is required to fix up relative path.\n");
883
884 AbsPath.emplace(OutputPath);
886 OutputPath = *AbsPath;
887 }
888
889 using namespace llvm::vfs;
891 OutputPath,
892 OutputConfig()
893 .setTextWithCRLF(!Binary)
894 .setDiscardOnSignal(RemoveFileOnSignal)
895 .setAtomicWrite(UseTemporary)
896 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
897 if (!O)
898 return O.takeError();
899
900 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
901 OutputFiles.push_back(std::move(*O));
902 return OutputFiles.back().createProxy();
903}
904
905// Initialization Utilities
906
911
912// static
914 DiagnosticsEngine &Diags,
915 FileManager &FileMgr,
916 SourceManager &SourceMgr) {
922
923 if (Input.isBuffer()) {
924 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
925 assert(SourceMgr.getMainFileID().isValid() &&
926 "Couldn't establish MainFileID!");
927 return true;
928 }
929
930 StringRef InputFile = Input.getFile();
931
932 // Figure out where to get and map in the main file.
933 auto FileOrErr = InputFile == "-"
934 ? FileMgr.getSTDIN()
935 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
936 if (!FileOrErr) {
937 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
938 if (InputFile != "-")
939 Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
940 else
941 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
942 return false;
943 }
944
945 SourceMgr.setMainFileID(
946 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
947
948 assert(SourceMgr.getMainFileID().isValid() &&
949 "Couldn't establish MainFileID!");
950 return true;
951}
952
953// High-Level Operations
954
956 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
957 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
958 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
959
960 // Mark this point as the bottom of the stack if we don't have somewhere
961 // better. We generally expect frontend actions to be invoked with (nearly)
962 // DesiredStackSpace available.
964
965 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
966 // Notify the diagnostic client that all files were processed.
968 });
969
970 raw_ostream &OS = getVerboseOutputStream();
971
972 if (!Act.PrepareToExecute(*this))
973 return false;
974
975 if (!createTarget())
976 return false;
977
978 // rewriter project will change target built-in bool type from its default.
979 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
981
982 // Validate/process some options.
983 if (getHeaderSearchOpts().Verbose)
984 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
985 << LLVM_VERSION_STRING << " default target "
986 << llvm::sys::getDefaultTargetTriple() << "\n";
987
988 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
989 llvm::EnableStatistics(false);
990
991 // Sort vectors containing toc data and no toc data variables to facilitate
992 // binary search later.
993 llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
994 llvm::sort(getCodeGenOpts().NoTocDataVars);
995
996 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
997 // Reset the ID tables if we are reusing the SourceManager and parsing
998 // regular files.
1001
1002 if (Act.BeginSourceFile(*this, FIF)) {
1003 if (llvm::Error Err = Act.Execute()) {
1004 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1005 }
1006 Act.EndSourceFile();
1007 }
1008 }
1009
1011
1012 if (getFrontendOpts().ShowStats) {
1013 if (hasFileManager()) {
1015 OS << '\n';
1016 }
1017 llvm::PrintStatistics(OS);
1018 }
1019 StringRef StatsFile = getFrontendOpts().StatsFile;
1020 if (!StatsFile.empty()) {
1021 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1022 if (getFrontendOpts().AppendStats)
1023 FileFlags |= llvm::sys::fs::OF_Append;
1024 std::error_code EC;
1025 auto StatS =
1026 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1027 if (EC) {
1028 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1029 << StatsFile << EC.message();
1030 } else {
1031 llvm::PrintStatisticsJSON(*StatS);
1032 }
1033 }
1034
1035 return !getDiagnostics().getClient()->getNumErrors();
1036}
1037
1039 if (!getDiagnosticOpts().ShowCarets)
1040 return;
1041
1042 raw_ostream &OS = getVerboseOutputStream();
1043
1044 // We can have multiple diagnostics sharing one diagnostic client.
1045 // Get the total number of warnings/errors from the client.
1046 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1047 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1048
1049 if (NumWarnings)
1050 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1051 if (NumWarnings && NumErrors)
1052 OS << " and ";
1053 if (NumErrors)
1054 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1055 if (NumWarnings || NumErrors) {
1056 OS << " generated";
1057 if (getLangOpts().CUDA) {
1058 if (!getLangOpts().CUDAIsDevice) {
1059 OS << " when compiling for host";
1060 } else {
1061 OS << " when compiling for "
1062 << (!getTargetOpts().CPU.empty() ? getTargetOpts().CPU
1063 : getTarget().getTriple().str());
1064 }
1065 }
1066 OS << ".\n";
1067 }
1068}
1069
1071 // Load any requested plugins.
1072 for (const std::string &Path : getFrontendOpts().Plugins) {
1073 std::string Error;
1074 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1075 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1076 << Path << Error;
1077 }
1078
1079 // Check if any of the loaded plugins replaces the main AST action
1080 for (const FrontendPluginRegistry::entry &Plugin :
1081 FrontendPluginRegistry::entries()) {
1082 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1083 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1085 getFrontendOpts().ActionName = Plugin.getName().str();
1086 break;
1087 }
1088 }
1089}
1090
1091/// Determine the appropriate source input kind based on language
1092/// options.
1094 if (LangOpts.OpenCL)
1095 return Language::OpenCL;
1096 if (LangOpts.CUDA)
1097 return Language::CUDA;
1098 if (LangOpts.ObjC)
1099 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1100 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1101}
1102
1103std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1104 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
1105 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1106 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1107 // Construct a compiler invocation for creating this module.
1108 auto Invocation = std::make_shared<CompilerInvocation>(getInvocation());
1109
1110 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1111
1112 // For any options that aren't intended to affect how a module is built,
1113 // reset them to their default values.
1114 Invocation->resetNonModularOptions();
1115
1116 // Remove any macro definitions that are explicitly ignored by the module.
1117 // They aren't supposed to affect how the module is built anyway.
1118 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1119 llvm::erase_if(PPOpts.Macros,
1120 [&HSOpts](const std::pair<std::string, bool> &def) {
1121 StringRef MacroDef = def.first;
1122 return HSOpts.ModulesIgnoreMacros.contains(
1123 llvm::CachedHashString(MacroDef.split('=').first));
1124 });
1125
1126 // If the original compiler invocation had -fmodule-name, pass it through.
1127 Invocation->getLangOpts().ModuleName =
1129
1130 // Note the name of the module we're building.
1131 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1132
1133 // If there is a module map file, build the module using the module map.
1134 // Set up the inputs/outputs so that we build the module from its umbrella
1135 // header.
1136 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1137 FrontendOpts.OutputFile = ModuleFileName.str();
1138 FrontendOpts.DisableFree = false;
1139 FrontendOpts.GenerateGlobalModuleIndex = false;
1140 FrontendOpts.BuildingImplicitModule = true;
1141 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1142 // Force implicitly-built modules to hash the content of the module file.
1143 HSOpts.ModulesHashContent = true;
1144 FrontendOpts.Inputs = {std::move(Input)};
1145
1146 // Don't free the remapped file buffers; they are owned by our caller.
1147 PPOpts.RetainRemappedFileBuffers = true;
1148
1149 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1150
1151 DiagOpts.VerifyDiagnostics = 0;
1152 assert(getInvocation().getModuleHash() == Invocation->getModuleHash() &&
1153 "Module hash mismatch!");
1154
1155 // Construct a compiler instance that will be used to actually create the
1156 // module. Since we're sharing an in-memory module cache,
1157 // CompilerInstance::CompilerInstance is responsible for finalizing the
1158 // buffers to prevent use-after-frees.
1159 auto InstancePtr = std::make_unique<CompilerInstance>(
1160 std::move(Invocation), getPCHContainerOperations(), &getModuleCache());
1161 auto &Instance = *InstancePtr;
1162
1163 auto &Inv = Instance.getInvocation();
1164
1165 if (ThreadSafeConfig) {
1166 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1167 Instance.createFileManager();
1168 } else if (FrontendOpts.ModulesShareFileManager) {
1169 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1170 Instance.setFileManager(getFileManagerPtr());
1171 } else {
1172 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1173 Instance.createFileManager();
1174 }
1175
1176 if (ThreadSafeConfig) {
1177 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1178 /*ShouldOwnClient=*/false);
1179 } else {
1180 Instance.createDiagnostics(
1181 new ForwardingDiagnosticConsumer(getDiagnosticClient()),
1182 /*ShouldOwnClient=*/true);
1183 }
1184 if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1185 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1186
1187 Instance.createSourceManager();
1188 SourceManager &SourceMgr = Instance.getSourceManager();
1189
1190 if (ThreadSafeConfig) {
1191 // Detecting cycles in the module graph is responsibility of the client.
1192 } else {
1193 // Note that this module is part of the module build stack, so that we
1194 // can detect cycles in the module graph.
1195 SourceMgr.setModuleBuildStack(getSourceManager().getModuleBuildStack());
1196 SourceMgr.pushModuleBuildStack(
1197 ModuleName, FullSourceLoc(ImportLoc, getSourceManager()));
1198 }
1199
1200 // Make a copy for the new instance.
1201 Instance.FailedModules = FailedModules;
1202
1203 if (GetDependencyDirectives)
1204 Instance.GetDependencyDirectives =
1205 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1206
1207 if (ThreadSafeConfig) {
1208 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1209 } else {
1210 // If we're collecting module dependencies, we need to share a collector
1211 // between all of the module CompilerInstances. Other than that, we don't
1212 // want to produce any dependency output from the module build.
1213 Instance.setModuleDepCollector(getModuleDepCollector());
1214 }
1215 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1216
1217 return InstancePtr;
1218}
1219
1221 StringRef ModuleName,
1222 StringRef ModuleFileName,
1223 CompilerInstance &Instance) {
1224 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1225
1226 // Never compile a module that's already finalized - this would cause the
1227 // existing module to be freed, causing crashes if it is later referenced
1228 if (getModuleCache().getInMemoryModuleCache().isPCMFinal(ModuleFileName)) {
1229 getDiagnostics().Report(ImportLoc, diag::err_module_rebuild_finalized)
1230 << ModuleName;
1231 return false;
1232 }
1233
1234 getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1235 << ModuleName << ModuleFileName;
1236
1237 // Execute the action to actually build the module in-place. Use a separate
1238 // thread so that we get a stack large enough.
1239 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1240 [&]() {
1242 Instance.ExecuteAction(Action);
1243 },
1245
1246 getDiagnostics().Report(ImportLoc, diag::remark_module_build_done)
1247 << ModuleName;
1248
1249 // Propagate the statistics to the parent FileManager.
1250 if (!getFrontendOpts().ModulesShareFileManager)
1251 getFileManager().AddStats(Instance.getFileManager());
1252
1253 // Propagate the failed modules to the parent instance.
1254 FailedModules = std::move(Instance.FailedModules);
1255
1256 if (Crashed) {
1257 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1258 // that must be closed before clearing output files.
1259 Instance.setSema(nullptr);
1260 Instance.setASTConsumer(nullptr);
1261
1262 // Delete any remaining temporary files related to Instance.
1263 Instance.clearOutputFiles(/*EraseFiles=*/true);
1264 }
1265
1266 // We've rebuilt a module. If we're allowed to generate or update the global
1267 // module index, record that fact in the importing compiler instance.
1268 if (getFrontendOpts().GenerateGlobalModuleIndex) {
1270 }
1271
1272 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1273 // occurred.
1274 return !Instance.getDiagnostics().hasErrorOccurred() ||
1275 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1276}
1277
1280 StringRef Filename = llvm::sys::path::filename(File.getName());
1281 SmallString<128> PublicFilename(File.getDir().getName());
1282 if (Filename == "module_private.map")
1283 llvm::sys::path::append(PublicFilename, "module.map");
1284 else if (Filename == "module.private.modulemap")
1285 llvm::sys::path::append(PublicFilename, "module.modulemap");
1286 else
1287 return std::nullopt;
1288 return FileMgr.getOptionalFileRef(PublicFilename);
1289}
1290
1291std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompile(
1292 SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName,
1293 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1294 StringRef ModuleName = Module->getTopLevelModuleName();
1295
1297
1298 // Get or create the module map that we'll use to build this module.
1300 SourceManager &SourceMgr = getSourceManager();
1301
1302 if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1303 ModuleMapFID.isValid()) {
1304 // We want to use the top-level module map. If we don't, the compiling
1305 // instance may think the containing module map is a top-level one, while
1306 // the importing instance knows it's included from a parent module map via
1307 // the extern directive. This mismatch could bite us later.
1308 SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1309 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1310 ModuleMapFID = SourceMgr.getFileID(Loc);
1311 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1312 }
1313
1314 OptionalFileEntryRef ModuleMapFile =
1315 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1316 assert(ModuleMapFile && "Top-level module map with no FileID");
1317
1318 // Canonicalize compilation to start with the public module map. This is
1319 // vital for submodules declarations in the private module maps to be
1320 // correctly parsed when depending on a top level module in the public one.
1321 if (OptionalFileEntryRef PublicMMFile =
1322 getPublicModuleMap(*ModuleMapFile, getFileManager()))
1323 ModuleMapFile = PublicMMFile;
1324
1325 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1326
1327 // Use the systemness of the module map as parsed instead of using the
1328 // IsSystem attribute of the module. If the module has [system] but the
1329 // module map is not in a system path, then this would incorrectly parse
1330 // any other modules in that module map as system too.
1331 const SrcMgr::SLocEntry &SLoc = SourceMgr.getSLocEntry(ModuleMapFID);
1332 bool IsSystem = isSystem(SLoc.getFile().getFileCharacteristic());
1333
1334 // Use the module map where this module resides.
1335 return cloneForModuleCompileImpl(
1336 ImportLoc, ModuleName,
1337 FrontendInputFile(ModuleMapFilePath, IK, IsSystem),
1338 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName,
1339 std::move(ThreadSafeConfig));
1340 }
1341
1342 // FIXME: We only need to fake up an input file here as a way of
1343 // transporting the module's directory to the module map parser. We should
1344 // be able to do that more directly, and parse from a memory buffer without
1345 // inventing this file.
1346 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1347 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1348
1349 std::string InferredModuleMapContent;
1350 llvm::raw_string_ostream OS(InferredModuleMapContent);
1351 Module->print(OS);
1352
1353 auto Instance = cloneForModuleCompileImpl(
1354 ImportLoc, ModuleName,
1355 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1356 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName,
1357 std::move(ThreadSafeConfig));
1358
1359 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1360 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1361 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1362 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1363 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1364 std::move(ModuleMapBuffer));
1365
1366 return Instance;
1367}
1368
1369/// Read the AST right after compiling the module.
1370static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1371 SourceLocation ImportLoc,
1372 SourceLocation ModuleNameLoc,
1373 Module *Module, StringRef ModuleFileName,
1374 bool *OutOfDate, bool *Missing) {
1375 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1376
1377 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1378 if (OutOfDate)
1379 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1380
1381 // Try to read the module file, now that we've compiled it.
1382 ASTReader::ASTReadResult ReadResult =
1383 ImportingInstance.getASTReader()->ReadAST(
1384 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1385 ModuleLoadCapabilities);
1386 if (ReadResult == ASTReader::Success)
1387 return true;
1388
1389 // The caller wants to handle out-of-date failures.
1390 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1391 *OutOfDate = true;
1392 return false;
1393 }
1394
1395 // The caller wants to handle missing module files.
1396 if (Missing && ReadResult == ASTReader::Missing) {
1397 *Missing = true;
1398 return false;
1399 }
1400
1401 // The ASTReader didn't diagnose the error, so conservatively report it.
1402 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1403 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1404 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1405
1406 return false;
1407}
1408
1409/// Compile a module in a separate compiler instance and read the AST,
1410/// returning true if the module compiles without errors.
1411static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1412 SourceLocation ImportLoc,
1413 SourceLocation ModuleNameLoc,
1414 Module *Module,
1415 StringRef ModuleFileName) {
1416 {
1417 auto Instance = ImportingInstance.cloneForModuleCompile(
1418 ModuleNameLoc, Module, ModuleFileName);
1419
1420 if (!ImportingInstance.compileModule(ModuleNameLoc,
1422 ModuleFileName, *Instance)) {
1423 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1424 diag::err_module_not_built)
1425 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1426 return false;
1427 }
1428 }
1429
1430 // The module is built successfully, we can update its timestamp now.
1431 if (ImportingInstance.getPreprocessor()
1435 ImportingInstance.getModuleCache().updateModuleTimestamp(ModuleFileName);
1436 }
1437
1438 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1439 Module, ModuleFileName,
1440 /*OutOfDate=*/nullptr, /*Missing=*/nullptr);
1441}
1442
1443/// Compile a module in a separate compiler instance and read the AST,
1444/// returning true if the module compiles without errors, using a lock manager
1445/// to avoid building the same module in multiple compiler instances.
1446///
1447/// Uses a lock file manager and exponential backoff to reduce the chances that
1448/// multiple instances will compete to create the same module. On timeout,
1449/// deletes the lock file in order to avoid deadlock from crashing processes or
1450/// bugs in the lock file manager.
1452 CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1453 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1454 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1455
1456 Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1457 << ModuleFileName << Module->Name;
1458
1459 auto &ModuleCache = ImportingInstance.getModuleCache();
1460 ModuleCache.prepareForGetLock(ModuleFileName);
1461
1462 while (true) {
1463 auto Lock = ModuleCache.getLock(ModuleFileName);
1464 bool Owned;
1465 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1466 // ModuleCache takes care of correctness and locks are only necessary for
1467 // performance. Fallback to building the module in case of any lock
1468 // related errors.
1469 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1470 << Module->Name << toString(std::move(Err));
1471 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1472 ModuleNameLoc, Module, ModuleFileName);
1473 }
1474 if (Owned) {
1475 // We're responsible for building the module ourselves.
1476 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1477 ModuleNameLoc, Module, ModuleFileName);
1478 }
1479
1480 // Someone else is responsible for building the module. Wait for them to
1481 // finish.
1482 switch (Lock->waitForUnlockFor(std::chrono::seconds(90))) {
1483 case llvm::WaitForUnlockResult::Success:
1484 break; // The interesting case.
1485 case llvm::WaitForUnlockResult::OwnerDied:
1486 continue; // try again to get the lock.
1487 case llvm::WaitForUnlockResult::Timeout:
1488 // Since the InMemoryModuleCache takes care of correctness, we try waiting
1489 // for someone else to complete the build so that it does not happen
1490 // twice. In case of timeout, build it ourselves.
1491 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1492 << Module->Name;
1493 // Clear the lock file so that future invocations can make progress.
1494 Lock->unsafeMaybeUnlock();
1495 continue;
1496 }
1497
1498 // Read the module that was just written by someone else.
1499 bool OutOfDate = false;
1500 bool Missing = false;
1501 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1502 Module, ModuleFileName, &OutOfDate, &Missing))
1503 return true;
1504 if (!OutOfDate && !Missing)
1505 return false;
1506
1507 // The module may be missing or out of date in the presence of file system
1508 // races. It may also be out of date if one of its imports depends on header
1509 // search paths that are not consistent with this ImportingInstance.
1510 // Try again...
1511 }
1512}
1513
1514/// Compile a module in a separate compiler instance and read the AST,
1515/// returning true if the module compiles without errors, potentially using a
1516/// lock manager to avoid building the same module in multiple compiler
1517/// instances.
1518static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1519 SourceLocation ImportLoc,
1520 SourceLocation ModuleNameLoc,
1521 Module *Module, StringRef ModuleFileName) {
1522 return ImportingInstance.getInvocation()
1525 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1526 ModuleNameLoc, Module,
1527 ModuleFileName)
1528 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1529 ModuleNameLoc, Module,
1530 ModuleFileName);
1531}
1532
1533/// Diagnose differences between the current definition of the given
1534/// configuration macro and the definition provided on the command line.
1535static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1536 Module *Mod, SourceLocation ImportLoc) {
1537 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1538 SourceManager &SourceMgr = PP.getSourceManager();
1539
1540 // If this identifier has never had a macro definition, then it could
1541 // not have changed.
1542 if (!Id->hadMacroDefinition())
1543 return;
1544 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1545
1546 // Find the macro definition from the command line.
1547 MacroInfo *CmdLineDefinition = nullptr;
1548 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1549 // We only care about the predefines buffer.
1550 FileID FID = SourceMgr.getFileID(MD->getLocation());
1551 if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1552 continue;
1553 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1554 CmdLineDefinition = DMD->getMacroInfo();
1555 break;
1556 }
1557
1558 auto *CurrentDefinition = PP.getMacroInfo(Id);
1559 if (CurrentDefinition == CmdLineDefinition) {
1560 // Macro matches. Nothing to do.
1561 } else if (!CurrentDefinition) {
1562 // This macro was defined on the command line, then #undef'd later.
1563 // Complain.
1564 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1565 << true << ConfigMacro << Mod->getFullModuleName();
1566 auto LatestDef = LatestLocalMD->getDefinition();
1567 assert(LatestDef.isUndefined() &&
1568 "predefined macro went away with no #undef?");
1569 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1570 << true;
1571 return;
1572 } else if (!CmdLineDefinition) {
1573 // There was no definition for this macro in the predefines buffer,
1574 // but there was a local definition. Complain.
1575 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1576 << false << ConfigMacro << Mod->getFullModuleName();
1577 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1578 diag::note_module_def_undef_here)
1579 << false;
1580 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1581 /*Syntactically=*/true)) {
1582 // The macro definitions differ.
1583 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1584 << false << ConfigMacro << Mod->getFullModuleName();
1585 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1586 diag::note_module_def_undef_here)
1587 << false;
1588 }
1589}
1590
1592 SourceLocation ImportLoc) {
1593 clang::Module *TopModule = M->getTopLevelModule();
1594 for (const StringRef ConMacro : TopModule->ConfigMacros) {
1595 checkConfigMacro(PP, ConMacro, M, ImportLoc);
1596 }
1597}
1598
1600 if (TheASTReader)
1601 return;
1602
1603 if (!hasASTContext())
1605
1606 // If we're implicitly building modules but not currently recursively
1607 // building a module, check whether we need to prune the module cache.
1608 if (getSourceManager().getModuleBuildStack().empty() &&
1609 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1610 ModCache->maybePrune(getHeaderSearchOpts().ModuleCachePath,
1611 getHeaderSearchOpts().ModuleCachePruneInterval,
1612 getHeaderSearchOpts().ModuleCachePruneAfter);
1613
1615 std::string Sysroot = HSOpts.Sysroot;
1616 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1617 const FrontendOptions &FEOpts = getFrontendOpts();
1618 std::unique_ptr<llvm::Timer> ReadTimer;
1619
1620 if (timerGroup)
1621 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1622 "Reading modules", *timerGroup);
1623 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1626 getFrontendOpts().ModuleFileExtensions,
1627 Sysroot.empty() ? "" : Sysroot.c_str(),
1629 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1630 /*AllowConfigurationMismatch=*/false,
1634 +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1635 if (hasASTConsumer()) {
1636 TheASTReader->setDeserializationListener(
1637 getASTConsumer().GetASTDeserializationListener());
1639 getASTConsumer().GetASTMutationListener());
1640 }
1641 getASTContext().setExternalSource(TheASTReader);
1642 if (hasSema())
1643 TheASTReader->InitializeSema(getSema());
1644 if (hasASTConsumer())
1645 TheASTReader->StartTranslationUnit(&getASTConsumer());
1646
1647 for (auto &Listener : DependencyCollectors)
1648 Listener->attachToASTReader(*TheASTReader);
1649}
1650
1652 StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1653 llvm::Timer Timer;
1654 if (timerGroup)
1655 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1656 *timerGroup);
1657 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1658
1659 // If we don't already have an ASTReader, create one now.
1660 if (!TheASTReader)
1662
1663 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1664 // ASTReader to diagnose it, since it can produce better errors that we can.
1665 bool ConfigMismatchIsRecoverable =
1666 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1669
1670 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1671 auto &ListenerRef = *Listener;
1672 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1673 std::move(Listener));
1674
1675 // Try to load the module file.
1676 switch (TheASTReader->ReadAST(
1678 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1679 &LoadedModuleFile)) {
1680 case ASTReader::Success:
1681 // We successfully loaded the module file; remember the set of provided
1682 // modules so that we don't try to load implicit modules for them.
1683 ListenerRef.registerAll();
1684 return true;
1685
1687 // Ignore unusable module files.
1688 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1689 << FileName;
1690 // All modules provided by any files we tried and failed to load are now
1691 // unavailable; includes of those modules should now be handled textually.
1692 ListenerRef.markAllUnavailable();
1693 return true;
1694
1695 default:
1696 return false;
1697 }
1698}
1699
1700namespace {
1701enum ModuleSource {
1702 MS_ModuleNotFound,
1703 MS_ModuleCache,
1704 MS_PrebuiltModulePath,
1705 MS_ModuleBuildPragma
1706};
1707} // end namespace
1708
1709/// Select a source for loading the named module and compute the filename to
1710/// load it from.
1711static ModuleSource selectModuleSource(
1712 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1713 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1714 HeaderSearch &HS) {
1715 assert(ModuleFilename.empty() && "Already has a module source?");
1716
1717 // Check to see if the module has been built as part of this compilation
1718 // via a module build pragma.
1719 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1720 if (BuiltModuleIt != BuiltModules.end()) {
1721 ModuleFilename = BuiltModuleIt->second;
1722 return MS_ModuleBuildPragma;
1723 }
1724
1725 // Try to load the module from the prebuilt module path.
1726 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1727 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1728 !HSOpts.PrebuiltModulePaths.empty()) {
1729 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1730 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1731 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1732 if (!ModuleFilename.empty())
1733 return MS_PrebuiltModulePath;
1734 }
1735
1736 // Try to load the module from the module cache.
1737 if (M) {
1738 ModuleFilename = HS.getCachedModuleFileName(M);
1739 return MS_ModuleCache;
1740 }
1741
1742 return MS_ModuleNotFound;
1743}
1744
1745ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1746 StringRef ModuleName, SourceLocation ImportLoc,
1747 SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1748 // Search for a module with the given name.
1749 HeaderSearch &HS = PP->getHeaderSearchInfo();
1750 Module *M =
1751 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1752
1753 // Check for any configuration macros that have changed. This is done
1754 // immediately before potentially building a module in case this module
1755 // depends on having one of its configuration macros defined to successfully
1756 // build. If this is not done the user will never see the warning.
1757 if (M)
1758 checkConfigMacros(getPreprocessor(), M, ImportLoc);
1759
1760 // Select the source and filename for loading the named module.
1761 std::string ModuleFilename;
1762 ModuleSource Source =
1763 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1764 if (Source == MS_ModuleNotFound) {
1765 // We can't find a module, error out here.
1766 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1767 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1768 return nullptr;
1769 }
1770 if (ModuleFilename.empty()) {
1771 if (M && M->HasIncompatibleModuleFile) {
1772 // We tried and failed to load a module file for this module. Fall
1773 // back to textual inclusion for its headers.
1775 }
1776
1777 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1778 << ModuleName;
1779 return nullptr;
1780 }
1781
1782 // Create an ASTReader on demand.
1783 if (!getASTReader())
1785
1786 // Time how long it takes to load the module.
1787 llvm::Timer Timer;
1788 if (timerGroup)
1789 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1790 *timerGroup);
1791 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1792 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1793
1794 // Try to load the module file. If we are not trying to load from the
1795 // module cache, we don't know how to rebuild modules.
1796 unsigned ARRFlags = Source == MS_ModuleCache
1799 : Source == MS_PrebuiltModulePath
1800 ? 0
1802 switch (getASTReader()->ReadAST(ModuleFilename,
1803 Source == MS_PrebuiltModulePath
1805 : Source == MS_ModuleBuildPragma
1808 ImportLoc, ARRFlags)) {
1809 case ASTReader::Success: {
1810 if (M)
1811 return M;
1812 assert(Source != MS_ModuleCache &&
1813 "missing module, but file loaded from cache");
1814
1815 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1816 // until the first call to ReadAST. Look it up now.
1817 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1818
1819 // Check whether M refers to the file in the prebuilt module path.
1820 if (M && M->getASTFile())
1821 if (auto ModuleFile = FileMgr->getOptionalFileRef(ModuleFilename))
1822 if (*ModuleFile == M->getASTFile())
1823 return M;
1824
1825 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1826 << ModuleName;
1827 return ModuleLoadResult();
1828 }
1829
1831 case ASTReader::Missing:
1832 // The most interesting case.
1833 break;
1834
1836 if (Source == MS_PrebuiltModulePath)
1837 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1838 // produce a warning here!
1839 getDiagnostics().Report(SourceLocation(),
1840 diag::warn_module_config_mismatch)
1841 << ModuleFilename;
1842 // Fall through to error out.
1843 [[fallthrough]];
1847 // FIXME: The ASTReader will already have complained, but can we shoehorn
1848 // that diagnostic information into a more useful form?
1849 return ModuleLoadResult();
1850
1851 case ASTReader::Failure:
1853 return ModuleLoadResult();
1854 }
1855
1856 // ReadAST returned Missing or OutOfDate.
1857 if (Source != MS_ModuleCache) {
1858 // We don't know the desired configuration for this module and don't
1859 // necessarily even have a module map. Since ReadAST already produces
1860 // diagnostics for these two cases, we simply error out here.
1861 return ModuleLoadResult();
1862 }
1863
1864 // The module file is missing or out-of-date. Build it.
1865 assert(M && "missing module, but trying to compile for cache");
1866
1867 // Check whether there is a cycle in the module graph.
1869 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1870 for (; Pos != PosEnd; ++Pos) {
1871 if (Pos->first == ModuleName)
1872 break;
1873 }
1874
1875 if (Pos != PosEnd) {
1876 SmallString<256> CyclePath;
1877 for (; Pos != PosEnd; ++Pos) {
1878 CyclePath += Pos->first;
1879 CyclePath += " -> ";
1880 }
1881 CyclePath += ModuleName;
1882
1883 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1884 << ModuleName << CyclePath;
1885 return nullptr;
1886 }
1887
1888 // Check whether we have already attempted to build this module (but failed).
1889 if (FailedModules.contains(ModuleName)) {
1890 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1891 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1892 return nullptr;
1893 }
1894
1895 // Try to compile and then read the AST.
1896 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1897 ModuleFilename)) {
1898 assert(getDiagnostics().hasErrorOccurred() &&
1899 "undiagnosed error in compileModuleAndReadAST");
1900 FailedModules.insert(ModuleName);
1901 return nullptr;
1902 }
1903
1904 // Okay, we've rebuilt and now loaded the module.
1905 return M;
1906}
1907
1910 ModuleIdPath Path,
1912 bool IsInclusionDirective) {
1913 // Determine what file we're searching from.
1914 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
1915 SourceLocation ModuleNameLoc = Path[0].getLoc();
1916
1917 // If we've already handled this import, just return the cached result.
1918 // This one-element cache is important to eliminate redundant diagnostics
1919 // when both the preprocessor and parser see the same import declaration.
1920 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1921 // Make the named module visible.
1922 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1923 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1924 ImportLoc);
1925 return LastModuleImportResult;
1926 }
1927
1928 // If we don't already have information on this module, load the module now.
1929 Module *Module = nullptr;
1931 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].getIdentifierInfo())) {
1932 // Use the cached result, which may be nullptr.
1933 Module = *MaybeModule;
1934 // Config macros are already checked before building a module, but they need
1935 // to be checked at each import location in case any of the config macros
1936 // have a new value at the current `ImportLoc`.
1937 if (Module)
1939 } else if (ModuleName == getLangOpts().CurrentModule) {
1940 // This is the module we're building.
1941 Module = PP->getHeaderSearchInfo().lookupModule(
1942 ModuleName, ImportLoc, /*AllowSearch*/ true,
1943 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1944
1945 // Config macros do not need to be checked here for two reasons.
1946 // * This will always be textual inclusion, and thus the config macros
1947 // actually do impact the content of the header.
1948 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
1949 // function as the `#include` or `#import` is textual.
1950
1951 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
1952 } else {
1953 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1954 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1955 if (!Result.isNormal())
1956 return Result;
1957 if (!Result)
1958 DisableGeneratingGlobalModuleIndex = true;
1959 Module = Result;
1960 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
1961 }
1962
1963 // If we never found the module, fail. Otherwise, verify the module and link
1964 // it up.
1965 if (!Module)
1966 return ModuleLoadResult();
1967
1968 // Verify that the rest of the module path actually corresponds to
1969 // a submodule.
1970 bool MapPrivateSubModToTopLevel = false;
1971 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1972 StringRef Name = Path[I].getIdentifierInfo()->getName();
1973 clang::Module *Sub = Module->findSubmodule(Name);
1974
1975 // If the user is requesting Foo.Private and it doesn't exist, try to
1976 // match Foo_Private and emit a warning asking for the user to write
1977 // @import Foo_Private instead. FIXME: remove this when existing clients
1978 // migrate off of Foo.Private syntax.
1979 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
1980 SmallString<128> PrivateModule(Module->Name);
1981 PrivateModule.append("_Private");
1982
1984 auto &II = PP->getIdentifierTable().get(
1985 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
1986 PrivPath.emplace_back(Path[0].getLoc(), &II);
1987
1988 std::string FileName;
1989 // If there is a modulemap module or prebuilt module, load it.
1990 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
1991 !IsInclusionDirective) ||
1992 selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
1993 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
1994 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1995 if (Sub) {
1996 MapPrivateSubModToTopLevel = true;
1997 PP->markClangModuleAsAffecting(Module);
1998 if (!getDiagnostics().isIgnored(
1999 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2000 getDiagnostics().Report(Path[I].getLoc(),
2001 diag::warn_no_priv_submodule_use_toplevel)
2002 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2003 << PrivateModule
2004 << SourceRange(Path[0].getLoc(), Path[I].getLoc())
2005 << FixItHint::CreateReplacement(SourceRange(Path[0].getLoc()),
2006 PrivateModule);
2007 getDiagnostics().Report(Sub->DefinitionLoc,
2008 diag::note_private_top_level_defined);
2009 }
2010 }
2011 }
2012
2013 if (!Sub) {
2014 // Attempt to perform typo correction to find a module name that works.
2016 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2017
2018 for (class Module *SubModule : Module->submodules()) {
2019 unsigned ED =
2020 Name.edit_distance(SubModule->Name,
2021 /*AllowReplacements=*/true, BestEditDistance);
2022 if (ED <= BestEditDistance) {
2023 if (ED < BestEditDistance) {
2024 Best.clear();
2025 BestEditDistance = ED;
2026 }
2027
2028 Best.push_back(SubModule->Name);
2029 }
2030 }
2031
2032 // If there was a clear winner, user it.
2033 if (Best.size() == 1) {
2034 getDiagnostics().Report(Path[I].getLoc(),
2035 diag::err_no_submodule_suggest)
2036 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2037 << Best[0] << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2038 << FixItHint::CreateReplacement(SourceRange(Path[I].getLoc()),
2039 Best[0]);
2040
2041 Sub = Module->findSubmodule(Best[0]);
2042 }
2043 }
2044
2045 if (!Sub) {
2046 // No submodule by this name. Complain, and don't look for further
2047 // submodules.
2048 getDiagnostics().Report(Path[I].getLoc(), diag::err_no_submodule)
2049 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2050 << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2051 break;
2052 }
2053
2054 Module = Sub;
2055 }
2056
2057 // Make the named module visible, if it's not already part of the module
2058 // we are parsing.
2059 if (ModuleName != getLangOpts().CurrentModule) {
2060 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2061 // We have an umbrella header or directory that doesn't actually include
2062 // all of the headers within the directory it covers. Complain about
2063 // this missing submodule and recover by forgetting that we ever saw
2064 // this submodule.
2065 // FIXME: Should we detect this at module load time? It seems fairly
2066 // expensive (and rare).
2067 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2069 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2070
2072 }
2073
2074 // Check whether this module is available.
2076 *Module, getDiagnostics())) {
2077 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2078 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2079 LastModuleImportLoc = ImportLoc;
2080 LastModuleImportResult = ModuleLoadResult();
2081 return ModuleLoadResult();
2082 }
2083
2084 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2085 }
2086
2087 // Resolve any remaining module using export_as for this one.
2090 .getModuleMap()
2092
2093 LastModuleImportLoc = ImportLoc;
2094 LastModuleImportResult = ModuleLoadResult(Module);
2095 return LastModuleImportResult;
2096}
2097
2099 StringRef ModuleName,
2100 StringRef Source) {
2101 // Avoid creating filenames with special characters.
2102 SmallString<128> CleanModuleName(ModuleName);
2103 for (auto &C : CleanModuleName)
2104 if (!isAlphanumeric(C))
2105 C = '_';
2106
2107 // FIXME: Using a randomized filename here means that our intermediate .pcm
2108 // output is nondeterministic (as .pcm files refer to each other by name).
2109 // Can this affect the output in any way?
2110 SmallString<128> ModuleFileName;
2111 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2112 CleanModuleName, "pcm", ModuleFileName)) {
2113 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2114 << ModuleFileName << EC.message();
2115 return;
2116 }
2117 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2118
2119 FrontendInputFile Input(
2120 ModuleMapFileName,
2121 InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2122 InputKind::ModuleMap, /*Preprocessed*/true));
2123
2124 std::string NullTerminatedSource(Source.str());
2125
2126 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2127 StringRef(), ModuleFileName);
2128
2129 // Create a virtual file containing our desired source.
2130 // FIXME: We shouldn't need to do this.
2131 FileEntryRef ModuleMapFile = Other->getFileManager().getVirtualFileRef(
2132 ModuleMapFileName, NullTerminatedSource.size(), 0);
2133 Other->getSourceManager().overrideFileContents(
2134 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2135
2136 Other->BuiltModules = std::move(BuiltModules);
2137 Other->DeleteBuiltModules = false;
2138
2139 // Build the module, inheriting any modules that we've built locally.
2140 bool Success = compileModule(ImportLoc, ModuleName, ModuleFileName, *Other);
2141
2142 BuiltModules = std::move(Other->BuiltModules);
2143
2144 if (Success) {
2145 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2146 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2147 }
2148}
2149
2152 SourceLocation ImportLoc) {
2153 if (!TheASTReader)
2155 if (!TheASTReader)
2156 return;
2157
2158 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2159}
2160
2162 SourceLocation TriggerLoc) {
2163 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2164 return nullptr;
2165 if (!TheASTReader)
2167 // Can't do anything if we don't have the module manager.
2168 if (!TheASTReader)
2169 return nullptr;
2170 // Get an existing global index. This loads it if not already
2171 // loaded.
2172 TheASTReader->loadGlobalIndex();
2173 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2174 // If the global index doesn't exist, create it.
2175 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2176 hasPreprocessor()) {
2177 llvm::sys::fs::create_directories(
2178 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2179 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2181 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2182 // FIXME this drops the error on the floor. This code is only used for
2183 // typo correction and drops more than just this one source of errors
2184 // (such as the directory creation failure above). It should handle the
2185 // error.
2186 consumeError(std::move(Err));
2187 return nullptr;
2188 }
2189 TheASTReader->resetForReload();
2190 TheASTReader->loadGlobalIndex();
2191 GlobalIndex = TheASTReader->getGlobalIndex();
2192 }
2193 // For finding modules needing to be imported for fixit messages,
2194 // we need to make the global index cover all modules, so we do that here.
2195 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2197 bool RecreateIndex = false;
2199 E = MMap.module_end(); I != E; ++I) {
2200 Module *TheModule = I->second;
2201 OptionalFileEntryRef Entry = TheModule->getASTFile();
2202 if (!Entry) {
2204 Path.emplace_back(TriggerLoc,
2205 getPreprocessor().getIdentifierInfo(TheModule->Name));
2206 std::reverse(Path.begin(), Path.end());
2207 // Load a module as hidden. This also adds it to the global index.
2208 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2209 RecreateIndex = true;
2210 }
2211 }
2212 if (RecreateIndex) {
2213 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2215 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2216 // FIXME As above, this drops the error on the floor.
2217 consumeError(std::move(Err));
2218 return nullptr;
2219 }
2220 TheASTReader->resetForReload();
2221 TheASTReader->loadGlobalIndex();
2222 GlobalIndex = TheASTReader->getGlobalIndex();
2223 }
2224 HaveFullGlobalModuleIndex = true;
2225 }
2226 return GlobalIndex;
2227}
2228
2229// Check global module index for missing imports.
2230bool
2232 SourceLocation TriggerLoc) {
2233 // Look for the symbol in non-imported modules, but only if an error
2234 // actually occurred.
2235 if (!buildingModule()) {
2236 // Load global module index, or retrieve a previously loaded one.
2238 TriggerLoc);
2239
2240 // Only if we have a global index.
2241 if (GlobalIndex) {
2242 GlobalModuleIndex::HitSet FoundModules;
2243
2244 // Find the modules that reference the identifier.
2245 // Note that this only finds top-level modules.
2246 // We'll let diagnoseTypo find the actual declaration module.
2247 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2248 return true;
2249 }
2250 }
2251
2252 return false;
2253}
2254void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2255
2258 ExternalSemaSrc = std::move(ESS);
2259}
Defines the clang::ASTContext interface.
Defines the Diagnostic-related interfaces.
static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static void SetupSerializedDiagnostics(DiagnosticOptions &DiagOpts, DiagnosticsEngine &Diags, StringRef OutputFile)
static bool compileModuleAndReadASTBehindLock(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static Language getLanguageFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, Module *Mod, SourceLocation ImportLoc)
Diagnose differences between the current definition of the given configuration macro and the definiti...
static void collectHeaderMaps(const HeaderSearch &HS, std::shared_ptr< ModuleDependencyCollector > MDC)
static ModuleSource selectModuleSource(Module *M, StringRef ModuleName, std::string &ModuleFilename, const std::map< std::string, std::string, std::less<> > &BuiltModules, HeaderSearch &HS)
Select a source for loading the named module and compute the filename to load it from.
static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName, bool *OutOfDate, bool *Missing)
Read the AST right after compiling the module.
static void InitializeFileRemapping(DiagnosticsEngine &Diags, SourceManager &SourceMgr, FileManager &FileMgr, const PreprocessorOptions &InitOpts)
static void collectIncludePCH(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File, FileManager &FileMgr)
static void checkConfigMacros(Preprocessor &PP, Module *M, SourceLocation ImportLoc)
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Compile a module in a separate compiler instance and read the AST, returning true if the module compi...
static void SetUpDiagnosticLog(DiagnosticOptions &DiagOpts, const CodeGenOptions *CodeGenOpts, DiagnosticsEngine &Diags)
Defines the clang::FileManager interface and associated types.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the SourceManager interface.
Defines utilities for dealing with stack allocation and stack space.
Defines version macros and version-related utility functions for Clang.
virtual void Initialize(ASTContext &Context)
Initialize - This is called to initialize the consumer, providing the ASTContext.
Definition ASTConsumer.h:48
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
RAII object to temporarily add an AST callback listener.
Definition ASTReader.h:1918
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition ASTReader.h:1831
@ ARR_None
The client can't handle any AST loading failures.
Definition ASTReader.h:1827
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1844
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition ASTReader.h:1835
@ ARR_TreatModuleWithErrorsAsOutOfDate
If a module file is marked with errors treat it as out-of-date so the caller can rebuild it.
Definition ASTReader.h:1848
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition ASTReader.h:450
@ Success
The control block was read successfully.
Definition ASTReader.h:453
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:470
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:463
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:456
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:466
@ HadErrors
The AST file has errors.
Definition ASTReader.h:473
@ Missing
The AST file was missing.
Definition ASTReader.h:459
ChainedDiagnosticConsumer - Chain two diagnostic clients so that diagnostics go to the first client a...
Abstract interface for a consumer of code-completion information.
Options controlling the behavior of code completion.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
void createPCHExternalASTSource(StringRef Path, DisableValidationForModuleKind DisableValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
DiagnosticConsumer & getDiagnosticClient() const
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
void setOutputManager(IntrusiveRefCntPtr< llvm::vfs::OutputBackend > NewOutputs)
Set the output manager.
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
DependencyOutputOptions & getDependencyOutputOpts()
TargetInfo * getAuxTarget() const
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
raw_ostream & getVerboseOutputStream()
Get the current stream for verbose output.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
bool compileModule(SourceLocation ImportLoc, StringRef ModuleName, StringRef ModuleFileName, CompilerInstance &Instance)
Compile a module file for the given module, using the options provided by the importing compiler inst...
std::string getSpecificModuleCachePath()
std::unique_ptr< CompilerInstance > cloneForModuleCompile(SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName, std::optional< ThreadSafeCloneConfig > ThreadSafeConfig=std::nullopt)
Creates a new CompilerInstance for compiling a module.
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
FileSystemOptions & getFileSystemOpts()
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
void createFileManager()
Create the file manager and replace any existing one with it.
FileManager & getFileManager() const
Return the current file manager to the caller.
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
void createOutputManager()
Create an output manager.
std::unique_ptr< Sema > takeSema()
void printDiagnosticStats()
At the end of a compilation, print the number of warnings/errors.
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
IntrusiveRefCntPtr< FileManager > getFileManagerPtr() const
ModuleCache & getModuleCache() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
void createASTContext()
Create the AST context.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
void createVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS=llvm::vfs::getRealFileSystem(), DiagnosticConsumer *DC=nullptr)
Create a virtual file system instance based on the invocation.
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
FrontendOptions & getFrontendOpts()
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
void setASTContext(llvm::IntrusiveRefCntPtr< ASTContext > Value)
setASTContext - Replace the current AST context.
HeaderSearchOptions & getHeaderSearchOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
void createSourceManager()
Create the source manager and replace any existing one with it.
CompilerInvocation & getInvocation()
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
PreprocessorOptions & getPreprocessorOpts()
ASTConsumer & getASTConsumer() const
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager.
TargetInfo & getTarget() const
llvm::vfs::OutputBackend & getOutputManager()
llvm::vfs::FileSystem & getVirtualFileSystem() const
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
void setCodeCompletionConsumer(CodeCompleteConsumer *Value)
setCodeCompletionConsumer - Replace the current code completion consumer; the compiler instance takes...
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
DiagnosticOptions & getDiagnosticOpts()
llvm::vfs::OutputBackend & getOrCreateOutputManager()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
void setDiagnostics(llvm::IntrusiveRefCntPtr< DiagnosticsEngine > Value)
setDiagnostics - Replace the current diagnostics engine.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
APINotesOptions & getAPINotesOpts()
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool loadModuleFile(StringRef FileName, serialization::ModuleFile *&LoadedModuleFile)
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
LangOptions & getLangOpts()
Mutable getters.
FrontendOptions & getFrontendOpts()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
std::string OutputFile
The file to write dependency output to.
std::string HeaderIncludeOutputFile
The file to write header include output to.
unsigned ShowHeaderIncludes
Show header inclusions (-H).
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
unsigned getNumErrors() const
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
unsigned getNumWarnings() const
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
std::string DiagnosticLogFile
The file to log diagnostic output to.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-headers-in-module=... options used to override whether -Wsystem-headers is enabl...
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool hasErrorOccurred() const
Definition Diagnostic.h:872
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition Diagnostic.h:615
DiagnosticConsumer * getClient()
Definition Diagnostic.h:607
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:966
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition Diagnostic.h:611
StringRef getName() const
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
off_t getSize() const
Definition FileEntry.h:346
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
StringRef getNameAsRequested() const
The name of this FileEntry, as originally requested without applying any remappings for VFS 'use-exte...
Definition FileEntry.h:68
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
void AddStats(const FileManager &Other)
Import statistics from a child FileManager and add them to this current FileManager.
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
void PrintStats() const
static bool fixupRelativePath(const FileSystemOptions &FileSystemOpts, SmallVectorImpl< char > &Path)
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
Abstract base class for actions which can be performed by the frontend.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
bool PrepareToExecute(CompilerInstance &CI)
Prepare the action to execute on the given compiler instance.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
An input file for the front end.
llvm::MemoryBufferRef getBuffer() const
InputKind getKind() const
StringRef getFile() const
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
unsigned AllowPCMWithCompilerErrors
Output (and read) PCM files regardless of compiler errors.
unsigned BuildingImplicitModuleUsesLock
Whether to use a filesystem lock when building implicit modules.
unsigned ModulesShareFileManager
Whether to share the FileManager when building modules.
std::optional< std::string > AuxTargetCPU
Auxiliary target CPU for CUDA/HIP compilation.
std::string StatsFile
Filename to write statistics to.
std::string OutputFile
The output file, if any.
std::string ActionName
The name of the action to run when using a plugin action.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred,...
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
unsigned DisableFree
Disable memory freeing on exit.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
frontend::ActionKind ProgramAction
The frontend action to perform.
std::optional< std::vector< std::string > > AuxTargetFeatures
Auxiliary target features for CUDA/HIP compilation.
A global index for a set of module files, providing information about the identifiers within those mo...
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
bool lookupIdentifier(llvm::StringRef Name, HitSet &Hits)
Look for all of the module files with information about the given identifier, e.g....
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
unsigned ModulesForceValidateUserHeaders
Whether to force the validation of user input files when a module is loaded (even despite the build s...
std::map< std::string, std::string, std::less<> > PrebuiltModuleFiles
The mapping of module names to prebuilt module files.
std::vector< std::string > PrebuiltModulePaths
The directories used to load prebuilt module files.
unsigned ModulesValidateSystemHeaders
Whether to validate system input files when a module is loaded.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
void getHeaderMapFileNames(SmallVectorImpl< std::string > &Names) const
Get filenames for all registered header maps.
std::string getPrebuiltImplicitModuleFileName(Module *Module)
Retrieve the name of the prebuilt module file that should be used to load the given module.
const HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module.
ModuleMap & getModuleMap()
Retrieve the module map.
std::string getPrebuiltModuleFileName(StringRef ModuleName, bool FileMapOnly=false)
Retrieve the name of the prebuilt module file that should be used to load a module with the given nam...
One of these records is kept for each identifier that is lexed.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
The kind of a file that we've been handed as an input.
Format getFormat() const
@ FPE_Default
Used internally to represent initial unspecified value.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:26
virtual void prepareForGetLock(StringRef ModuleFilename)=0
May perform any work that only needs to be performed once for multiple calls getLock() with the same ...
virtual void updateModuleTimestamp(StringRef ModuleFilename)=0
Updates the timestamp denoting the last time inputs of the module file were validated.
virtual std::unique_ptr< llvm::AdvisoryLock > getLock(StringRef ModuleFilename)=0
Returns lock for the given module file. The lock is initially unlocked.
Describes the result of attempting to load a module.
bool buildingModule() const
Returns true if this instance is building a module.
ModuleLoader(bool BuildingModule=false)
llvm::StringMap< Module * >::const_iterator module_iterator
Definition ModuleMap.h:745
module_iterator module_begin() const
Definition ModuleMap.h:747
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition ModuleMap.h:759
module_iterator module_end() const
Definition ModuleMap.h:748
FileID getContainingModuleMapFileID(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition ModuleMap.cpp:51
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Definition ModuleMap.h:754
Module * findOrLoadModule(StringRef Name)
Describes a module or submodule.
Definition Module.h:144
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:732
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
Definition Module.cpp:350
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:528
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:361
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:443
@ Hidden
All of the names in this module are hidden.
Definition Module.h:445
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
Definition Module.cpp:463
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:389
std::string Name
The name of this module.
Definition Module.h:147
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:838
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:198
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:376
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
Definition Module.h:365
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:372
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition Module.h:737
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
@ ReplaceAction
Replace the main action.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
DisableValidationForModuleKind DisablePCHOrModuleValidation
Whether to disable most of the normal validation performed on precompiled headers and module files.
std::vector< std::pair< std::string, bool > > Macros
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
bool SetCodeCompletionPoint(FileEntryRef File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, const Module &M, DiagnosticsEngine &Diags)
Check that the given module is available, producing a diagnostic if not.
FileManager & getFileManager() const
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
HeaderSearch & getHeaderSearchInfo() const
DiagnosticsEngine & getDiagnostics() const
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
A simple code-completion consumer that prints the results it receives in a simple format.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:362
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
A trivial tuple used to represent a source range.
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
Exposes information about the current target.
Definition TargetInfo.h:226
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition Targets.cpp:792
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual void setAuxTarget(const TargetInfo *Aux)
void noSignedCharForObjCBool()
Definition TargetInfo.h:939
virtual void adjust(DiagnosticsEngine &Diags, LangOptions &Opts, const TargetInfo *Aux)
Set forced language options.
std::string CPU
If given, the name of the target CPU to generate code for.
VerifyDiagnosticConsumer - Create a diagnostic client which will use markers in the input source to c...
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:130
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
@ PluginAction
Run a plugin action,.
@ RewriteObjC
ObjC->C Rewriter.
bool Inv(InterpState &S, CodePtr OpPC)
Definition Interp.h:643
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:51
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:54
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:48
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:45
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:60
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions &DiagOpts, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
@ HeaderSearch
Remove unused header search paths including header maps.
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
ArrayRef< std::pair< std::string, FullSourceLoc > > ModuleBuildStack
The stack used when building modules on demand, which is used to provide a link between the source ma...
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
@ Success
Annotation was successful.
Definition Parser.h:65
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts, const CodeGenOptions &CodeGenOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
Definition CharInfo.h:138
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
Language
The language for the input, used to select and validate the language standard and possible actions.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
void normalizeModuleCachePath(FileManager &FileMgr, StringRef Path, SmallVectorImpl< char > &NormalizedPath)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
Definition Stack.h:26
IntrusiveRefCntPtr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
void noteBottomOfStack(bool ForceSet=false)
Call this once on each thread, as soon after starting the thread as feasible, to note the approximate...
Definition Stack.cpp:20
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, llvm::vfs::FileSystem &VFS, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition Warnings.cpp:46
TranslationUnitKind
Describes the kind of translation unit being processed.
void AttachHeaderIncludeGen(Preprocessor &PP, const DependencyOutputOptions &DepOpts, bool ShowAllHeaders=false, StringRef OutputPath={}, bool ShowDepth=true, bool MSStyle=false)
AttachHeaderIncludeGen - Create a header include list generator, and attach it to the given preproces...
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ Other
Other implicit parameter.
Definition Decl.h:1746
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition Visibility.h:34
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, StringRef SysRoot)
AttachDependencyGraphGen - Create a dependency graph generator, and attach it to the given preprocess...
A source location that has been parsed on the command line.