clang 23.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"
20#include "clang/Basic/Stack.h"
22#include "clang/Basic/Version.h"
23#include "clang/Config/config.h"
39#include "clang/Sema/Sema.h"
45#include "llvm/ADT/IntrusiveRefCntPtr.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/ScopeExit.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/Config/llvm-config.h"
50#include "llvm/Plugins/PassPlugin.h"
51#include "llvm/Support/AdvisoryLock.h"
52#include "llvm/Support/BuryPointer.h"
53#include "llvm/Support/CrashRecoveryContext.h"
54#include "llvm/Support/Errc.h"
55#include "llvm/Support/FileSystem.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/Path.h"
58#include "llvm/Support/Signals.h"
59#include "llvm/Support/SmallVectorMemoryBuffer.h"
60#include "llvm/Support/TimeProfiler.h"
61#include "llvm/Support/Timer.h"
62#include "llvm/Support/VirtualFileSystem.h"
63#include "llvm/Support/VirtualOutputBackends.h"
64#include "llvm/Support/VirtualOutputError.h"
65#include "llvm/Support/raw_ostream.h"
66#include "llvm/TargetParser/Host.h"
67#include <optional>
68#include <time.h>
69#include <utility>
70
71using namespace clang;
72
73CompilerInstance::CompilerInstance(
74 std::shared_ptr<CompilerInvocation> Invocation,
75 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
76 std::shared_ptr<ModuleCache> ModCache)
77 : ModuleLoader(/*BuildingModule=*/ModCache != nullptr),
78 Invocation(std::move(Invocation)),
79 ModCache(ModCache ? std::move(ModCache)
81 ThePCHContainerOperations(std::move(PCHContainerOps)) {
82 assert(this->Invocation && "Invocation must not be null");
83}
84
86 assert(OutputFiles.empty() && "Still output files in flight?");
87}
88
90 return (BuildGlobalModuleIndex ||
91 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
92 getFrontendOpts().GenerateGlobalModuleIndex)) &&
93 !DisableGeneratingGlobalModuleIndex;
94}
95
100
102 OwnedVerboseOutputStream.reset();
103 VerboseOutputStream = &Value;
104}
105
106void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
107 OwnedVerboseOutputStream.swap(Value);
108 VerboseOutputStream = OwnedVerboseOutputStream.get();
109}
110
113
115 // Create the target instance.
118 if (!hasTarget())
119 return false;
120
121 // Check whether AuxTarget exists, if not, then create TargetInfo for the
122 // other side of CUDA/OpenMP/SYCL compilation.
123 if (!getAuxTarget() &&
124 (getLangOpts().CUDA || getLangOpts().isTargetDevice()) &&
125 !getFrontendOpts().AuxTriple.empty()) {
126 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
127 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
128 if (getFrontendOpts().AuxTargetCPU)
129 TO->CPU = *getFrontendOpts().AuxTargetCPU;
130 if (getFrontendOpts().AuxTargetFeatures)
131 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
132 TO->HostTriple = getTarget().getTriple().str();
134 }
135
136 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
137 if (getLangOpts().RoundingMath) {
138 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
139 getLangOpts().RoundingMath = false;
140 }
141 auto FPExc = getLangOpts().getFPExceptionMode();
142 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
143 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
144 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
145 }
146 // FIXME: can we disable FEnvAccess?
147 }
148
149 // We should do it here because target knows nothing about
150 // language options when it's being created.
151 if (getLangOpts().OpenCL &&
152 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
153 return false;
154
155 // Inform the target of the language options.
156 // FIXME: We shouldn't need to do this, the target should be immutable once
157 // created. This complexity should be lifted elsewhere.
159
160 if (auto *Aux = getAuxTarget())
161 getTarget().setAuxTarget(Aux);
162
163 return true;
164}
165
167 assert(Value == nullptr ||
168 getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr());
169 FileMgr = std::move(Value);
170}
171
176
177void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
178 PP = std::move(Value);
179}
180
183 Context = std::move(Value);
184
185 if (Context && Consumer)
187}
188
190 TheSema.reset(S);
191}
192
193void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
194 Consumer = std::move(Value);
195
196 if (Context && Consumer)
198}
199
203
204std::unique_ptr<Sema> CompilerInstance::takeSema() {
205 return std::move(TheSema);
206}
207
209 return TheASTReader;
210}
212 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
213 "Expected ASTReader to use the same PCM cache");
214 TheASTReader = std::move(Reader);
215}
216
217std::shared_ptr<ModuleDependencyCollector>
219 return ModuleDepCollector;
220}
221
223 std::shared_ptr<ModuleDependencyCollector> Collector) {
224 ModuleDepCollector = std::move(Collector);
225}
226
227static void collectHeaderMaps(const HeaderSearch &HS,
228 std::shared_ptr<ModuleDependencyCollector> MDC) {
229 SmallVector<std::string, 4> HeaderMapFileNames;
230 HS.getHeaderMapFileNames(HeaderMapFileNames);
231 for (auto &Name : HeaderMapFileNames)
232 MDC->addFile(Name);
233}
234
236 std::shared_ptr<ModuleDependencyCollector> MDC) {
237 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
238 if (PPOpts.ImplicitPCHInclude.empty())
239 return;
240
241 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
243 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
244 if (!PCHDir) {
245 MDC->addFile(PCHInclude);
246 return;
247 }
248
249 std::error_code EC;
250 SmallString<128> DirNative;
251 llvm::sys::path::native(PCHDir->getName(), DirNative);
252 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
254 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
255 Dir != DirEnd && !EC; Dir.increment(EC)) {
256 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
257 // used here since we're not interested in validating the PCH at this time,
258 // but only to check whether this is a file containing an AST.
260 Dir->path(), FileMgr, CI.getModuleCache(),
262 /*FindModuleFileExtensions=*/false, Validator,
263 /*ValidateDiagnosticOptions=*/false))
264 MDC->addFile(Dir->path());
265 }
266}
267
269 std::shared_ptr<ModuleDependencyCollector> MDC) {
270 // Collect all VFS found.
272 CI.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &VFS) {
273 if (auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
274 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
275 });
276
277 for (auto &E : VFSEntries)
278 MDC->addFile(E.VPath, E.RPath);
279}
280
283 DiagnosticOptions DiagOpts;
284 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC,
285 /*ShouldOwnClient=*/false);
286
288 std::move(BaseFS));
289 // FIXME: Should this go into createVFSFromCompilerInvocation?
290 if (getFrontendOpts().ShowStats)
291 VFS =
292 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
293}
294
295// Diagnostics
297 const CodeGenOptions *CodeGenOpts,
298 DiagnosticsEngine &Diags) {
299 std::error_code EC;
300 std::unique_ptr<raw_ostream> StreamOwner;
301 raw_ostream *OS = &llvm::errs();
302 if (DiagOpts.DiagnosticLogFile != "-") {
303 // Create the output stream.
304 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
305 DiagOpts.DiagnosticLogFile, EC,
306 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
307 if (EC) {
308 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
309 << DiagOpts.DiagnosticLogFile << EC.message();
310 } else {
311 FileOS->SetUnbuffered();
312 OS = FileOS.get();
313 StreamOwner = std::move(FileOS);
314 }
315 }
316
317 // Chain in the diagnostic client which will log the diagnostics.
318 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
319 std::move(StreamOwner));
320 if (CodeGenOpts)
321 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
322 if (Diags.ownsClient()) {
323 Diags.setClient(
324 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
325 } else {
326 Diags.setClient(
327 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
328 }
329}
330
332 DiagnosticsEngine &Diags,
333 StringRef OutputFile) {
334 auto SerializedConsumer =
335 clang::serialized_diags::create(OutputFile, DiagOpts);
336
337 if (Diags.ownsClient()) {
339 Diags.takeClient(), std::move(SerializedConsumer)));
340 } else {
342 Diags.getClient(), std::move(SerializedConsumer)));
343 }
344}
345
347 bool ShouldOwnClient) {
349 Client, ShouldOwnClient, &getCodeGenOpts());
350}
351
353 llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
354 DiagnosticConsumer *Client, bool ShouldOwnClient,
355 const CodeGenOptions *CodeGenOpts) {
356 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
357 DiagnosticIDs::create(), Opts);
358
359 // Create the diagnostic client for reporting errors or for
360 // implementing -verify.
361 if (Client) {
362 Diags->setClient(Client, ShouldOwnClient);
363 } else if (Opts.getFormat() == DiagnosticOptions::SARIF) {
364 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
365 } else
366 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
367
368 // Chain in -verify checker, if requested.
369 if (Opts.VerifyDiagnostics)
370 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
371
372 // Chain in -diagnostic-log-file dumper, if requested.
373 if (!Opts.DiagnosticLogFile.empty())
374 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
375
376 if (!Opts.DiagnosticSerializationFile.empty())
378
379 // Configure our handling of diagnostics.
380 ProcessWarningOptions(*Diags, Opts, VFS);
381
382 return Diags;
383}
384
385// File Manager
386
388 assert(VFS && "CompilerInstance needs a VFS for creating FileManager");
389 FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(), VFS);
390}
391
392// Source Manager
393
395 assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager");
396 assert(FileMgr && "FileManager needed for creating SourceManager");
397 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(),
399}
400
401// Initialize the remapping of files to alternative contents, e.g.,
402// those specified through other files.
404 SourceManager &SourceMgr,
406 const PreprocessorOptions &InitOpts) {
407 // Remap files in the source manager (with buffers).
408 for (const auto &RB : InitOpts.RemappedFileBuffers) {
409 // Create the file entry for the file that we're mapping from.
410 FileEntryRef FromFile =
411 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
412
413 // Override the contents of the "from" file with the contents of the
414 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
415 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
416 // to the SourceManager.
417 if (InitOpts.RetainRemappedFileBuffers)
418 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
419 else
420 SourceMgr.overrideFileContents(
421 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
422 }
423
424 // Remap files in the source manager (with other files).
425 for (const auto &RF : InitOpts.RemappedFiles) {
426 // Find the file that we're mapping to.
427 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
428 if (!ToFile) {
429 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
430 continue;
431 }
432
433 // Create the file entry for the file that we're mapping from.
434 FileEntryRef FromFile =
435 FileMgr.getVirtualFileRef(RF.first, ToFile->getSize(), 0);
436
437 // Override the contents of the "from" file with the contents of
438 // the "to" file.
439 SourceMgr.overrideFileContents(FromFile, *ToFile);
440 }
441
442 SourceMgr.setOverridenFilesKeepOriginalName(
444}
445
446// Preprocessor
447
450
451 // The AST reader holds a reference to the old preprocessor (if any).
452 TheASTReader.reset();
453
454 // Create the Preprocessor.
455 HeaderSearch *HeaderInfo =
458 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
460 getSourceManager(), *HeaderInfo, *this,
461 /*IdentifierInfoLookup=*/nullptr,
462 /*OwnsHeaderSearch=*/true, TUKind);
464 PP->Initialize(getTarget(), getAuxTarget());
465
466 if (PPOpts.DetailedRecord)
467 PP->createPreprocessingRecord();
468
469 // Apply remappings to the source manager.
470 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
471 PP->getFileManager(), PPOpts);
472
473 // Predefine macros and configure the preprocessor.
476
477 // Initialize the header search object. In CUDA compilations, we use the aux
478 // triple (the host triple) to initialize our header search, since we need to
479 // find the host headers in order to compile the CUDA code.
480 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
481 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
482 PP->getAuxTargetInfo())
483 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
484
485 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
486 PP->getLangOpts(), *HeaderSearchTriple);
487
488 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
489
490 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
491 // FIXME: We already might've computed the context hash and the specific
492 // module cache path in `FrontendAction::BeginSourceFile()` when turning
493 // "-include-pch <DIR>" into "-include-pch <DIR>/<FILE>". Reuse those here.
494 PP->getHeaderSearchInfo().initializeModuleCachePath(
495 getInvocation().computeContextHash());
496 }
497
498 // Handle generating dependencies, if requested.
500 if (!DepOpts.OutputFile.empty())
501 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
502 if (!DepOpts.DOTOutputFile.empty())
504 getHeaderSearchOpts().Sysroot);
505
506 // If we don't have a collector, but we are collecting module dependencies,
507 // then we're the top level compiler instance and need to create one.
508 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
509 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
511 }
512
513 // If there is a module dep collector, register with other dep collectors
514 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
515 if (ModuleDepCollector) {
516 addDependencyCollector(ModuleDepCollector);
517 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
518 collectIncludePCH(*this, ModuleDepCollector);
519 collectVFSEntries(*this, ModuleDepCollector);
520 }
521
522 // Modules need an output manager.
523 if (!hasOutputManager())
525
526 for (auto &Listener : DependencyCollectors)
527 Listener->attachToPreprocessor(*PP);
528
529 // Handle generating header include information, if requested.
530 if (DepOpts.ShowHeaderIncludes)
531 AttachHeaderIncludeGen(*PP, DepOpts);
532 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
533 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
534 if (OutputPath == "-")
535 OutputPath = "";
536 AttachHeaderIncludeGen(*PP, DepOpts,
537 /*ShowAllHeaders=*/true, OutputPath,
538 /*ShowDepth=*/false);
539 }
540
542 AttachHeaderIncludeGen(*PP, DepOpts,
543 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
544 /*ShowDepth=*/true, /*MSStyle=*/true);
545 }
546
547 if (GetDependencyDirectives)
548 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
549}
550
551// ASTContext
552
555 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
556 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
557 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
558 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
559 setASTContext(std::move(Context));
560}
561
562// ExternalASTSource
563
564namespace {
565// Helper to recursively read the module names for all modules we're adding.
566// We mark these as known and redirect any attempt to load that module to
567// the files we were handed.
568struct ReadModuleNames : ASTReaderListener {
569 Preprocessor &PP;
571
572 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
573
574 void ReadModuleName(StringRef ModuleName) override {
575 // Keep the module name as a string for now. It's not safe to create a new
576 // IdentifierInfo from an ASTReader callback.
577 LoadedModules.push_back(ModuleName.str());
578 }
579
580 void registerAll() {
581 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
582 for (const std::string &LoadedModule : LoadedModules)
583 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
584 MM.findOrLoadModule(LoadedModule));
585 LoadedModules.clear();
586 }
587
588 void markAllUnavailable() {
589 for (const std::string &LoadedModule : LoadedModules) {
591 LoadedModule)) {
592 M->HasIncompatibleModuleFile = true;
593
594 // Mark module as available if the only reason it was unavailable
595 // was missing headers.
596 SmallVector<Module *, 2> Stack;
597 Stack.push_back(M);
598 while (!Stack.empty()) {
599 Module *Current = Stack.pop_back_val();
600 if (Current->IsUnimportable) continue;
601 Current->IsAvailable = true;
602 auto SubmodulesRange = Current->submodules();
603 llvm::append_range(Stack, SubmodulesRange);
604 }
605 }
606 }
607 LoadedModules.clear();
608 }
609};
610} // namespace
611
613 StringRef Path, DisableValidationForModuleKind DisableValidation,
614 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
615 bool OwnDeserializationListener) {
617 TheASTReader = createPCHExternalASTSource(
618 Path, getHeaderSearchOpts().Sysroot, DisableValidation,
619 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
621 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
622 DeserializationListener, OwnDeserializationListener, Preamble,
623 getFrontendOpts().UseGlobalModuleIndex);
624}
625
627 StringRef Path, StringRef Sysroot,
628 DisableValidationForModuleKind DisableValidation,
629 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
630 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
631 const CodeGenOptions &CodeGenOpts,
632 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
633 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
634 void *DeserializationListener, bool OwnDeserializationListener,
635 bool Preamble, bool UseGlobalModuleIndex) {
636 const HeaderSearchOptions &HSOpts =
637 PP.getHeaderSearchInfo().getHeaderSearchOpts();
638
639 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
640 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
641 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
642 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
645 HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex);
646
647 // We need the external source to be set up before we read the AST, because
648 // eagerly-deserialized declarations may use it.
649 Context.setExternalSource(Reader);
650
651 Reader->setDeserializationListener(
652 static_cast<ASTDeserializationListener *>(DeserializationListener),
653 /*TakeOwnership=*/OwnDeserializationListener);
654
655 for (auto &Listener : DependencyCollectors)
656 Listener->attachToASTReader(*Reader);
657
658 auto Listener = std::make_unique<ReadModuleNames>(PP);
659 auto &ListenerRef = *Listener;
660 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
661 std::move(Listener));
662
663 switch (Reader->ReadAST(ModuleFileName::makeExplicit(Path),
668 // Set the predefines buffer as suggested by the PCH reader. Typically, the
669 // predefines buffer will be empty.
670 PP.setPredefines(Reader->getSuggestedPredefines());
671 ListenerRef.registerAll();
672 return Reader;
673
675 // Unrecoverable failure: don't even try to process the input file.
676 break;
677
683 // No suitable PCH file could be found. Return an error.
684 break;
685 }
686
687 ListenerRef.markAllUnavailable();
688 Context.setExternalSource(nullptr);
689 return nullptr;
690}
691
692// Code Completion
693
695 StringRef Filename,
696 unsigned Line,
697 unsigned Column) {
698 // Tell the source manager to chop off the given file at a specific
699 // line and column.
700 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
701 if (!Entry) {
702 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
703 << Filename;
704 return true;
705 }
706
707 // Truncate the named file at the given line/column.
709 return false;
710}
711
714 if (!CompletionConsumer) {
716 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
717 getFrontendOpts().CodeCompleteOpts, llvm::outs()));
718 return;
720 Loc.Line, Loc.Column)) {
722 return;
723 }
724}
725
727 timerGroup.reset(new llvm::TimerGroup("clang", "Clang time report"));
728 FrontendTimer.reset(new llvm::Timer("frontend", "Front end", *timerGroup));
729}
730
733 StringRef Filename,
734 unsigned Line,
735 unsigned Column,
736 const CodeCompleteOptions &Opts,
737 raw_ostream &OS) {
738 if (EnableCodeCompletion(PP, Filename, Line, Column))
739 return nullptr;
740
741 // Set up the creation routine for code-completion.
742 return new PrintingCodeCompleteConsumer(Opts, OS);
743}
744
746 CodeCompleteConsumer *CompletionConsumer) {
747 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
748 TUKind, CompletionConsumer));
749
750 // Set up API notes.
751 TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
752
753 // Attach the external sema source if there is any.
754 if (ExternalSemaSrc) {
755 TheSema->addExternalSource(ExternalSemaSrc);
756 ExternalSemaSrc->InitializeSema(*TheSema);
757 }
758
759 // If we're building a module and are supposed to load API notes,
760 // notify the API notes manager.
761 if (auto *currentModule = getPreprocessor().getCurrentModule()) {
762 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
763 currentModule, getLangOpts().APINotesModules,
764 getAPINotesOpts().ModuleSearchPaths);
765 }
766}
767
768// Output Files
769
771 // The ASTConsumer can own streams that write to the output files.
772 assert(!hasASTConsumer() && "ASTConsumer should be reset");
773 if (!EraseFiles) {
774 for (auto &O : OutputFiles)
775 llvm::handleAllErrors(
776 O.keep(),
777 [&](const llvm::vfs::TempFileOutputError &E) {
778 getDiagnostics().Report(diag::err_unable_to_rename_temp)
779 << E.getTempPath() << E.getOutputPath()
780 << E.convertToErrorCode().message();
781 },
782 [&](const llvm::vfs::OutputError &E) {
783 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
784 << E.getOutputPath() << E.convertToErrorCode().message();
785 },
786 [&](const llvm::ErrorInfoBase &EIB) { // Handle any remaining error
787 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
788 << O.getPath() << EIB.message();
789 });
790 }
791 OutputFiles.clear();
792 if (DeleteBuiltModules) {
793 for (auto &Module : BuiltModules)
794 llvm::sys::fs::remove(Module.second);
795 BuiltModules.clear();
796 }
797}
798
799std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
800 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
801 bool CreateMissingDirectories, bool ForceUseTemporary) {
802 StringRef OutputPath = getFrontendOpts().OutputFile;
803 std::optional<SmallString<128>> PathStorage;
804 if (OutputPath.empty()) {
805 if (InFile == "-" || Extension.empty()) {
806 OutputPath = "-";
807 } else {
808 PathStorage.emplace(InFile);
809 llvm::sys::path::replace_extension(*PathStorage, Extension);
810 OutputPath = *PathStorage;
811 }
812 }
813
814 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
815 getFrontendOpts().UseTemporary || ForceUseTemporary,
816 CreateMissingDirectories);
817}
818
819std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
820 return std::make_unique<llvm::raw_null_ostream>();
821}
822
823// Output Manager
824
827 assert(!OutputMgr && "Already has an output manager");
828 OutputMgr = std::move(NewOutputs);
829}
830
832 assert(!OutputMgr && "Already has an output manager");
833 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
834}
835
836llvm::vfs::OutputBackend &CompilerInstance::getOutputManager() {
837 assert(OutputMgr);
838 return *OutputMgr;
839}
840
842 if (!hasOutputManager())
844 return getOutputManager();
845}
846
847std::unique_ptr<raw_pwrite_stream>
849 bool RemoveFileOnSignal, bool UseTemporary,
850 bool CreateMissingDirectories) {
852 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
853 CreateMissingDirectories);
854 if (OS)
855 return std::move(*OS);
856 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
857 << OutputPath << errorToErrorCode(OS.takeError()).message();
858 return nullptr;
859}
860
862CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
863 bool RemoveFileOnSignal,
864 bool UseTemporary,
865 bool CreateMissingDirectories) {
866 assert((!CreateMissingDirectories || UseTemporary) &&
867 "CreateMissingDirectories is only allowed when using temporary files");
868
869 // If '-working-directory' was passed, the output filename should be
870 // relative to that.
871 std::optional<SmallString<128>> AbsPath;
872 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
873 assert(hasFileManager() &&
874 "File Manager is required to fix up relative path.\n");
875
876 AbsPath.emplace(OutputPath);
878 OutputPath = *AbsPath;
879 }
880
881 using namespace llvm::vfs;
883 OutputPath,
884 OutputConfig()
885 .setTextWithCRLF(!Binary)
886 .setDiscardOnSignal(RemoveFileOnSignal)
887 .setAtomicWrite(UseTemporary)
888 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
889 if (!O)
890 return O.takeError();
891
892 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
893 OutputFiles.push_back(std::move(*O));
894 return OutputFiles.back().createProxy();
895}
896
897// Initialization Utilities
898
903
904// static
906 DiagnosticsEngine &Diags,
907 FileManager &FileMgr,
908 SourceManager &SourceMgr) {
914
915 if (Input.isBuffer()) {
916 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
917 assert(SourceMgr.getMainFileID().isValid() &&
918 "Couldn't establish MainFileID!");
919 return true;
920 }
921
922 StringRef InputFile = Input.getFile();
923
924 // Figure out where to get and map in the main file.
925 auto FileOrErr = InputFile == "-"
926 ? FileMgr.getSTDIN()
927 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
928 if (!FileOrErr) {
929 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
930 if (InputFile != "-")
931 Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
932 else
933 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
934 return false;
935 }
936
937 SourceMgr.setMainFileID(
938 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
939
940 assert(SourceMgr.getMainFileID().isValid() &&
941 "Couldn't establish MainFileID!");
942 return true;
943}
944
945// High-Level Operations
946
948 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
949 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
950 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
951
952 // Mark this point as the bottom of the stack if we don't have somewhere
953 // better. We generally expect frontend actions to be invoked with (nearly)
954 // DesiredStackSpace available.
956
957 raw_ostream &OS = getVerboseOutputStream();
958
959 if (!Act.PrepareToExecute(*this))
960 return false;
961
962 if (!createTarget())
963 return false;
964
965 // rewriter project will change target built-in bool type from its default.
966 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
968
969 // Validate/process some options.
970 if (getHeaderSearchOpts().Verbose)
971 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
972 << LLVM_VERSION_STRING << " default target "
973 << llvm::sys::getDefaultTargetTriple() << "\n";
974
975 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
976 llvm::EnableStatistics(false);
977
978 // Sort vectors containing toc data and no toc data variables to facilitate
979 // binary search later.
980 llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
981 llvm::sort(getCodeGenOpts().NoTocDataVars);
982
983 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
984 // Reset the ID tables if we are reusing the SourceManager and parsing
985 // regular files.
988
989 if (Act.BeginSourceFile(*this, FIF)) {
990 if (llvm::Error Err = Act.Execute()) {
991 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
992 }
993 Act.EndSourceFile();
994 }
995 }
996
998
999 if (getFrontendOpts().ShowStats) {
1000 if (hasFileManager()) {
1002 OS << '\n';
1003 }
1004 llvm::PrintStatistics(OS);
1005 }
1006 StringRef StatsFile = getFrontendOpts().StatsFile;
1007 if (!StatsFile.empty()) {
1008 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1009 if (getFrontendOpts().AppendStats)
1010 FileFlags |= llvm::sys::fs::OF_Append;
1011 std::error_code EC;
1012 auto StatS =
1013 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1014 if (EC) {
1015 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1016 << StatsFile << EC.message();
1017 } else {
1018 llvm::PrintStatisticsJSON(*StatS);
1019 }
1020 }
1021
1022 return !getDiagnostics().getClient()->getNumErrors();
1023}
1024
1026 if (!getDiagnosticOpts().ShowCarets)
1027 return;
1028
1029 raw_ostream &OS = getVerboseOutputStream();
1030
1031 // We can have multiple diagnostics sharing one diagnostic client.
1032 // Get the total number of warnings/errors from the client.
1033 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1034 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1035
1036 if (NumWarnings)
1037 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1038 if (NumWarnings && NumErrors)
1039 OS << " and ";
1040 if (NumErrors)
1041 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1042 if (NumWarnings || NumErrors) {
1043 OS << " generated";
1044 if (getLangOpts().CUDA) {
1045 if (!getLangOpts().CUDAIsDevice) {
1046 OS << " when compiling for host";
1047 } else {
1048 OS << " when compiling for "
1049 << (!getTargetOpts().CPU.empty() ? getTargetOpts().CPU
1050 : getTarget().getTriple().str());
1051 }
1052 }
1053 OS << ".\n";
1054 }
1055}
1056
1058 // Load any requested plugins.
1059 for (const std::string &Path : getFrontendOpts().Plugins) {
1060 std::string Error;
1061 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1062 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1063 << Path << Error;
1064 }
1065
1066 // Load and store pass plugins for the back-end.
1067 for (const std::string &Path : getCodeGenOpts().PassPlugins) {
1068 if (auto PassPlugin = llvm::PassPlugin::Load(Path)) {
1069 PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
1070 } else {
1071 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1072 << Path << toString(PassPlugin.takeError());
1073 }
1074 }
1075
1076 // Check if any of the loaded plugins replaces the main AST action
1077 for (const FrontendPluginRegistry::entry &Plugin :
1078 FrontendPluginRegistry::entries()) {
1079 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1080 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1082 getFrontendOpts().ActionName = Plugin.getName().str();
1083 break;
1084 }
1085 }
1086}
1087
1088/// Determine the appropriate source input kind based on language
1089/// options.
1091 if (LangOpts.OpenCL)
1092 return Language::OpenCL;
1093 if (LangOpts.CUDA)
1094 return Language::CUDA;
1095 if (LangOpts.ObjC)
1096 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1097 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1098}
1099
1100std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1101 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
1102 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1103 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1104 // Construct a compiler invocation for creating this module.
1105 auto Invocation = std::make_shared<CompilerInvocation>(getInvocation());
1106
1107 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1108
1109 // For any options that aren't intended to affect how a module is built,
1110 // reset them to their default values.
1111 Invocation->resetNonModularOptions();
1112
1113 // Remove any macro definitions that are explicitly ignored by the module.
1114 // They aren't supposed to affect how the module is built anyway.
1115 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1116 llvm::erase_if(PPOpts.Macros,
1117 [&HSOpts](const std::pair<std::string, bool> &def) {
1118 StringRef MacroDef = def.first;
1119 return HSOpts.ModulesIgnoreMacros.contains(
1120 llvm::CachedHashString(MacroDef.split('=').first));
1121 });
1122
1123 // If the original compiler invocation had -fmodule-name, pass it through.
1124 Invocation->getLangOpts().ModuleName =
1126
1127 // Note the name of the module we're building.
1128 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1129
1130 // If there is a module map file, build the module using the module map.
1131 // Set up the inputs/outputs so that we build the module from its umbrella
1132 // header.
1133 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1134 FrontendOpts.OutputFile = ModuleFileName.str();
1135 FrontendOpts.DisableFree = false;
1136 FrontendOpts.GenerateGlobalModuleIndex = false;
1137 FrontendOpts.BuildingImplicitModule = true;
1138 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1139 // Force implicitly-built modules to hash the content of the module file.
1140 HSOpts.ModulesHashContent = true;
1141 FrontendOpts.Inputs = {std::move(Input)};
1142
1143 // Don't free the remapped file buffers; they are owned by our caller.
1144 PPOpts.RetainRemappedFileBuffers = true;
1145
1146 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1147
1148 DiagOpts.VerifyDiagnostics = 0;
1149 assert(getInvocation().computeContextHash() ==
1150 Invocation->computeContextHash() &&
1151 "Module hash mismatch!");
1152
1153 std::shared_ptr<ModuleCache> ModCache;
1154 if (ThreadSafeConfig) {
1155 ModCache = ThreadSafeConfig->getModuleCache();
1156 } else {
1157 ModCache = this->ModCache;
1158 }
1159
1160 // Construct a compiler instance that will be used to create the module.
1161 auto InstancePtr = std::make_unique<CompilerInstance>(
1162 std::move(Invocation), getPCHContainerOperations(), std::move(ModCache));
1163 auto &Instance = *InstancePtr;
1164
1165 auto &Inv = Instance.getInvocation();
1166
1167 if (ThreadSafeConfig) {
1168 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1169 Instance.createFileManager();
1170 } else if (FrontendOpts.ModulesShareFileManager) {
1171 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1172 Instance.setFileManager(getFileManagerPtr());
1173 } else {
1174 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1175 Instance.createFileManager();
1176 }
1177
1178 if (ThreadSafeConfig) {
1179 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1180 /*ShouldOwnClient=*/false);
1181 } else {
1182 Instance.createDiagnostics(
1183 new ForwardingDiagnosticConsumer(getDiagnosticClient()),
1184 /*ShouldOwnClient=*/true);
1185 }
1186 if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1187 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1188
1189 Instance.createSourceManager();
1190 SourceManager &SourceMgr = Instance.getSourceManager();
1191
1192 if (ThreadSafeConfig) {
1193 // Detecting cycles in the module graph is responsibility of the client.
1194 } else {
1195 // Note that this module is part of the module build stack, so that we
1196 // can detect cycles in the module graph.
1197 SourceMgr.setModuleBuildStack(getSourceManager().getModuleBuildStack());
1198 SourceMgr.pushModuleBuildStack(
1199 ModuleName, FullSourceLoc(ImportLoc, getSourceManager()));
1200 }
1201
1202 // Make a copy for the new instance.
1203 Instance.FailedModules = FailedModules;
1204
1205 // Pass along the GenModuleActionWrapper callback.
1206 Instance.setGenModuleActionWrapper(getGenModuleActionWrapper());
1207
1208 if (GetDependencyDirectives)
1209 Instance.GetDependencyDirectives =
1210 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1211
1212 if (ThreadSafeConfig) {
1213 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1214 } else {
1215 // If we're collecting module dependencies, we need to share a collector
1216 // between all of the module CompilerInstances. Other than that, we don't
1217 // want to produce any dependency output from the module build.
1218 Instance.setModuleDepCollector(getModuleDepCollector());
1219 }
1220 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1221
1222 return InstancePtr;
1223}
1224
1225namespace {
1226class PrettyStackTraceBuildModule : public llvm::PrettyStackTraceEntry {
1227 StringRef ModuleName;
1228 StringRef ModuleFileName;
1229
1230public:
1231 PrettyStackTraceBuildModule(StringRef ModuleName, StringRef ModuleFileName)
1232 : ModuleName(ModuleName), ModuleFileName(ModuleFileName) {}
1233 void print(raw_ostream &OS) const override {
1234 OS << "Building module '" << ModuleName << "' as '" << ModuleFileName
1235 << "'\n";
1236 }
1237};
1238} // namespace
1239
1240std::unique_ptr<llvm::MemoryBuffer>
1241CompilerInstance::compileModule(SourceLocation ImportLoc, StringRef ModuleName,
1242 StringRef ModuleFileName,
1243 CompilerInstance &Instance) {
1244 PrettyStackTraceBuildModule CrashInfo(ModuleName, ModuleFileName);
1245 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1246
1247 // Never compile a module that's already finalized - this would cause the
1248 // existing module to be freed, causing crashes if it is later referenced
1249 if (getModuleCache().getInMemoryModuleCache().isPCMFinal(ModuleFileName)) {
1250 getDiagnostics().Report(ImportLoc, diag::err_module_rebuild_finalized)
1251 << ModuleName;
1252 return nullptr;
1253 }
1254
1255 getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1256 << ModuleName << ModuleFileName;
1257
1258 SmallString<0> Buffer;
1259
1260 // Execute the action to actually build the module in-place. Use a separate
1261 // thread so that we get a stack large enough.
1262 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1263 [&]() {
1264 auto OS = std::make_unique<llvm::raw_svector_ostream>(Buffer);
1265
1266 std::unique_ptr<FrontendAction> Action =
1267 std::make_unique<GenerateModuleFromModuleMapAction>(std::move(OS));
1268
1269 if (auto WrapGenModuleAction = Instance.getGenModuleActionWrapper())
1270 Action = WrapGenModuleAction(Instance.getFrontendOpts(),
1271 std::move(Action));
1272
1273 Instance.ExecuteAction(*Action);
1274 },
1276
1277 getDiagnostics().Report(ImportLoc, diag::remark_module_build_done)
1278 << ModuleName;
1279
1280 // Propagate the statistics to the parent FileManager.
1281 if (!getFrontendOpts().ModulesShareFileManager)
1282 getFileManager().AddStats(Instance.getFileManager());
1283
1284 // Propagate the failed modules to the parent instance.
1285 FailedModules = std::move(Instance.FailedModules);
1286
1287 if (Crashed) {
1288 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1289 // that must be closed before clearing output files.
1290 Instance.setSema(nullptr);
1291 Instance.setASTConsumer(nullptr);
1292
1293 // Delete any remaining temporary files related to Instance.
1294 Instance.clearOutputFiles(/*EraseFiles=*/true);
1295 }
1296
1297 // We've rebuilt a module. If we're allowed to generate or update the global
1298 // module index, record that fact in the importing compiler instance.
1299 if (getFrontendOpts().GenerateGlobalModuleIndex) {
1301 }
1302
1303 if (Crashed)
1304 return nullptr;
1305
1306 // Unless \p AllowPCMWithCompilerErrors is set, return 'failure' if errors
1307 // occurred.
1308 if (Instance.getDiagnostics().hasErrorOccurred() &&
1309 !Instance.getFrontendOpts().AllowPCMWithCompilerErrors)
1310 return nullptr;
1311
1312 return std::make_unique<llvm::SmallVectorMemoryBuffer>(
1313 std::move(Buffer), Instance.getFrontendOpts().OutputFile);
1314}
1315
1318 StringRef Filename = llvm::sys::path::filename(File.getName());
1319 SmallString<128> PublicFilename(File.getDir().getName());
1320 if (Filename == "module_private.map")
1321 llvm::sys::path::append(PublicFilename, "module.map");
1322 else if (Filename == "module.private.modulemap")
1323 llvm::sys::path::append(PublicFilename, "module.modulemap");
1324 else
1325 return std::nullopt;
1326 return FileMgr.getOptionalFileRef(PublicFilename);
1327}
1328
1329std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompile(
1330 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
1331 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1332 StringRef ModuleName = Module->getTopLevelModuleName();
1333
1335
1336 // Get or create the module map that we'll use to build this module.
1338 SourceManager &SourceMgr = getSourceManager();
1339
1340 if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1341 ModuleMapFID.isValid()) {
1342 // We want to use the top-level module map. If we don't, the compiling
1343 // instance may think the containing module map is a top-level one, while
1344 // the importing instance knows it's included from a parent module map via
1345 // the extern directive. This mismatch could bite us later.
1346 SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1347 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1348 ModuleMapFID = SourceMgr.getFileID(Loc);
1349 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1350 }
1351
1352 OptionalFileEntryRef ModuleMapFile =
1353 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1354 assert(ModuleMapFile && "Top-level module map with no FileID");
1355
1356 // Canonicalize compilation to start with the public module map. This is
1357 // vital for submodules declarations in the private module maps to be
1358 // correctly parsed when depending on a top level module in the public one.
1359 if (OptionalFileEntryRef PublicMMFile =
1360 getPublicModuleMap(*ModuleMapFile, getFileManager()))
1361 ModuleMapFile = PublicMMFile;
1362
1363 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1364
1365 // Use the systemness of the module map as parsed instead of using the
1366 // IsSystem attribute of the module. If the module has [system] but the
1367 // module map is not in a system path, then this would incorrectly parse
1368 // any other modules in that module map as system too.
1369 const SrcMgr::SLocEntry &SLoc = SourceMgr.getSLocEntry(ModuleMapFID);
1370 bool IsSystem = isSystem(SLoc.getFile().getFileCharacteristic());
1371
1372 // Use the module map where this module resides.
1373 return cloneForModuleCompileImpl(
1374 ImportLoc, ModuleName,
1375 FrontendInputFile(ModuleMapFilePath, IK, IsSystem),
1377 std::move(ThreadSafeConfig));
1378 }
1379
1380 // FIXME: We only need to fake up an input file here as a way of
1381 // transporting the module's directory to the module map parser. We should
1382 // be able to do that more directly, and parse from a memory buffer without
1383 // inventing this file.
1384 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1385 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1386
1387 std::string InferredModuleMapContent;
1388 llvm::raw_string_ostream OS(InferredModuleMapContent);
1389 Module->print(OS);
1390
1391 auto Instance = cloneForModuleCompileImpl(
1392 ImportLoc, ModuleName,
1393 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1395 std::move(ThreadSafeConfig));
1396
1397 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1398 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1399 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1400 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1401 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1402 std::move(ModuleMapBuffer));
1403
1404 return Instance;
1405}
1406
1407/// Read the AST right after compiling the module.
1408/// Returns true on success, false on failure.
1409static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1410 SourceLocation ImportLoc,
1412 Module *Module,
1414 bool *OutOfDate, bool *Missing) {
1415 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1416
1417 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1418 if (OutOfDate)
1419 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1420
1421 // Try to read the module file, now that we've compiled it.
1422 ASTReader::ASTReadResult ReadResult =
1423 ImportingInstance.getASTReader()->ReadAST(
1425 ModuleLoadCapabilities);
1426 if (ReadResult == ASTReader::Success)
1427 return true;
1428
1429 // The caller wants to handle out-of-date failures.
1430 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1431 *OutOfDate = true;
1432 return false;
1433 }
1434
1435 // The caller wants to handle missing module files.
1436 if (Missing && ReadResult == ASTReader::Missing) {
1437 *Missing = true;
1438 return false;
1439 }
1440
1441 // The ASTReader didn't diagnose the error, so conservatively report it.
1442 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1443 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1444 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1445
1446 return false;
1447}
1448
1449/// Compile a module in a separate compiler instance.
1450/// Returns true on success, false on failure.
1451static bool compileModuleImpl(CompilerInstance &ImportingInstance,
1452 SourceLocation ImportLoc,
1455 std::unique_ptr<llvm::MemoryBuffer> Buffer;
1456
1457 {
1458 auto Instance = ImportingInstance.cloneForModuleCompile(
1460
1461 Buffer = ImportingInstance.compileModule(ModuleNameLoc,
1463 ModuleFileName, *Instance);
1464
1465 if (!Buffer) {
1466 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1467 diag::err_module_not_built)
1468 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1469 return false;
1470 }
1471 }
1472
1473 std::error_code EC =
1474 ImportingInstance.getModuleCache().write(ModuleFileName, *Buffer);
1475 if (EC) {
1476 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1477 diag::err_module_not_written)
1478 << Module->Name << ModuleFileName << EC.message()
1479 << SourceRange(ImportLoc, ModuleNameLoc);
1480 return false;
1481 }
1482
1483 // The module is built successfully, we can update its timestamp now.
1484 if (ImportingInstance.getPreprocessor()
1489 }
1490
1491 // This isn't strictly necessary, but it's more efficient to extract the AST
1492 // file (which may be wrapped in an object file) now rather than doing so
1493 // repeatedly in the readers.
1494 const PCHContainerReader &Rdr = ImportingInstance.getPCHContainerReader();
1495 StringRef ExtractedBuffer = Rdr.ExtractPCH(*Buffer);
1496 // FIXME: Avoid the copy here by having InMemoryModuleCache accept both the
1497 // owning buffer and the StringRef.
1498 Buffer = llvm::MemoryBuffer::getMemBufferCopy(ExtractedBuffer);
1499
1501 ModuleFileName, std::move(Buffer));
1502
1503 return true;
1504}
1505
1506/// The result of `compileModuleBehindLockOrRead()`.
1507enum class CompileOrReadResult : uint8_t {
1508 /// We failed to compile the module.
1510 /// We successfully compiled the module and we still need to read it.
1512 /// We failed to read the module file compiled by another instance.
1514 /// We read a module file compiled by another instance.
1516};
1517
1518/// Attempt to compile the module in a separate compiler instance behind a lock
1519/// (to avoid building the same module in multiple compiler instances), or read
1520/// the AST produced by another compiler instance.
1523 SourceLocation ImportLoc,
1526 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1527
1528 Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1529 << ModuleFileName << Module->Name;
1530
1531 auto &ModuleCache = ImportingInstance.getModuleCache();
1532
1533 while (true) {
1534 auto Lock = ModuleCache.getLock(ModuleFileName);
1535 bool Owned;
1536 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1537 // ModuleCache takes care of correctness and locks are only necessary for
1538 // performance. Fallback to building the module in case of any lock
1539 // related errors.
1540 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1541 << Module->Name << toString(std::move(Err));
1542 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc,
1546 }
1547 if (Owned) {
1548 // We're responsible for building the module ourselves.
1549 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc,
1553 }
1554
1555 // Someone else is responsible for building the module. Wait for them to
1556 // finish.
1557 unsigned Timeout =
1559 switch (Lock->waitForUnlockFor(std::chrono::seconds(Timeout))) {
1560 case llvm::WaitForUnlockResult::Success:
1561 break; // The interesting case.
1562 case llvm::WaitForUnlockResult::OwnerDied:
1563 continue; // try again to get the lock.
1564 case llvm::WaitForUnlockResult::Timeout:
1565 // Since the InMemoryModuleCache takes care of correctness, we try waiting
1566 // for someone else to complete the build so that it does not happen
1567 // twice. In case of timeout, try to build it ourselves again.
1568 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1569 << Module->Name;
1570 // Clear the lock file so that future invocations can make progress.
1571 Lock->unsafeUnlock();
1572 continue;
1573 }
1574
1575 // Read the module that was just written by someone else.
1576 bool OutOfDate = false;
1577 bool Missing = false;
1578 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1579 Module, ModuleFileName, &OutOfDate, &Missing))
1581 if (!OutOfDate && !Missing)
1583
1584 // The module may be missing or out of date in the presence of file system
1585 // races. It may also be out of date if one of its imports depends on header
1586 // search paths that are not consistent with this ImportingInstance.
1587 // Try again...
1588 }
1589}
1590
1591/// Compile a module in a separate compiler instance and read the AST,
1592/// returning true if the module compiles without errors, potentially using a
1593/// lock manager to avoid building the same module in multiple compiler
1594/// instances.
1595static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1596 SourceLocation ImportLoc,
1598 Module *Module,
1600 if (ImportingInstance.getInvocation()
1604 ImportingInstance, ImportLoc, ModuleNameLoc, Module, ModuleFileName)) {
1607 return false;
1609 return true;
1611 // We successfully compiled the module under a lock. Let's read it from
1612 // the in-memory module cache now.
1613 break;
1614 }
1615 } else {
1616 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc, Module,
1618 return false;
1619 }
1620
1621 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1623 /*OutOfDate=*/nullptr, /*Missing=*/nullptr);
1624}
1625
1626/// Diagnose differences between the current definition of the given
1627/// configuration macro and the definition provided on the command line.
1628static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1629 Module *Mod, SourceLocation ImportLoc) {
1630 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1631 SourceManager &SourceMgr = PP.getSourceManager();
1632
1633 // If this identifier has never had a macro definition, then it could
1634 // not have changed.
1635 if (!Id->hadMacroDefinition())
1636 return;
1637 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1638
1639 // Find the macro definition from the command line.
1640 MacroInfo *CmdLineDefinition = nullptr;
1641 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1642 SourceLocation MDLoc = MD->getLocation();
1643 FileID FID = SourceMgr.getFileID(MDLoc);
1644 if (FID.isInvalid())
1645 continue;
1646 // We only care about the predefines buffer, or if the macro is defined
1647 // over the command line transitively through a PCH.
1648 if (FID != PP.getPredefinesFileID() &&
1649 !SourceMgr.isWrittenInCommandLineFile(MDLoc))
1650 continue;
1651 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1652 CmdLineDefinition = DMD->getMacroInfo();
1653 break;
1654 }
1655
1656 auto *CurrentDefinition = PP.getMacroInfo(Id);
1657 if (CurrentDefinition == CmdLineDefinition) {
1658 // Macro matches. Nothing to do.
1659 } else if (!CurrentDefinition) {
1660 // This macro was defined on the command line, then #undef'd later.
1661 // Complain.
1662 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1663 << true << ConfigMacro << Mod->getFullModuleName();
1664 auto LatestDef = LatestLocalMD->getDefinition();
1665 assert(LatestDef.isUndefined() &&
1666 "predefined macro went away with no #undef?");
1667 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1668 << true;
1669 return;
1670 } else if (!CmdLineDefinition) {
1671 // There was no definition for this macro in the command line,
1672 // but there was a local definition. Complain.
1673 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1674 << false << ConfigMacro << Mod->getFullModuleName();
1675 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1676 diag::note_module_def_undef_here)
1677 << false;
1678 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1679 /*Syntactically=*/true)) {
1680 // The macro definitions differ.
1681 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1682 << false << ConfigMacro << Mod->getFullModuleName();
1683 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1684 diag::note_module_def_undef_here)
1685 << false;
1686 }
1687}
1688
1690 SourceLocation ImportLoc) {
1691 clang::Module *TopModule = M->getTopLevelModule();
1692 for (const StringRef ConMacro : TopModule->ConfigMacros) {
1693 checkConfigMacro(PP, ConMacro, M, ImportLoc);
1694 }
1695}
1696
1698 if (TheASTReader)
1699 return;
1700
1701 if (!hasASTContext())
1703
1704 // If we're implicitly building modules but not currently recursively
1705 // building a module, check whether we need to prune the module cache.
1706 if (getSourceManager().getModuleBuildStack().empty() &&
1708 .getHeaderSearchInfo()
1709 .getSpecificModuleCachePath()
1710 .empty())
1711 ModCache->maybePrune(getHeaderSearchOpts().ModuleCachePath,
1712 getHeaderSearchOpts().ModuleCachePruneInterval,
1713 getHeaderSearchOpts().ModuleCachePruneAfter);
1714
1716 std::string Sysroot = HSOpts.Sysroot;
1717 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1718 const FrontendOptions &FEOpts = getFrontendOpts();
1719 std::unique_ptr<llvm::Timer> ReadTimer;
1720
1721 if (timerGroup)
1722 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1723 "Reading modules", *timerGroup);
1724 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1727 getFrontendOpts().ModuleFileExtensions,
1728 Sysroot.empty() ? "" : Sysroot.c_str(),
1730 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1731 /*AllowConfigurationMismatch=*/false,
1735 +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1736 if (hasASTConsumer()) {
1737 TheASTReader->setDeserializationListener(
1738 getASTConsumer().GetASTDeserializationListener());
1740 getASTConsumer().GetASTMutationListener());
1741 }
1742 getASTContext().setExternalSource(TheASTReader);
1743 if (hasSema())
1744 TheASTReader->InitializeSema(getSema());
1745 if (hasASTConsumer())
1746 TheASTReader->StartTranslationUnit(&getASTConsumer());
1747
1748 for (auto &Listener : DependencyCollectors)
1749 Listener->attachToASTReader(*TheASTReader);
1750}
1751
1754 llvm::Timer Timer;
1755 if (timerGroup)
1756 Timer.init("preloading." + std::string(FileName.str()),
1757 "Preloading " + std::string(FileName.str()), *timerGroup);
1758 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1759
1760 // If we don't already have an ASTReader, create one now.
1761 if (!TheASTReader)
1763
1764 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1765 // ASTReader to diagnose it, since it can produce better errors that we can.
1766 bool ConfigMismatchIsRecoverable =
1767 getDiagnostics().getDiagnosticLevel(diag::warn_ast_file_config_mismatch,
1768 SourceLocation()) <=
1770
1771 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1772 auto &ListenerRef = *Listener;
1773 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1774 std::move(Listener));
1775
1776 // Try to load the module file.
1777 switch (TheASTReader->ReadAST(
1779 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1780 &LoadedModuleFile)) {
1781 case ASTReader::Success:
1782 // We successfully loaded the module file; remember the set of provided
1783 // modules so that we don't try to load implicit modules for them.
1784 ListenerRef.registerAll();
1785 return true;
1786
1788 // Ignore unusable module files.
1790 diag::warn_ast_file_config_mismatch)
1791 << FileName;
1792 // All modules provided by any files we tried and failed to load are now
1793 // unavailable; includes of those modules should now be handled textually.
1794 ListenerRef.markAllUnavailable();
1795 return true;
1796
1797 default:
1798 return false;
1799 }
1800}
1801
1802namespace {
1803enum ModuleSource {
1804 MS_ModuleNotFound,
1805 MS_ModuleCache,
1806 MS_PrebuiltModulePath,
1807 MS_ModuleBuildPragma
1808};
1809} // end namespace
1810
1811/// Select a source for loading the named module and compute the filename to
1812/// load it from.
1813static ModuleSource selectModuleSource(
1814 Module *M, StringRef ModuleName, ModuleFileName &ModuleFilename,
1815 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1816 HeaderSearch &HS) {
1817 assert(ModuleFilename.empty() && "Already has a module source?");
1818
1819 // Check to see if the module has been built as part of this compilation
1820 // via a module build pragma.
1821 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1822 if (BuiltModuleIt != BuiltModules.end()) {
1823 ModuleFilename = ModuleFileName::makeExplicit(BuiltModuleIt->second);
1824 return MS_ModuleBuildPragma;
1825 }
1826
1827 // Try to load the module from the prebuilt module path.
1828 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1829 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1830 !HSOpts.PrebuiltModulePaths.empty()) {
1831 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1832 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1833 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1834 if (!ModuleFilename.empty())
1835 return MS_PrebuiltModulePath;
1836 }
1837
1838 // Try to load the module from the module cache.
1839 if (M) {
1840 ModuleFilename = HS.getCachedModuleFileName(M);
1841 return MS_ModuleCache;
1842 }
1843
1844 return MS_ModuleNotFound;
1845}
1846
1847ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1848 StringRef ModuleName, SourceLocation ImportLoc, SourceRange ModuleNameRange,
1849 bool IsInclusionDirective) {
1850 // Search for a module with the given name.
1851 HeaderSearch &HS = PP->getHeaderSearchInfo();
1852 Module *M =
1853 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1854
1855 // Check for any configuration macros that have changed. This is done
1856 // immediately before potentially building a module in case this module
1857 // depends on having one of its configuration macros defined to successfully
1858 // build. If this is not done the user will never see the warning.
1859 if (M)
1860 checkConfigMacros(getPreprocessor(), M, ImportLoc);
1861
1862 // Select the source and filename for loading the named module.
1863 ModuleFileName ModuleFilename;
1864 ModuleSource Source =
1865 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1866 SourceLocation ModuleNameLoc = ModuleNameRange.getBegin();
1867 if (Source == MS_ModuleNotFound) {
1868 // We can't find a module, error out here.
1869 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1870 << ModuleName << ModuleNameRange;
1871 return nullptr;
1872 }
1873 if (ModuleFilename.empty()) {
1874 if (M && M->HasIncompatibleModuleFile) {
1875 // We tried and failed to load a module file for this module. Fall
1876 // back to textual inclusion for its headers.
1878 }
1879
1880 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1881 << ModuleName;
1882 return nullptr;
1883 }
1884
1885 // Create an ASTReader on demand.
1886 if (!getASTReader())
1888
1889 // Time how long it takes to load the module.
1890 llvm::Timer Timer;
1891 if (timerGroup)
1892 Timer.init("loading." + std::string(ModuleFilename.str()),
1893 "Loading " + std::string(ModuleFilename.str()), *timerGroup);
1894 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1895 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1896
1897 // Try to load the module file. If we are not trying to load from the
1898 // module cache, we don't know how to rebuild modules.
1899 unsigned ARRFlags = Source == MS_ModuleCache
1902 : Source == MS_PrebuiltModulePath
1903 ? 0
1905 switch (getASTReader()->ReadAST(ModuleFilename,
1906 Source == MS_PrebuiltModulePath
1908 : Source == MS_ModuleBuildPragma
1911 ImportLoc, ARRFlags)) {
1912 case ASTReader::Success: {
1913 if (M)
1914 return M;
1915 assert(Source != MS_ModuleCache &&
1916 "missing module, but file loaded from cache");
1917
1918 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1919 // until the first call to ReadAST. Look it up now.
1920 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1921
1922 // Check whether M refers to the file in the prebuilt module path.
1923 if (M && M->getASTFileKey() &&
1924 *M->getASTFileKey() == ModuleFilename.makeKey(*FileMgr))
1925 return M;
1926
1927 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1928 << ModuleName;
1929 return ModuleLoadResult();
1930 }
1931
1933 case ASTReader::Missing:
1934 // The most interesting case.
1935 break;
1936
1938 if (Source == MS_PrebuiltModulePath)
1939 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1940 // produce a warning here!
1941 getDiagnostics().Report(SourceLocation(),
1942 diag::warn_ast_file_config_mismatch)
1943 << ModuleFilename;
1944 // Fall through to error out.
1945 [[fallthrough]];
1949 // FIXME: The ASTReader will already have complained, but can we shoehorn
1950 // that diagnostic information into a more useful form?
1951 return ModuleLoadResult();
1952
1953 case ASTReader::Failure:
1955 return ModuleLoadResult();
1956 }
1957
1958 // ReadAST returned Missing or OutOfDate.
1959 if (Source != MS_ModuleCache) {
1960 // We don't know the desired configuration for this module and don't
1961 // necessarily even have a module map. Since ReadAST already produces
1962 // diagnostics for these two cases, we simply error out here.
1963 return ModuleLoadResult();
1964 }
1965
1966 // The module file is missing or out-of-date. Build it.
1967 assert(M && "missing module, but trying to compile for cache");
1968
1969 // Check whether there is a cycle in the module graph.
1971 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1972 for (; Pos != PosEnd; ++Pos) {
1973 if (Pos->first == ModuleName)
1974 break;
1975 }
1976
1977 if (Pos != PosEnd) {
1978 SmallString<256> CyclePath;
1979 for (; Pos != PosEnd; ++Pos) {
1980 CyclePath += Pos->first;
1981 CyclePath += " -> ";
1982 }
1983 CyclePath += ModuleName;
1984
1985 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1986 << ModuleName << CyclePath;
1987 return nullptr;
1988 }
1989
1990 // Check whether we have already attempted to build this module (but failed).
1991 if (FailedModules.contains(ModuleName)) {
1992 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1993 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1994 return nullptr;
1995 }
1996
1997 // Try to compile and then read the AST.
1998 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1999 ModuleFilename)) {
2000 assert(getDiagnostics().hasErrorOccurred() &&
2001 "undiagnosed error in compileModuleAndReadAST");
2002 FailedModules.insert(ModuleName);
2003 return nullptr;
2004 }
2005
2006 // Okay, we've rebuilt and now loaded the module.
2007 return M;
2008}
2009
2012 ModuleIdPath Path,
2014 bool IsInclusionDirective) {
2015 // Determine what file we're searching from.
2016 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
2017 SourceLocation ModuleNameLoc = Path[0].getLoc();
2018
2019 // If we've already handled this import, just return the cached result.
2020 // This one-element cache is important to eliminate redundant diagnostics
2021 // when both the preprocessor and parser see the same import declaration.
2022 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
2023 // Make the named module visible.
2024 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
2025 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
2026 ImportLoc);
2027 return LastModuleImportResult;
2028 }
2029
2030 // If we don't already have information on this module, load the module now.
2031 Module *Module = nullptr;
2033 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].getIdentifierInfo())) {
2034 // Use the cached result, which may be nullptr.
2035 Module = *MaybeModule;
2036 // Config macros are already checked before building a module, but they need
2037 // to be checked at each import location in case any of the config macros
2038 // have a new value at the current `ImportLoc`.
2039 if (Module)
2041 } else if (ModuleName == getLangOpts().CurrentModule) {
2042 // This is the module we're building.
2043 Module = PP->getHeaderSearchInfo().lookupModule(
2044 ModuleName, ImportLoc, /*AllowSearch*/ true,
2045 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
2046
2047 // Config macros do not need to be checked here for two reasons.
2048 // * This will always be textual inclusion, and thus the config macros
2049 // actually do impact the content of the header.
2050 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
2051 // function as the `#include` or `#import` is textual.
2052
2053 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2054 } else if (getPreprocessorOpts().SingleModuleParseMode) {
2055 // This mimics how findOrCompileModuleAndReadAST() finds the module.
2057 ModuleName, ImportLoc, true, !IsInclusionDirective);
2058 if (Module) {
2059 if (PPCallbacks *PPCb = getPreprocessor().getPPCallbacks())
2060 PPCb->moduleLoadSkipped(Module);
2061 // Mark the module and its submodules as if they were loaded from a PCM.
2062 // This prevents emission of the "missing submodule" diagnostic below.
2063 std::vector<clang::Module *> Worklist{Module};
2064 while (!Worklist.empty()) {
2065 clang::Module *M = Worklist.back();
2066 Worklist.pop_back();
2067 M->IsFromModuleFile = true;
2068 for (auto *SubM : M->submodules())
2069 Worklist.push_back(SubM);
2070 }
2071 }
2072 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2073 } else {
2074 SourceLocation ModuleNameEndLoc = Path.back().getLoc().getLocWithOffset(
2075 Path.back().getIdentifierInfo()->getLength());
2076 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
2077 ModuleName, ImportLoc, SourceRange{ModuleNameLoc, ModuleNameEndLoc},
2078 IsInclusionDirective);
2079 if (!Result.isNormal())
2080 return Result;
2081 if (!Result)
2082 DisableGeneratingGlobalModuleIndex = true;
2083 Module = Result;
2084 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2085 }
2086
2087 // If we never found the module, fail. Otherwise, verify the module and link
2088 // it up.
2089 if (!Module)
2090 return ModuleLoadResult();
2091
2092 // Verify that the rest of the module path actually corresponds to
2093 // a submodule.
2094 bool MapPrivateSubModToTopLevel = false;
2095 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2096 StringRef Name = Path[I].getIdentifierInfo()->getName();
2097 clang::Module *Sub = Module->findSubmodule(Name);
2098
2099 // If the user is requesting Foo.Private and it doesn't exist, try to
2100 // match Foo_Private and emit a warning asking for the user to write
2101 // @import Foo_Private instead. FIXME: remove this when existing clients
2102 // migrate off of Foo.Private syntax.
2103 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2104 SmallString<128> PrivateModule(Module->Name);
2105 PrivateModule.append("_Private");
2106
2108 auto &II = PP->getIdentifierTable().get(
2109 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2110 PrivPath.emplace_back(Path[0].getLoc(), &II);
2111
2113 // If there is a modulemap module or prebuilt module, load it.
2114 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2115 !IsInclusionDirective) ||
2116 selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2117 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2118 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2119 if (Sub) {
2120 MapPrivateSubModToTopLevel = true;
2121 PP->markClangModuleAsAffecting(Module);
2122 if (!getDiagnostics().isIgnored(
2123 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2124 getDiagnostics().Report(Path[I].getLoc(),
2125 diag::warn_no_priv_submodule_use_toplevel)
2126 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2127 << PrivateModule
2128 << SourceRange(Path[0].getLoc(), Path[I].getLoc())
2129 << FixItHint::CreateReplacement(SourceRange(Path[0].getLoc()),
2130 PrivateModule);
2131 getDiagnostics().Report(Sub->DefinitionLoc,
2132 diag::note_private_top_level_defined);
2133 }
2134 }
2135 }
2136
2137 if (!Sub) {
2138 // Attempt to perform typo correction to find a module name that works.
2140 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2141
2142 for (class Module *SubModule : Module->submodules()) {
2143 unsigned ED =
2144 Name.edit_distance(SubModule->Name,
2145 /*AllowReplacements=*/true, BestEditDistance);
2146 if (ED <= BestEditDistance) {
2147 if (ED < BestEditDistance) {
2148 Best.clear();
2149 BestEditDistance = ED;
2150 }
2151
2152 Best.push_back(SubModule->Name);
2153 }
2154 }
2155
2156 // If there was a clear winner, user it.
2157 if (Best.size() == 1) {
2158 getDiagnostics().Report(Path[I].getLoc(),
2159 diag::err_no_submodule_suggest)
2160 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2161 << Best[0] << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2162 << FixItHint::CreateReplacement(SourceRange(Path[I].getLoc()),
2163 Best[0]);
2164
2165 Sub = Module->findSubmodule(Best[0]);
2166 }
2167 }
2168
2169 if (!Sub) {
2170 // No submodule by this name. Complain, and don't look for further
2171 // submodules.
2172 getDiagnostics().Report(Path[I].getLoc(), diag::err_no_submodule)
2173 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2174 << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2175 break;
2176 }
2177
2178 Module = Sub;
2179 }
2180
2181 // Make the named module visible, if it's not already part of the module
2182 // we are parsing.
2183 if (ModuleName != getLangOpts().CurrentModule) {
2184 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2185 // We have an umbrella header or directory that doesn't actually include
2186 // all of the headers within the directory it covers. Complain about
2187 // this missing submodule and recover by forgetting that we ever saw
2188 // this submodule.
2189 // FIXME: Should we detect this at module load time? It seems fairly
2190 // expensive (and rare).
2191 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2193 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2194
2196 }
2197
2198 // Check whether this module is available.
2200 *Module, getDiagnostics())) {
2201 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2202 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2203 LastModuleImportLoc = ImportLoc;
2204 LastModuleImportResult = ModuleLoadResult();
2205 return ModuleLoadResult();
2206 }
2207
2208 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2209 }
2210
2211 // Resolve any remaining module using export_as for this one.
2214 .getModuleMap()
2216
2217 LastModuleImportLoc = ImportLoc;
2218 LastModuleImportResult = ModuleLoadResult(Module);
2219 return LastModuleImportResult;
2220}
2221
2223 StringRef ModuleName,
2224 StringRef Source) {
2225 // Avoid creating filenames with special characters.
2226 SmallString<128> CleanModuleName(ModuleName);
2227 for (auto &C : CleanModuleName)
2228 if (!isAlphanumeric(C))
2229 C = '_';
2230
2231 // FIXME: Using a randomized filename here means that our intermediate .pcm
2232 // output is nondeterministic (as .pcm files refer to each other by name).
2233 // Can this affect the output in any way?
2235 int FD;
2236 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2237 CleanModuleName, "pcm", FD, ModuleFileName)) {
2238 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2239 << ModuleFileName << EC.message();
2240 return;
2241 }
2242 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2243
2244 FrontendInputFile Input(
2245 ModuleMapFileName,
2246 InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2247 InputKind::ModuleMap, /*Preprocessed*/true));
2248
2249 std::string NullTerminatedSource(Source.str());
2250
2251 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2252 StringRef(), ModuleFileName);
2253
2254 // Create a virtual file containing our desired source.
2255 // FIXME: We shouldn't need to do this.
2256 FileEntryRef ModuleMapFile = Other->getFileManager().getVirtualFileRef(
2257 ModuleMapFileName, NullTerminatedSource.size(), 0);
2258 Other->getSourceManager().overrideFileContents(
2259 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2260
2261 Other->BuiltModules = std::move(BuiltModules);
2262 Other->DeleteBuiltModules = false;
2263
2264 // Build the module, inheriting any modules that we've built locally.
2265 std::unique_ptr<llvm::MemoryBuffer> Buffer =
2266 compileModule(ImportLoc, ModuleName, ModuleFileName, *Other);
2267 BuiltModules = std::move(Other->BuiltModules);
2268
2269 if (Buffer) {
2270 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
2271 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2272 OS << Buffer->getBuffer();
2273 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2274 }
2275}
2276
2279 SourceLocation ImportLoc) {
2280 if (!TheASTReader)
2282 if (!TheASTReader)
2283 return;
2284
2285 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2286}
2287
2289 SourceLocation TriggerLoc) {
2290 if (getPreprocessor()
2291 .getHeaderSearchInfo()
2292 .getSpecificModuleCachePath()
2293 .empty())
2294 return nullptr;
2295 if (!TheASTReader)
2297 // Can't do anything if we don't have the module manager.
2298 if (!TheASTReader)
2299 return nullptr;
2300 // Get an existing global index. This loads it if not already
2301 // loaded.
2302 TheASTReader->loadGlobalIndex();
2303 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2304 // If the global index doesn't exist, create it.
2305 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2306 hasPreprocessor()) {
2307 llvm::sys::fs::create_directories(
2308 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath());
2309 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2312 .getHeaderSearchInfo()
2313 .getSpecificModuleCachePath())) {
2314 // FIXME this drops the error on the floor. This code is only used for
2315 // typo correction and drops more than just this one source of errors
2316 // (such as the directory creation failure above). It should handle the
2317 // error.
2318 consumeError(std::move(Err));
2319 return nullptr;
2320 }
2321 TheASTReader->resetForReload();
2322 TheASTReader->loadGlobalIndex();
2323 GlobalIndex = TheASTReader->getGlobalIndex();
2324 }
2325 // For finding modules needing to be imported for fixit messages,
2326 // we need to make the global index cover all modules, so we do that here.
2327 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2329
2330 // Load modules that were parsed from module maps but not loaded yet.
2331 MMap.loadAllParsedModules();
2332
2333 bool RecreateIndex = false;
2335 E = MMap.module_end(); I != E; ++I) {
2336 Module *TheModule = I->second;
2337 if (!TheModule->getASTFileKey()) {
2339 Path.emplace_back(TriggerLoc,
2340 getPreprocessor().getIdentifierInfo(TheModule->Name));
2341 std::reverse(Path.begin(), Path.end());
2342 // Load a module as hidden. This also adds it to the global index.
2343 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2344 RecreateIndex = true;
2345 }
2346 }
2347 if (RecreateIndex) {
2348 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2351 .getHeaderSearchInfo()
2352 .getSpecificModuleCachePath())) {
2353 // FIXME As above, this drops the error on the floor.
2354 consumeError(std::move(Err));
2355 return nullptr;
2356 }
2357 TheASTReader->resetForReload();
2358 TheASTReader->loadGlobalIndex();
2359 GlobalIndex = TheASTReader->getGlobalIndex();
2360 }
2361 HaveFullGlobalModuleIndex = true;
2362 }
2363 return GlobalIndex;
2364}
2365
2366// Check global module index for missing imports.
2367bool
2369 SourceLocation TriggerLoc) {
2370 // Look for the symbol in non-imported modules, but only if an error
2371 // actually occurred.
2372 if (!buildingModule()) {
2373 // Load global module index, or retrieve a previously loaded one.
2375 TriggerLoc);
2376
2377 // Only if we have a global index.
2378 if (GlobalIndex) {
2379 GlobalModuleIndex::HitSet FoundModules;
2380
2381 // Find the modules that reference the identifier.
2382 // Note that this only finds top-level modules.
2383 // We'll let diagnoseTypo find the actual declaration module.
2384 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2385 return true;
2386 }
2387 }
2388
2389 return false;
2390}
2391void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2392
2395 ExternalSemaSrc = std::move(ESS);
2396}
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 compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName 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 readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName, bool *OutOfDate, bool *Missing)
Read the AST right after compiling the module.
static CompileOrReadResult compileModuleBehindLockOrRead(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName)
Attempt to compile the module in a separate compiler instance behind a lock (to avoid building the sa...
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)
CompileOrReadResult
The result of compileModuleBehindLockOrRead().
@ Compiled
We successfully compiled the module and we still need to read it.
@ Read
We read a module file compiled by another instance.
@ FailedToRead
We failed to read the module file compiled by another instance.
@ FailedToCompile
We failed to compile 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 ModuleSource selectModuleSource(Module *M, StringRef ModuleName, ModuleFileName &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 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName)
Compile a module in a separate compiler instance.
static void checkConfigMacros(Preprocessor &PP, Module *M, SourceLocation ImportLoc)
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...
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
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:49
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
RAII object to temporarily add an AST callback listener.
Definition ASTReader.h:1940
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition ASTReader.h:1853
@ ARR_None
The client can't handle any AST loading failures.
Definition ASTReader.h:1849
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1866
@ 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:1857
@ 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:1870
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:447
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
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.
bool loadModuleFile(ModuleFileName FileName, serialization::ModuleFile *&LoadedModuleFile)
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)
GenModuleActionWrapperFunc getGenModuleActionWrapper() const
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()
std::unique_ptr< llvm::MemoryBuffer > 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...
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.
std::unique_ptr< CompilerInstance > cloneForModuleCompile(SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName, std::optional< ThreadSafeCloneConfig > ThreadSafeConfig=std::nullopt)
Creates a new CompilerInstance for compiling a module.
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.
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 computeContextHash() const
Compute the context hash - a string that uniquely identifies compiler settings.
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
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:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool hasErrorOccurred() const
Definition Diagnostic.h:881
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:621
DiagnosticConsumer * getClient()
Definition Diagnostic.h:613
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:975
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition Diagnostic.h:617
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:141
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.
unsigned ImplicitModulesLockTimeoutSeconds
The time in seconds to wait on an implicit module lock before timing out.
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.
ModuleFileName 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...
ModuleFileName getPrebuiltImplicitModuleFileName(Module *Module)
Retrieve the name of the prebuilt module file that should be used to load the given module.
ModuleFileName getCachedModuleFileName(Module *Module)
Retrieve the name of the cached 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.
ModuleMap & getModuleMap()
Retrieve the module map.
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.
llvm::MemoryBuffer & addBuiltPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Store a just-built PCM under the Filename.
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:30
virtual std::error_code write(StringRef Path, llvm::MemoryBufferRef Buffer)=0
Write the PCM contents to the given path in the module cache.
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
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.
Identifies a module file to be loaded.
Definition Module.h:102
bool empty() const
Checks whether the module file name is empty.
Definition Module.h:150
std::optional< ModuleFileKey > makeKey(FileManager &FileMgr) const
Creates the deduplication key for use in ModuleManager.
Definition Module.cpp:37
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:111
StringRef str() const
Returns the plain module file name.
Definition Module.h:144
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:777
module_iterator module_begin() const
Definition ModuleMap.h:779
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition ModuleMap.h:791
module_iterator module_end() const
Definition ModuleMap.h:780
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:786
void loadAllParsedModules()
Module * findOrLoadModule(StringRef Name)
Describes a module or submodule.
Definition Module.h:246
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:835
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
Definition Module.cpp:369
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:631
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:464
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:546
@ Hidden
All of the names in this module are hidden.
Definition Module.h:548
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:482
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:846
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:252
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:492
std::string Name
The name of this module.
Definition Module.h:249
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:952
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:300
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:479
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
Definition Module.h:468
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:258
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:475
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:825
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const =0
Returns the serialized AST inside the PCH container Buffer.
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
@ 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:868
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:359
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.
SourceLocation getBegin() const
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:227
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition Targets.cpp:810
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual void setAuxTarget(const TargetInfo *Aux)
void noSignedCharForObjCBool()
Definition TargetInfo.h:945
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:145
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
@ HeaderSearch
Remove unused header search paths including header maps.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ PluginAction
Run a plugin action,.
@ RewriteObjC
ObjC->C Rewriter.
bool Inv(InterpState &S, CodePtr OpPC)
Definition Interp.h:696
@ 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.
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.
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
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)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
Definition Stack.h:26
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:1761
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.