clang 23.0.0git
CompilerInstance.h
Go to the documentation of this file.
1//===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===//
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
9#ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
10#define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/IntrusiveRefCntPtr.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/BuryPointer.h"
28#include "llvm/Support/FileSystem.h"
29#include "llvm/Support/VirtualFileSystem.h"
30#include "llvm/Support/VirtualOutputBackend.h"
31#include <cassert>
32#include <list>
33#include <memory>
34#include <optional>
35#include <string>
36#include <utility>
37
38namespace llvm {
39class raw_fd_ostream;
40class PassPlugin;
41class Timer;
42class TimerGroup;
43}
44
45namespace clang {
46class ASTContext;
47class ASTReader;
48
49namespace serialization {
50class ModuleFile;
51}
52
56class FileManager;
57class FrontendAction;
58class Module;
59class ModuleCache;
60class Preprocessor;
61class Sema;
62class SourceManager;
63class TargetInfo;
65
66/// CompilerInstance - Helper class for managing a single instance of the Clang
67/// compiler.
68///
69/// The CompilerInstance serves two purposes:
70/// (1) It manages the various objects which are necessary to run the compiler,
71/// for example the preprocessor, the target information, and the AST
72/// context.
73/// (2) It provides utility routines for constructing and manipulating the
74/// common Clang objects.
75///
76/// The compiler instance generally owns the instance of all the objects that it
77/// manages. However, clients can still share objects by manually setting the
78/// object and retaking ownership prior to destroying the CompilerInstance.
79///
80/// The compiler instance is intended to simplify clients, but not to lock them
81/// in to the compiler instance for everything. When possible, utility functions
82/// come in two forms; a short form that reuses the CompilerInstance objects,
83/// and a long form that takes explicit instances of any required objects.
84class CompilerInstance : public ModuleLoader {
85 /// The options used in this compiler instance.
86 std::shared_ptr<CompilerInvocation> Invocation;
87
88 /// The virtual file system instance.
90
91 /// The diagnostics engine instance.
93
94 /// The target being compiled for.
96
97 /// Options for the auxiliary target.
98 std::unique_ptr<TargetOptions> AuxTargetOpts;
99
100 /// Auxiliary Target info.
102
103 /// The file manager.
105
106 /// The output manager.
108
109 /// The source manager.
111
112 /// The cache of PCM files.
113 std::shared_ptr<ModuleCache> ModCache;
114
115 /// Functor for getting the dependency preprocessor directives of a file.
116 std::unique_ptr<DependencyDirectivesGetter> GetDependencyDirectives;
117
118 /// The preprocessor.
119 std::shared_ptr<Preprocessor> PP;
120
121 /// The AST context.
123
124 /// An optional sema source that will be attached to sema.
126
127 /// The AST consumer.
128 std::unique_ptr<ASTConsumer> Consumer;
129
130 /// The code completion consumer.
131 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
132
133 /// The semantic analysis object.
134 std::unique_ptr<Sema> TheSema;
135
136 /// Back-end pass plugins.
137 std::vector<std::unique_ptr<llvm::PassPlugin>> PassPlugins;
138
139 /// The frontend timer group.
140 std::unique_ptr<llvm::TimerGroup> timerGroup;
141
142 /// The frontend timer.
143 std::unique_ptr<llvm::Timer> FrontendTimer;
144
145 /// The ASTReader, if one exists.
147
148 /// The module dependency collector for crashdumps
149 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
150
151 /// The module provider.
152 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
153
154 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
155
156 /// The set of modules that failed to build.
157 ///
158 /// This value will be passed among all of the compiler instances created
159 /// to (re)build modules, so that once a module fails to build anywhere,
160 /// other instances will see that the module has failed and won't try to
161 /// build it again.
162 llvm::StringSet<> FailedModules;
163
164 /// The set of top-level modules that has already been built on the
165 /// fly as part of this overall compilation action.
166 std::map<std::string, std::string, std::less<>> BuiltModules;
167
168 /// Should we delete the BuiltModules when we're done?
169 bool DeleteBuiltModules = true;
170
171 /// Cache of module import results keyed by import location.
172 /// It is important to eliminate redundant diagnostics
173 /// when both the preprocessor and parser see the same import declaration.
174 llvm::SmallDenseMap<SourceLocation, ModuleLoadResult, 4> ModuleImportResults;
175
176 /// Whether we should (re)build the global module index once we
177 /// have finished with this translation unit.
178 bool BuildGlobalModuleIndex = false;
179
180 /// We have a full global module index, with all modules.
181 bool HaveFullGlobalModuleIndex = false;
182
183 /// One or more modules failed to build.
184 bool DisableGeneratingGlobalModuleIndex = false;
185
186 /// The stream for verbose output if owned, otherwise nullptr.
187 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
188
189 /// The stream for verbose output.
190 raw_ostream *VerboseOutputStream = &llvm::errs();
191
192 /// The list of active output files.
193 std::list<llvm::vfs::OutputFile> OutputFiles;
194
195 /// Force an output buffer.
196 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
197
198 using GenModuleActionWrapperFunc =
200 const FrontendOptions &, std::unique_ptr<FrontendAction>)>;
201
202 /// An optional callback function used to wrap all FrontendActions
203 /// produced to generate imported modules before they are executed.
204 GenModuleActionWrapperFunc GenModuleActionWrapper;
205
206 CompilerInstance(const CompilerInstance &) = delete;
207 void operator=(const CompilerInstance &) = delete;
208public:
209 explicit CompilerInstance(
210 std::shared_ptr<CompilerInvocation> Invocation =
211 std::make_shared<CompilerInvocation>(),
212 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
213 std::make_shared<PCHContainerOperations>(),
214 std::shared_ptr<ModuleCache> ModCache = nullptr);
215 ~CompilerInstance() override;
216
217 /// @name High-Level Operations
218 /// @{
219
220 /// ExecuteAction - Execute the provided action against the compiler's
221 /// CompilerInvocation object.
222 ///
223 /// This function makes the following assumptions:
224 ///
225 /// - The invocation options should be initialized. This function does not
226 /// handle the '-help' or '-version' options, clients should handle those
227 /// directly.
228 ///
229 /// - The diagnostics engine should have already been created by the client.
230 ///
231 /// - No other CompilerInstance state should have been initialized (this is
232 /// an unchecked error).
233 ///
234 /// - Clients should have initialized any LLVM target features that may be
235 /// required.
236 ///
237 /// - Clients should eventually call llvm_shutdown() upon the completion of
238 /// this routine to ensure that any managed objects are properly destroyed.
239 ///
240 /// Note that this routine may write output to 'stderr'.
241 ///
242 /// \param Act - The action to execute.
243 /// \return - True on success.
244 //
245 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
246 // of the context or else not CompilerInstance specific.
247 bool ExecuteAction(FrontendAction &Act);
248
249 /// At the end of a compilation, print the number of warnings/errors.
251
252 /// Load the list of plugins requested in the \c FrontendOptions.
254
255 /// @}
256 /// @name Compiler Invocation and Options
257 /// @{
258
259 CompilerInvocation &getInvocation() { return *Invocation; }
260
261 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
262
263 /// Indicates whether we should (re)build the global module index.
264 bool shouldBuildGlobalModuleIndex() const;
265
266 /// Set the flag indicating whether we should (re)build the global
267 /// module index.
268 void setBuildGlobalModuleIndex(bool Build) {
269 BuildGlobalModuleIndex = Build;
270 }
271
272 /// @}
273 /// @name Forwarding Methods
274 /// @{
275
276 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
277
279 return Invocation->getCodeGenOpts();
280 }
282 return Invocation->getCodeGenOpts();
283 }
284
286 return Invocation->getDependencyOutputOpts();
287 }
289 return Invocation->getDependencyOutputOpts();
290 }
291
293 return Invocation->getDiagnosticOpts();
294 }
296 return Invocation->getDiagnosticOpts();
297 }
298
300 return Invocation->getFileSystemOpts();
301 }
303 return Invocation->getFileSystemOpts();
304 }
305
307 return Invocation->getFrontendOpts();
308 }
310 return Invocation->getFrontendOpts();
311 }
312
314 return Invocation->getHeaderSearchOpts();
315 }
317 return Invocation->getHeaderSearchOpts();
318 }
319
320 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
322 return Invocation->getAPINotesOpts();
323 }
324
325 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
326 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
327
329 return Invocation->getPreprocessorOpts();
330 }
332 return Invocation->getPreprocessorOpts();
333 }
334
336 return Invocation->getPreprocessorOutputOpts();
337 }
339 return Invocation->getPreprocessorOutputOpts();
340 }
341
343 return Invocation->getTargetOpts();
344 }
346 return Invocation->getTargetOpts();
347 }
348
349 /// @}
350 /// @name Diagnostics Engine
351 /// @{
352
353 bool hasDiagnostics() const { return Diagnostics != nullptr; }
354
355 /// Get the current diagnostics engine.
357 assert(Diagnostics && "Compiler instance has no diagnostics!");
358 return *Diagnostics;
359 }
360
362 assert(Diagnostics && "Compiler instance has no diagnostics!");
363 return Diagnostics;
364 }
365
366 /// setDiagnostics - Replace the current diagnostics engine.
368
370 assert(Diagnostics && Diagnostics->getClient() &&
371 "Compiler instance has no diagnostic client!");
372 return *Diagnostics->getClient();
373 }
374
375 /// @}
376 /// @name VerboseOutputStream
377 /// @{
378
379 /// Replace the current stream for verbose output.
380 void setVerboseOutputStream(raw_ostream &Value);
381
382 /// Replace the current stream for verbose output.
383 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
384
385 /// Get the current stream for verbose output.
386 raw_ostream &getVerboseOutputStream() {
387 return *VerboseOutputStream;
388 }
389
390 /// @}
391 /// @name Target Info
392 /// @{
393
394 bool hasTarget() const { return Target != nullptr; }
395
397 assert(Target && "Compiler instance has no target!");
398 return *Target;
399 }
400
402 assert(Target && "Compiler instance has no target!");
403 return Target;
404 }
405
406 /// Replace the current Target.
408
409 /// @}
410 /// @name AuxTarget Info
411 /// @{
412
413 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
414
415 /// Replace the current AuxTarget.
417
418 // Create Target and AuxTarget based on current options
419 bool createTarget();
420
421 /// @}
422 /// @name Virtual File System
423 /// @{
424
425 bool hasVirtualFileSystem() const { return VFS != nullptr; }
426
427 /// Create a virtual file system instance based on the invocation.
428 ///
429 /// @param BaseFS The file system that may be used when configuring the final
430 /// file system, and act as the underlying file system. Must not
431 /// be NULL.
432 /// @param DC If non-NULL, the diagnostic consumer to be used in case
433 /// configuring the file system emits diagnostics. Note that the
434 /// DiagnosticsEngine using the consumer won't obey the
435 /// --warning-suppression-mappings= flag.
437 BaseFS = llvm::vfs::getRealFileSystem(),
438 DiagnosticConsumer *DC = nullptr);
439
440 /// Use the given file system.
442 VFS = std::move(FS);
443 }
444
445 llvm::vfs::FileSystem &getVirtualFileSystem() const { return *VFS; }
446
450
451 /// @}
452 /// @name File Manager
453 /// @{
454
455 bool hasFileManager() const { return FileMgr != nullptr; }
456
457 /// Return the current file manager to the caller.
459 assert(FileMgr && "Compiler instance has no file manager!");
460 return *FileMgr;
461 }
462
464 assert(FileMgr && "Compiler instance has no file manager!");
465 return FileMgr;
466 }
467
469 llvm::BuryPointer(FileMgr.get());
470 FileMgr.resetWithoutRelease();
471 }
472
473 /// Replace the current file manager.
475
476 /// @}
477 /// @name Output Manager
478 /// @{
479
480 /// Set the output manager.
481 void
483
484 /// Create an output manager.
485 void createOutputManager();
486
487 bool hasOutputManager() const { return bool(OutputMgr); }
488
489 llvm::vfs::OutputBackend &getOutputManager();
490 llvm::vfs::OutputBackend &getOrCreateOutputManager();
491
492 /// @}
493 /// @name Source Manager
494 /// @{
495
496 bool hasSourceManager() const { return SourceMgr != nullptr; }
497
498 /// Return the current source manager.
500 assert(SourceMgr && "Compiler instance has no source manager!");
501 return *SourceMgr;
502 }
503
505 assert(SourceMgr && "Compiler instance has no source manager!");
506 return SourceMgr;
507 }
508
510 llvm::BuryPointer(SourceMgr.get());
511 SourceMgr.resetWithoutRelease();
512 }
513
514 /// setSourceManager - Replace the current source manager.
516
517 /// @}
518 /// @name Preprocessor
519 /// @{
520
521 bool hasPreprocessor() const { return PP != nullptr; }
522
523 /// Return the current preprocessor.
525 assert(PP && "Compiler instance has no preprocessor!");
526 return *PP;
527 }
528
529 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
530
532 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
533 }
534
535 /// Replace the current preprocessor.
536 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
537
538 /// @}
539 /// @name ASTContext
540 /// @{
541
542 bool hasASTContext() const { return Context != nullptr; }
543
545 assert(Context && "Compiler instance has no AST context!");
546 return *Context;
547 }
548
550 assert(Context && "Compiler instance has no AST context!");
551 return Context;
552 }
553
555 llvm::BuryPointer(Context.get());
556 Context.resetWithoutRelease();
557 }
558
559 /// setASTContext - Replace the current AST context.
561
562 /// Replace the current Sema; the compiler instance takes ownership
563 /// of S.
564 void setSema(Sema *S);
565
566 /// @}
567 /// @name ASTConsumer
568 /// @{
569
570 bool hasASTConsumer() const { return (bool)Consumer; }
571
573 assert(Consumer && "Compiler instance has no AST consumer!");
574 return *Consumer;
575 }
576
577 /// takeASTConsumer - Remove the current AST consumer and give ownership to
578 /// the caller.
579 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
580
581 /// setASTConsumer - Replace the current AST consumer; the compiler instance
582 /// takes ownership of \p Value.
583 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
584
585 /// @}
586 /// @name Semantic analysis
587 /// @{
588 bool hasSema() const { return (bool)TheSema; }
589
590 Sema &getSema() const {
591 assert(TheSema && "Compiler instance has no Sema object!");
592 return *TheSema;
593 }
594
595 std::unique_ptr<Sema> takeSema();
596 void resetAndLeakSema();
597
598 /// @}
599 /// @name Module Management
600 /// @{
601
604
605 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
607 std::shared_ptr<ModuleDependencyCollector> Collector);
608
609 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
610 return ThePCHContainerOperations;
611 }
612
613 /// Return the appropriate PCHContainerWriter depending on the
614 /// current CodeGenOptions.
616 assert(Invocation && "cannot determine module format without invocation");
617 StringRef Format = getHeaderSearchOpts().ModuleFormat;
618 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
619 if (!Writer) {
620 if (Diagnostics)
621 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
622 llvm::report_fatal_error("unknown module format");
623 }
624 return *Writer;
625 }
626
627 /// Return the appropriate PCHContainerReader depending on the
628 /// current CodeGenOptions.
630 assert(Invocation && "cannot determine module format without invocation");
631 StringRef Format = getHeaderSearchOpts().ModuleFormat;
632 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
633 if (!Reader) {
634 if (Diagnostics)
635 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
636 llvm::report_fatal_error("unknown module format");
637 }
638 return *Reader;
639 }
640
641 /// @}
642 /// @name Code Completion
643 /// @{
644
645 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
646
648 assert(CompletionConsumer &&
649 "Compiler instance has no code completion consumer!");
650 return *CompletionConsumer;
651 }
652
653 /// setCodeCompletionConsumer - Replace the current code completion consumer;
654 /// the compiler instance takes ownership of \p Value.
656
657 /// }
658 /// @name Back-end Pass Plugins
659 /// @{
660
662 return PassPlugins;
663 }
664
665 /// @}
666 /// @name Frontend timer
667 /// @{
668
669 llvm::TimerGroup &getTimerGroup() const { return *timerGroup; }
670
671 llvm::Timer &getFrontendTimer() const {
672 assert(FrontendTimer && "Compiler instance has no frontend timer!");
673 return *FrontendTimer;
674 }
675
676 /// }
677 /// @name Output Files
678 /// @{
679
680 /// clearOutputFiles - Clear the output file list. The underlying output
681 /// streams must have been closed beforehand.
682 ///
683 /// \param EraseFiles - If true, attempt to erase the files from disk.
684 void clearOutputFiles(bool EraseFiles);
685
686 /// @}
687 /// @name Construction Utility Methods
688 /// @{
689
690 /// Create the diagnostics engine using the invocation's diagnostic options
691 /// and replace any existing one with it.
692 ///
693 /// Note that this routine also replaces the diagnostic client,
694 /// allocating one if one is not provided.
695 ///
696 /// \param Client If non-NULL, a diagnostic client that will be
697 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
698 /// unit.
699 ///
700 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
701 /// the diagnostic object should take ownership of the client.
702 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
703 bool ShouldOwnClient = true);
704
705 /// Create a DiagnosticsEngine object.
706 ///
707 /// If no diagnostic client is provided, this creates a
708 /// DiagnosticConsumer that is owned by the returned diagnostic
709 /// object, if using directly the caller is responsible for
710 /// releasing the returned DiagnosticsEngine's client eventually.
711 ///
712 /// \param VFS The file system used to load the suppression mappings file.
713 ///
714 /// \param Opts - The diagnostic options; note that the created text
715 /// diagnostic object contains a reference to these options.
716 ///
717 /// \param Client If non-NULL, a diagnostic client that will be
718 /// attached to (and, then, owned by) the returned DiagnosticsEngine
719 /// object. If NULL, the returned DiagnosticsEngine will own a newly-created
720 /// client.
721 ///
722 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
723 /// used by some diagnostics printers (for logging purposes only).
724 ///
725 /// \return The new object on success, or null on failure.
727 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
728 DiagnosticConsumer *Client = nullptr,
729 bool ShouldOwnClient = true,
730 const CodeGenOptions *CodeGenOpts = nullptr);
731
732 /// Create the file manager and replace any existing one with it.
733 void createFileManager();
734
735 /// Create the source manager and replace any existing one with it.
736 void createSourceManager();
737
738 /// Create the preprocessor, using the invocation, file, and source managers,
739 /// and replace any existing one with it.
741
743 std::unique_ptr<DependencyDirectivesGetter> Getter) {
744 GetDependencyDirectives = std::move(Getter);
745 }
746
747 /// Create the AST context.
748 void createASTContext();
749
750 /// Create an external AST source to read a PCH file and attach it to the AST
751 /// context.
753 StringRef Path, DisableValidationForModuleKind DisableValidation,
754 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
755 bool OwnDeserializationListener);
756
757 /// Create an external AST source to read a PCH file.
758 ///
759 /// \return - The new object on success, or null on failure.
761 StringRef Path, StringRef Sysroot,
762 DisableValidationForModuleKind DisableValidation,
763 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
764 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
765 const CodeGenOptions &CodeGenOpts,
766 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
767 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
768 void *DeserializationListener, bool OwnDeserializationListener,
769 bool Preamble, bool UseGlobalModuleIndex);
770
771 /// Create a code completion consumer using the invocation; note that this
772 /// will cause the source manager to truncate the input source file at the
773 /// completion point.
775
776 /// Create a code completion consumer to print code completion results, at
777 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
779 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
780 const CodeCompleteOptions &Opts, raw_ostream &OS);
781
782 /// Create the Sema object to be used for parsing.
784 CodeCompleteConsumer *CompletionConsumer);
785
786 /// Create the frontend timer and replace any existing one with it.
787 void createFrontendTimer();
788
789 /// Create the default output file (from the invocation's options) and add it
790 /// to the list of tracked output files.
791 ///
792 /// The files created by this are usually removed on signal, and, depending
793 /// on FrontendOptions, may also use a temporary file (that is, the data is
794 /// written to a temporary file which will atomically replace the target
795 /// output on success).
796 ///
797 /// \return - Null on error.
798 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
799 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
800 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
801 bool ForceUseTemporary = false);
802
803 /// Create a new output file, optionally deriving the output path name, and
804 /// add it to the list of tracked output files.
805 ///
806 /// \return - Null on error.
807 std::unique_ptr<raw_pwrite_stream>
808 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
809 bool UseTemporary, bool CreateMissingDirectories = false);
810
811private:
812 /// Create a new output file and add it to the list of tracked output files.
813 ///
814 /// If \p OutputPath is empty, then createOutputFile will derive an output
815 /// path location as \p BaseInput, with any suffix removed, and \p Extension
816 /// appended. If \p OutputPath is not stdout and \p UseTemporary
817 /// is true, createOutputFile will create a new temporary file that must be
818 /// renamed to \p OutputPath in the end.
819 ///
820 /// \param OutputPath - If given, the path to the output file.
821 /// \param Binary - The mode to open the file in.
822 /// \param RemoveFileOnSignal - Whether the file should be registered with
823 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
824 /// multithreaded use, as the underlying signal mechanism is not reentrant
825 /// \param UseTemporary - Create a new temporary file that must be renamed to
826 /// OutputPath in the end.
827 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
828 /// missing directories in the output path.
830 createOutputFileImpl(StringRef OutputPath, bool Binary,
831 bool RemoveFileOnSignal, bool UseTemporary,
832 bool CreateMissingDirectories);
833
834public:
835 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
836
837 /// @}
838 /// @name Initialization Utility Methods
839 /// @{
840
841 /// InitializeSourceManager - Initialize the source manager to set InputFile
842 /// as the main file.
843 ///
844 /// \return True on success.
846
847 /// InitializeSourceManager - Initialize the source manager to set InputFile
848 /// as the main file.
849 ///
850 /// \return True on success.
851 static bool InitializeSourceManager(const FrontendInputFile &Input,
852 DiagnosticsEngine &Diags,
854 SourceManager &SourceMgr);
855
856 /// @}
857
858 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
859 OutputStream = std::move(OutStream);
860 }
861
862 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
863 return std::move(OutputStream);
864 }
865
866 void createASTReader();
867
869 serialization::ModuleFile *&LoadedModuleFile);
870
871 /// Configuration object for making the result of \c cloneForModuleCompile()
872 /// thread-safe.
875 DiagnosticConsumer &DiagConsumer;
876 std::shared_ptr<ModuleCache> ModCache;
877 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
878
879 public:
882 DiagnosticConsumer &DiagConsumer, std::shared_ptr<ModuleCache> ModCache,
883 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector = nullptr)
884 : VFS(std::move(VFS)), DiagConsumer(DiagConsumer),
885 ModCache(std::move(ModCache)),
886 ModuleDepCollector(std::move(ModuleDepCollector)) {
887 assert(this->VFS && "Clone config requires non-null VFS");
888 assert(this->ModCache && "Clone config requires non-null ModuleCache");
889 }
890
892 DiagnosticConsumer &getDiagConsumer() const { return DiagConsumer; }
893 std::shared_ptr<ModuleCache> getModuleCache() const { return ModCache; }
894 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const {
895 return ModuleDepCollector;
896 }
897 };
898
899private:
900 /// Find a module, potentially compiling it, before reading its AST. This is
901 /// the guts of loadModule.
902 ///
903 /// For prebuilt modules, the Module is not expected to exist in
904 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
905 /// ModuleManager, then it will be loaded and looked up.
906 ///
907 /// For implicit modules, the Module is expected to already be in the
908 /// ModuleMap. First attempt to load it from the given path on disk. If that
909 /// fails, defer to compileModuleAndReadAST, which will first build and then
910 /// load it.
911 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
912 SourceLocation ImportLoc,
913 SourceRange ModuleNameRange,
914 bool IsInclusionDirective);
915
916 /// Creates a \c CompilerInstance for compiling a module.
917 ///
918 /// This expects a properly initialized \c FrontendInputFile.
919 std::unique_ptr<CompilerInstance> cloneForModuleCompileImpl(
920 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
921 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
922 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
923
924public:
925 /// Creates a new \c CompilerInstance for compiling a module.
926 ///
927 /// This takes care of creating appropriate \c FrontendInputFile for
928 /// public/private frameworks, inferred modules and such.
929 ///
930 /// The \c ThreadSafeConfig takes precedence over the \c DiagnosticConsumer
931 /// and \c FileSystem of this instance (and disables \c FileManager sharing).
932 std::unique_ptr<CompilerInstance> cloneForModuleCompile(
933 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
934 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
935
936 /// Compile a module file for the given module, using the options
937 /// provided by the importing compiler instance. Returns the PCM file in
938 /// a buffer.
939 // FIXME: This should be private, but it's called from static non-member
940 // functions in the implementation file.
941 std::unique_ptr<llvm::MemoryBuffer> compileModule(SourceLocation ImportLoc,
942 StringRef ModuleName,
943 StringRef ModuleFileName,
944 CompilerInstance &Instance);
945
948 bool IsInclusionDirective) override;
949
950 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
951 StringRef Source) override;
952
954 SourceLocation ImportLoc) override;
955
959
961
962 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
963
964 void setGenModuleActionWrapper(GenModuleActionWrapperFunc Wrapper) {
965 GenModuleActionWrapper = Wrapper;
966 }
967
968 GenModuleActionWrapperFunc getGenModuleActionWrapper() const {
969 return GenModuleActionWrapper;
970 }
971
972 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
973 DependencyCollectors.push_back(std::move(Listener));
974 }
975
976 void clearDependencyCollectors() { DependencyCollectors.clear(); }
977
978 std::vector<std::shared_ptr<DependencyCollector>> &getDependencyCollectors() {
979 return DependencyCollectors;
980 }
981
983
984 ModuleCache &getModuleCache() const { return *ModCache; }
985 std::shared_ptr<ModuleCache> getModuleCachePtr() const { return ModCache; }
986};
987
988} // end namespace clang
989
990#endif
Defines the Diagnostic-related interfaces.
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
Defines the SourceManager interface.
Tracks various options which control how API notes are found and handled.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:428
Stores options for the analyzer from the command line.
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::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVFS() const
std::shared_ptr< ModuleCache > getModuleCache() const
ThreadSafeCloneConfig(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagConsumer, std::shared_ptr< ModuleCache > ModCache, std::shared_ptr< ModuleDependencyCollector > ModuleDepCollector=nullptr)
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...
AnalyzerOptions & getAnalyzerOpts()
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 ...
const HeaderSearchOptions & getHeaderSearchOpts() const
DependencyOutputOptions & getDependencyOutputOpts()
const DependencyOutputOptions & getDependencyOutputOpts() const
std::shared_ptr< Preprocessor > getPreprocessorPtr()
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.
llvm::TimerGroup & getTimerGroup() const
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
const DiagnosticOptions & getDiagnosticOpts() const
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
const CodeGenOptions & getCodeGenOpts() const
FileSystemOptions & getFileSystemOpts()
llvm::Timer & getFrontendTimer() const
const TargetOptions & getTargetOpts() 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.
void setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Use the given file system.
void setOutputStream(std::unique_ptr< llvm::raw_pwrite_stream > OutStream)
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.
IntrusiveRefCntPtr< DiagnosticsEngine > getDiagnosticsPtr() const
void createOutputManager()
Create an output manager.
std::unique_ptr< Sema > takeSema()
const PreprocessorOptions & getPreprocessorOpts() const
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
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
ModuleCache & getModuleCache() const
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
std::shared_ptr< ModuleCache > getModuleCachePtr() const
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()
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
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)
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
const FrontendOptions & getFrontendOpts() const
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
std::shared_ptr< CompilerInvocation > getInvocationPtr()
bool hadModuleLoaderFatalFailure() 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.
bool hasCodeCompletionConsumer() const
std::vector< std::shared_ptr< DependencyCollector > > & getDependencyCollectors()
const LangOptions & getLangOpts() const
void createSourceManager()
Create the source manager and replace any existing one with it.
CompilerInvocation & getInvocation()
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
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
const FileSystemOptions & getFileSystemOpts() 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::ArrayRef< std::unique_ptr< llvm::PassPlugin > > getPassPlugins() const
llvm::vfs::OutputBackend & getOrCreateOutputManager()
const APINotesOptions & getAPINotesOpts() const
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr() const
CodeCompleteConsumer & getCodeCompletionConsumer() const
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.
void setGenModuleActionWrapper(GenModuleActionWrapperFunc Wrapper)
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 setDependencyDirectivesGetter(std::unique_ptr< DependencyDirectivesGetter > Getter)
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.
Helper class for holding the data necessary to invoke the compiler.
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:53
Keeps track of options that affect how file operations are performed.
Abstract base class for actions which can be performed by the frontend.
An input file for the front end.
FrontendOptions - Options for controlling the behavior of the frontend.
A global index for a set of module files, providing information about the identifiers within those mo...
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::string ModuleFormat
The module/pch container format.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:30
Identifies a module file to be loaded.
Definition Module.h:102
Describes the result of attempting to load a module.
ModuleLoader(bool BuildingModule=false)
Describes a module or submodule.
Definition Module.h:246
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:549
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
This abstract interface provides operations for creating containers for serialized ASTs (precompiled ...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
Encodes a location in the source.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition TargetInfo.h:227
Options for controlling the target.
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
TranslationUnitKind
Describes the kind of translation unit being processed.
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition Visibility.h:34
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int const char * function
Definition c++config.h:31