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