clang 24.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/LibraryOptionsContext.h"
30#include "llvm/Support/VirtualFileSystem.h"
31#include "llvm/Support/VirtualOutputBackend.h"
32#include <cassert>
33#include <list>
34#include <memory>
35#include <optional>
36#include <string>
37#include <utility>
38
39namespace llvm {
40class raw_fd_ostream;
41class PassPlugin;
42class Timer;
43class TimerGroup;
44}
45
46namespace clang {
47class ASTContext;
48class ASTReader;
49
50namespace serialization {
51class ModuleFile;
52}
53
57class FileManager;
58class FrontendAction;
59class Module;
60class ModuleCache;
61class Preprocessor;
62class Sema;
63class SourceManager;
64class TargetInfo;
66
67namespace Builtin {
68class TargetBuiltins;
69} // namespace Builtin
70
71/// CompilerInstance - Helper class for managing a single instance of the Clang
72/// compiler.
73///
74/// The CompilerInstance serves two purposes:
75/// (1) It manages the various objects which are necessary to run the compiler,
76/// for example the preprocessor, the target information, and the AST
77/// context.
78/// (2) It provides utility routines for constructing and manipulating the
79/// common Clang objects.
80///
81/// The compiler instance generally owns the instance of all the objects that it
82/// manages. However, clients can still share objects by manually setting the
83/// object and retaking ownership prior to destroying the CompilerInstance.
84///
85/// The compiler instance is intended to simplify clients, but not to lock them
86/// in to the compiler instance for everything. When possible, utility functions
87/// come in two forms; a short form that reuses the CompilerInstance objects,
88/// and a long form that takes explicit instances of any required objects.
89class CompilerInstance : public ModuleLoader {
90 /// The options used in this compiler instance.
91 std::shared_ptr<CompilerInvocation> Invocation;
92
93 /// The virtual file system instance.
95
96 /// The diagnostics engine instance.
98
99 /// The target being compiled for.
101
102 /// Options for the auxiliary target.
103 std::unique_ptr<TargetOptions> AuxTargetOpts;
104
105 /// Auxiliary Target info.
107
108 /// The file manager.
110
111 /// The output manager.
113
114 /// The source manager.
116
117 /// The cache of PCM files.
118 std::shared_ptr<ModuleCache> ModCache;
119
120 /// The builtins of the instance's target and aux target, shared with the
121 /// module builds it requests, which have the same targets.
122 std::shared_ptr<const Builtin::TargetBuiltins> SharedBuiltins;
123
124 /// Directory dependencies from the instance that requested this module build.
125 /// An inferred framework is built from printed module map text rather than by
126 /// repeating the inference, so its \c Frameworks listing is only seen there.
127 std::vector<std::string> InheritedDirectoryDependencies;
128
129 /// Functor for getting the dependency preprocessor directives of a file.
130 std::unique_ptr<DependencyDirectivesGetter> GetDependencyDirectives;
131
132 /// The preprocessor.
133 std::shared_ptr<Preprocessor> PP;
134
135 /// The AST context.
137
138 /// An optional sema source that will be attached to sema.
140
141 /// The AST consumer.
142 std::unique_ptr<ASTConsumer> Consumer;
143
144 /// The code completion consumer.
145 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
146
147 /// The semantic analysis object.
148 std::unique_ptr<Sema> TheSema;
149
150 /// Back-end pass plugins.
151 std::vector<std::unique_ptr<llvm::PassPlugin>> PassPlugins;
152
153 /// The frontend timer group.
154 std::unique_ptr<llvm::TimerGroup> timerGroup;
155
156 /// The frontend timer.
157 std::unique_ptr<llvm::Timer> FrontendTimer;
158
159 /// The -mllvm options of per-context libraries, which every LLVMContext that
160 /// compiles for this instance receives.
161 llvm::cl::LibraryOptionsContext LibraryOptions;
162
163 /// The ASTReader, if one exists.
165
166 /// The module dependency collector for crashdumps
167 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
168
169 /// The module provider.
170 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
171
172 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
173
174 /// The set of modules that failed to build.
175 ///
176 /// This value will be passed among all of the compiler instances created
177 /// to (re)build modules, so that once a module fails to build anywhere,
178 /// other instances will see that the module has failed and won't try to
179 /// build it again.
180 llvm::StringSet<> FailedModules;
181
182 /// The set of top-level modules that has already been built on the
183 /// fly as part of this overall compilation action.
184 std::map<std::string, std::string, std::less<>> BuiltModules;
185
186 /// Should we delete the BuiltModules when we're done?
187 bool DeleteBuiltModules = true;
188
189 /// Cache of module import results keyed by import location.
190 /// It is important to eliminate redundant diagnostics
191 /// when both the preprocessor and parser see the same import declaration.
192 llvm::SmallDenseMap<SourceLocation, ModuleLoadResult, 4> ModuleImportResults;
193
194 /// Whether we should (re)build the global module index once we
195 /// have finished with this translation unit.
196 bool BuildGlobalModuleIndex = false;
197
198 /// We have a full global module index, with all modules.
199 bool HaveFullGlobalModuleIndex = false;
200
201 /// One or more modules failed to build.
202 bool DisableGeneratingGlobalModuleIndex = false;
203
204 /// The stream for verbose output if owned, otherwise nullptr.
205 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
206
207 /// The stream for verbose output.
208 raw_ostream *VerboseOutputStream = &llvm::errs();
209
210 /// The list of active output files.
211 std::list<llvm::vfs::OutputFile> OutputFiles;
212
213 /// Force an output buffer.
214 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
215
216 using GenModuleActionWrapperFunc =
218 const FrontendOptions &, std::unique_ptr<FrontendAction>)>;
219
220 /// An optional callback function used to wrap all FrontendActions
221 /// produced to generate imported modules before they are executed.
222 GenModuleActionWrapperFunc GenModuleActionWrapper;
223
224 CompilerInstance(const CompilerInstance &) = delete;
225 void operator=(const CompilerInstance &) = delete;
226public:
227 explicit CompilerInstance(
228 std::shared_ptr<CompilerInvocation> Invocation =
229 std::make_shared<CompilerInvocation>(),
230 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
231 std::make_shared<PCHContainerOperations>(),
232 std::shared_ptr<ModuleCache> ModCache = nullptr);
233 ~CompilerInstance() override;
234
235 /// @name High-Level Operations
236 /// @{
237
238 // FIXME: Add a static InitializeProcess() method to consolidate process-level
239 // setup that is currently scattered across tool entry points (cc1_main,
240 // clang-repl, libclang, etc.). This would include things like AsmParsers and
241 // install_fatal_error_handler.
242 // These are process-global, so a single static method would allow clang-based
243 // tools to share them without duplication.
244
245 /// ExecuteAction - Execute the provided action against the compiler's
246 /// CompilerInvocation object.
247 ///
248 /// This function makes the following assumptions:
249 ///
250 /// - The invocation options should be initialized. This function does not
251 /// handle the '-help' or '-version' options, clients should handle those
252 /// directly.
253 ///
254 /// - The diagnostics engine should have already been created by the client.
255 ///
256 /// - No other CompilerInstance state should have been initialized (this is
257 /// an unchecked error).
258 ///
259 /// - Clients should have initialized any LLVM target features that may be
260 /// required.
261 ///
262 /// - Clients should eventually call llvm_shutdown() upon the completion of
263 /// this routine to ensure that any managed objects are properly destroyed.
264 ///
265 /// Note that this routine may write output to 'stderr'.
266 ///
267 /// \param Act - The action to execute.
268 /// \return - True on success.
269 //
270 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
271 // of the context or else not CompilerInstance specific.
272 bool ExecuteAction(FrontendAction &Act);
273
274 /// At the end of a compilation, print the number of warnings/errors.
276
277 /// Load the list of plugins requested in the \c FrontendOptions.
279
280 /// Parse the -mllvm options in FrontendOptions::LLVMArgs, setting library
281 /// options in getLibraryOptions(). Call after loading plugins. Return false
282 /// after reporting errors to \p Errs, or exit if \p Errs is null.
283 bool parseLLVMArgs(llvm::raw_ostream *Errs = nullptr);
284
285 const llvm::cl::LibraryOptionsContext &getLibraryOptions() const {
286 return LibraryOptions;
287 }
288
289 /// @}
290 /// @name Compiler Invocation and Options
291 /// @{
292
293 CompilerInvocation &getInvocation() { return *Invocation; }
294
295 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
296
297 /// Indicates whether we should (re)build the global module index.
298 bool shouldBuildGlobalModuleIndex() const;
299
300 /// Set the flag indicating whether we should (re)build the global
301 /// module index.
302 void setBuildGlobalModuleIndex(bool Build) {
303 BuildGlobalModuleIndex = Build;
304 }
305
306 /// @}
307 /// @name Forwarding Methods
308 /// @{
309
310 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
311
313 return Invocation->getCodeGenOpts();
314 }
316 return Invocation->getCodeGenOpts();
317 }
318
320 return Invocation->getDependencyOutputOpts();
321 }
323 return Invocation->getDependencyOutputOpts();
324 }
325
327 return Invocation->getDiagnosticOpts();
328 }
330 return Invocation->getDiagnosticOpts();
331 }
332
334 return Invocation->getFileSystemOpts();
335 }
337 return Invocation->getFileSystemOpts();
338 }
339
341 return Invocation->getFrontendOpts();
342 }
344 return Invocation->getFrontendOpts();
345 }
346
347 ssaf::SSAFOptions &getSSAFOpts() { return Invocation->getSSAFOpts(); }
349 return Invocation->getSSAFOpts();
350 }
351
353 return Invocation->getHeaderSearchOpts();
354 }
356 return Invocation->getHeaderSearchOpts();
357 }
358
359 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
361 return Invocation->getAPINotesOpts();
362 }
363
364 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
365 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
366
368 return Invocation->getPreprocessorOpts();
369 }
371 return Invocation->getPreprocessorOpts();
372 }
373
375 return Invocation->getPreprocessorOutputOpts();
376 }
378 return Invocation->getPreprocessorOutputOpts();
379 }
380
382 return Invocation->getTargetOpts();
383 }
385 return Invocation->getTargetOpts();
386 }
387
388 /// @}
389 /// @name Diagnostics Engine
390 /// @{
391
392 bool hasDiagnostics() const { return Diagnostics != nullptr; }
393
394 /// Get the current diagnostics engine.
396 assert(Diagnostics && "Compiler instance has no diagnostics!");
397 return *Diagnostics;
398 }
399
401 assert(Diagnostics && "Compiler instance has no diagnostics!");
402 return Diagnostics;
403 }
404
405 /// setDiagnostics - Replace the current diagnostics engine.
407
409 assert(Diagnostics && Diagnostics->getClient() &&
410 "Compiler instance has no diagnostic client!");
411 return *Diagnostics->getClient();
412 }
413
414 /// @}
415 /// @name VerboseOutputStream
416 /// @{
417
418 /// Replace the current stream for verbose output.
419 void setVerboseOutputStream(raw_ostream &Value);
420
421 /// Replace the current stream for verbose output.
422 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
423
424 /// Get the current stream for verbose output.
425 raw_ostream &getVerboseOutputStream() {
426 return *VerboseOutputStream;
427 }
428
429 /// @}
430 /// @name Target Info
431 /// @{
432
433 bool hasTarget() const { return Target != nullptr; }
434
436 assert(Target && "Compiler instance has no target!");
437 return *Target;
438 }
439
441 assert(Target && "Compiler instance has no target!");
442 return Target;
443 }
444
445 /// Replace the current Target.
447
448 /// @}
449 /// @name AuxTarget Info
450 /// @{
451
452 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
453
454 /// Replace the current AuxTarget.
456
457 // Create Target and AuxTarget based on current options
458 bool createTarget();
459
460 /// @}
461 /// @name Virtual File System
462 /// @{
463
464 bool hasVirtualFileSystem() const { return VFS != nullptr; }
465
466 /// Create a virtual file system instance based on the invocation.
467 ///
468 /// @param BaseFS The file system that may be used when configuring the final
469 /// file system, and act as the underlying file system. Must not
470 /// be NULL.
471 /// @param DC If non-NULL, the diagnostic consumer to be used in case
472 /// configuring the file system emits diagnostics. Note that the
473 /// DiagnosticsEngine using the consumer won't obey the
474 /// --warning-suppression-mappings= flag.
476 BaseFS = llvm::vfs::getRealFileSystem(),
477 DiagnosticConsumer *DC = nullptr);
478
479 /// Use the given file system.
481 VFS = std::move(FS);
482 }
483
484 llvm::vfs::FileSystem &getVirtualFileSystem() const { return *VFS; }
485
489
490 /// @}
491 /// @name File Manager
492 /// @{
493
494 bool hasFileManager() const { return FileMgr != nullptr; }
495
496 /// Return the current file manager to the caller.
498 assert(FileMgr && "Compiler instance has no file manager!");
499 return *FileMgr;
500 }
501
503 assert(FileMgr && "Compiler instance has no file manager!");
504 return FileMgr;
505 }
506
508 llvm::BuryPointer(FileMgr.get());
509 FileMgr.resetWithoutRelease();
510 }
511
512 /// Replace the current file manager.
514
515 /// @}
516 /// @name Output Manager
517 /// @{
518
519 /// Set the output manager.
520 void
522
523 /// Create an output manager.
524 void createOutputManager();
525
526 bool hasOutputManager() const { return bool(OutputMgr); }
527
528 llvm::vfs::OutputBackend &getOutputManager();
529 llvm::vfs::OutputBackend &getOrCreateOutputManager();
530
531 /// @}
532 /// @name Source Manager
533 /// @{
534
535 bool hasSourceManager() const { return SourceMgr != nullptr; }
536
537 /// Return the current source manager.
539 assert(SourceMgr && "Compiler instance has no source manager!");
540 return *SourceMgr;
541 }
542
544 assert(SourceMgr && "Compiler instance has no source manager!");
545 return SourceMgr;
546 }
547
549 llvm::BuryPointer(SourceMgr.get());
550 SourceMgr.resetWithoutRelease();
551 }
552
553 /// setSourceManager - Replace the current source manager.
555
556 /// @}
557 /// @name Preprocessor
558 /// @{
559
560 bool hasPreprocessor() const { return PP != nullptr; }
561
562 /// Return the current preprocessor.
564 assert(PP && "Compiler instance has no preprocessor!");
565 return *PP;
566 }
567
568 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
569
571 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
572 }
573
574 /// Replace the current preprocessor.
575 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
576
577 /// @}
578 /// @name ASTContext
579 /// @{
580
581 bool hasASTContext() const { return Context != nullptr; }
582
584 assert(Context && "Compiler instance has no AST context!");
585 return *Context;
586 }
587
589
591 llvm::BuryPointer(Context.get());
592 Context.resetWithoutRelease();
593 }
594
595 /// setASTContext - Replace the current AST context.
597
598 /// Replace the current Sema; the compiler instance takes ownership
599 /// of S.
600 void setSema(Sema *S);
601
602 /// @}
603 /// @name ASTConsumer
604 /// @{
605
606 bool hasASTConsumer() const { return (bool)Consumer; }
607
609 assert(Consumer && "Compiler instance has no AST consumer!");
610 return *Consumer;
611 }
612
613 /// takeASTConsumer - Remove the current AST consumer and give ownership to
614 /// the caller.
615 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
616
617 /// setASTConsumer - Replace the current AST consumer; the compiler instance
618 /// takes ownership of \p Value.
619 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
620
621 /// @}
622 /// @name Semantic analysis
623 /// @{
624 bool hasSema() const { return (bool)TheSema; }
625
626 Sema &getSema() const {
627 assert(TheSema && "Compiler instance has no Sema object!");
628 return *TheSema;
629 }
630
631 std::unique_ptr<Sema> takeSema();
632 void resetAndLeakSema();
633
634 /// @}
635 /// @name Module Management
636 /// @{
637
640
641 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
643 std::shared_ptr<ModuleDependencyCollector> Collector);
644
645 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
646 return ThePCHContainerOperations;
647 }
648
649 /// Return the appropriate PCHContainerWriter depending on the
650 /// current CodeGenOptions.
652 assert(Invocation && "cannot determine module format without invocation");
653 StringRef Format = getHeaderSearchOpts().ModuleFormat;
654 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
655 if (!Writer) {
656 if (Diagnostics)
657 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
658 llvm::report_fatal_error("unknown module format");
659 }
660 return *Writer;
661 }
662
663 /// Return the appropriate PCHContainerReader depending on the
664 /// current CodeGenOptions.
666 assert(Invocation && "cannot determine module format without invocation");
667 StringRef Format = getHeaderSearchOpts().ModuleFormat;
668 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
669 if (!Reader) {
670 if (Diagnostics)
671 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
672 llvm::report_fatal_error("unknown module format");
673 }
674 return *Reader;
675 }
676
677 /// @}
678 /// @name Code Completion
679 /// @{
680
681 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
682
684 assert(CompletionConsumer &&
685 "Compiler instance has no code completion consumer!");
686 return *CompletionConsumer;
687 }
688
689 /// setCodeCompletionConsumer - Replace the current code completion consumer;
690 /// the compiler instance takes ownership of \p Value.
692
693 /// }
694 /// @name Back-end Pass Plugins
695 /// @{
696
698 return PassPlugins;
699 }
700
701 /// @}
702 /// @name Frontend timer
703 /// @{
704
705 llvm::TimerGroup &getTimerGroup() const { return *timerGroup; }
706
707 llvm::Timer &getFrontendTimer() const {
708 assert(FrontendTimer && "Compiler instance has no frontend timer!");
709 return *FrontendTimer;
710 }
711
712 /// }
713 /// @name Output Files
714 /// @{
715
716 /// clearOutputFiles - Clear the output file list. The underlying output
717 /// streams must have been closed beforehand.
718 ///
719 /// \param EraseFiles - If true, attempt to erase the files from disk.
720 void clearOutputFiles(bool EraseFiles);
721
722 /// @}
723 /// @name Construction Utility Methods
724 /// @{
725
726 /// Create the diagnostics engine using the invocation's diagnostic options
727 /// and replace any existing one with it.
728 ///
729 /// Note that this routine also replaces the diagnostic client,
730 /// allocating one if one is not provided.
731 ///
732 /// \param Client If non-NULL, a diagnostic client that will be
733 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
734 /// unit.
735 ///
736 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
737 /// the diagnostic object should take ownership of the client.
738 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
739 bool ShouldOwnClient = true);
740
741 /// Create a DiagnosticsEngine object.
742 ///
743 /// If no diagnostic client is provided, this creates a
744 /// DiagnosticConsumer that is owned by the returned diagnostic
745 /// object, if using directly the caller is responsible for
746 /// releasing the returned DiagnosticsEngine's client eventually.
747 ///
748 /// \param VFS The file system used to load the suppression mappings file.
749 ///
750 /// \param Opts - The diagnostic options; note that the created text
751 /// diagnostic object contains a reference to these options.
752 ///
753 /// \param Client If non-NULL, a diagnostic client that will be
754 /// attached to (and, then, owned by) the returned DiagnosticsEngine
755 /// object. If NULL, the returned DiagnosticsEngine will own a newly-created
756 /// client.
757 ///
758 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
759 /// used by some diagnostics printers (for logging purposes only).
760 ///
761 /// \return The new object on success, or null on failure.
763 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
764 DiagnosticConsumer *Client = nullptr,
765 bool ShouldOwnClient = true,
766 const CodeGenOptions *CodeGenOpts = nullptr);
767
768 /// Create the file manager and replace any existing one with it.
769 void createFileManager();
770
771 /// Create the source manager and replace any existing one with it.
772 void createSourceManager();
773
774 /// Create the preprocessor, using the invocation, file, and source managers,
775 /// and replace any existing one with it.
777
779 std::unique_ptr<DependencyDirectivesGetter> Getter) {
780 GetDependencyDirectives = std::move(Getter);
781 }
782
783 /// Create the AST context.
784 void createASTContext();
785
786 /// Create an external AST source to read a PCH file and attach it to the AST
787 /// context.
789 StringRef Path, DisableValidationForModuleKind DisableValidation,
790 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
791 bool OwnDeserializationListener);
792
793 /// Create an external AST source to read a PCH file.
794 ///
795 /// \return - The new object on success, or null on failure.
797 StringRef Path, StringRef Sysroot,
798 DisableValidationForModuleKind DisableValidation,
799 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
800 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
801 const CodeGenOptions &CodeGenOpts,
802 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
803 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
804 void *DeserializationListener, bool OwnDeserializationListener,
805 bool Preamble, bool UseGlobalModuleIndex);
806
807 /// Create a code completion consumer using the invocation; note that this
808 /// will cause the source manager to truncate the input source file at the
809 /// completion point.
811
812 /// Create a code completion consumer to print code completion results, at
813 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
815 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
816 const CodeCompleteOptions &Opts, raw_ostream &OS);
817
818 /// Create the Sema object to be used for parsing.
820 CodeCompleteConsumer *CompletionConsumer);
821
822 /// Create the frontend timer and replace any existing one with it.
823 void createFrontendTimer();
824
825 /// Create the default output file (from the invocation's options) and add it
826 /// to the list of tracked output files.
827 ///
828 /// The files created by this are usually removed on signal, and, depending
829 /// on FrontendOptions, may also use a temporary file (that is, the data is
830 /// written to a temporary file which will atomically replace the target
831 /// output on success).
832 ///
833 /// \return - Null on error.
834 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
835 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
836 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
837 bool ForceUseTemporary = false, bool SetOnlyIfDifferent = false);
838
839 /// Create a new output file, optionally deriving the output path name, and
840 /// add it to the list of tracked output files.
841 ///
842 /// \return - Null on error.
843 std::unique_ptr<raw_pwrite_stream>
844 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
845 bool UseTemporary, bool CreateMissingDirectories = false,
846 bool SetOnlyIfDifferent = false);
847
848private:
849 /// Prepare the CompilerInstance for executing a frontend action.
850 ///
851 /// Called by ExecuteAction. Consolidates instance-level setup that was
852 /// previously duplicated across tool entry points (cc1_main,
853 /// clang-repl/Interpreter, etc.).
854 void PrepareForExecution();
855
856 /// Create a new output file and add it to the list of tracked output files.
857 ///
858 /// If \p OutputPath is empty, then createOutputFile will derive an output
859 /// path location as \p BaseInput, with any suffix removed, and \p Extension
860 /// appended. If \p OutputPath is not stdout and \p UseTemporary
861 /// is true, createOutputFile will create a new temporary file that must be
862 /// renamed to \p OutputPath in the end.
863 ///
864 /// \param OutputPath - If given, the path to the output file.
865 /// \param Binary - The mode to open the file in.
866 /// \param RemoveFileOnSignal - Whether the file should be registered with
867 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
868 /// multithreaded use, as the underlying signal mechanism is not reentrant
869 /// \param UseTemporary - Create a new temporary file that must be renamed to
870 /// OutputPath in the end.
871 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
872 /// missing directories in the output path.
874 createOutputFileImpl(StringRef OutputPath, bool Binary,
875 bool RemoveFileOnSignal, bool UseTemporary,
876 bool CreateMissingDirectories, bool SetOnlyIfDifferent);
877
878public:
879 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
880
881 /// @}
882 /// @name Initialization Utility Methods
883 /// @{
884
885 /// InitializeSourceManager - Initialize the source manager to set InputFile
886 /// as the main file.
887 ///
888 /// \return True on success.
890
891 /// InitializeSourceManager - Initialize the source manager to set InputFile
892 /// as the main file.
893 ///
894 /// \return True on success.
895 static bool InitializeSourceManager(const FrontendInputFile &Input,
896 DiagnosticsEngine &Diags,
898 SourceManager &SourceMgr);
899
900 /// @}
901
902 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
903 OutputStream = std::move(OutStream);
904 }
905
906 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
907 return std::move(OutputStream);
908 }
909
910 void createASTReader();
911
913 serialization::ModuleFile *&LoadedModuleFile);
914
915 /// Configuration object for making the result of \c cloneForModuleCompile()
916 /// thread-safe.
919 DiagnosticConsumer &DiagConsumer;
920 std::shared_ptr<ModuleCache> ModCache;
921 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
922
923 public:
926 DiagnosticConsumer &DiagConsumer, std::shared_ptr<ModuleCache> ModCache,
927 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector = nullptr)
928 : VFS(std::move(VFS)), DiagConsumer(DiagConsumer),
929 ModCache(std::move(ModCache)),
930 ModuleDepCollector(std::move(ModuleDepCollector)) {
931 assert(this->VFS && "Clone config requires non-null VFS");
932 assert(this->ModCache && "Clone config requires non-null ModuleCache");
933 }
934
936 DiagnosticConsumer &getDiagConsumer() const { return DiagConsumer; }
937 std::shared_ptr<ModuleCache> getModuleCache() const { return ModCache; }
938 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const {
939 return ModuleDepCollector;
940 }
941 };
942
943private:
944 /// Find a module, potentially compiling it, before reading its AST. This is
945 /// the guts of loadModule.
946 ///
947 /// For prebuilt modules, the Module is not expected to exist in
948 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
949 /// ModuleManager, then it will be loaded and looked up.
950 ///
951 /// For implicit modules, the Module is expected to already be in the
952 /// ModuleMap. First attempt to load it from the given path on disk. If that
953 /// fails, defer to compileModuleAndReadAST, which will first build and then
954 /// load it.
955 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
956 SourceLocation ImportLoc,
957 SourceRange ModuleNameRange,
958 bool IsInclusionDirective);
959
960 /// Creates a \c CompilerInstance for compiling a module.
961 ///
962 /// This expects a properly initialized \c FrontendInputFile. See
963 /// \c InheritedDirectoryDependencies for \p DirectoryDependencies.
964 std::unique_ptr<CompilerInstance> cloneForModuleCompileImpl(
965 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
966 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
967 ArrayRef<std::string> DirectoryDependencies = {},
968 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
969
970public:
971 /// Creates a new \c CompilerInstance for compiling a module.
972 ///
973 /// This takes care of creating appropriate \c FrontendInputFile for
974 /// public/private frameworks, inferred modules and such.
975 ///
976 /// The \c ThreadSafeConfig takes precedence over the \c DiagnosticConsumer
977 /// and \c FileSystem of this instance (and disables \c FileManager sharing).
978 std::unique_ptr<CompilerInstance> cloneForModuleCompile(
979 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
980 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
981
982 /// Compile a module file for the given module, using the options
983 /// provided by the importing compiler instance. Returns the PCM file in
984 /// a buffer.
985 // FIXME: This should be private, but it's called from static non-member
986 // functions in the implementation file.
987 std::unique_ptr<llvm::MemoryBuffer> compileModule(SourceLocation ImportLoc,
988 StringRef ModuleName,
989 StringRef ModuleFileName,
990 CompilerInstance &Instance);
991
992 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
994 bool IsInclusionDirective) override;
995
996 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
997 StringRef Source) override;
998
1000 SourceLocation ImportLoc) override;
1001
1005
1007
1008 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
1009
1010 void setGenModuleActionWrapper(GenModuleActionWrapperFunc Wrapper) {
1011 GenModuleActionWrapper = Wrapper;
1012 }
1013
1014 GenModuleActionWrapperFunc getGenModuleActionWrapper() const {
1015 return GenModuleActionWrapper;
1016 }
1017
1018 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
1019 DependencyCollectors.push_back(std::move(Listener));
1020 }
1021
1022 void clearDependencyCollectors() { DependencyCollectors.clear(); }
1023
1024 std::vector<std::shared_ptr<DependencyCollector>> &getDependencyCollectors() {
1025 return DependencyCollectors;
1026 }
1027
1029
1030 ModuleCache &getModuleCache() const { return *ModCache; }
1031 std::shared_ptr<ModuleCache> getModuleCachePtr() const { return ModCache; }
1032
1033 /// See \c InheritedDirectoryDependencies.
1035 return InheritedDirectoryDependencies;
1036 }
1038 InheritedDirectoryDependencies.assign(Dirs.begin(), Dirs.end());
1039 }
1040};
1041
1042} // end namespace clang
1043
1044#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:246
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
Stores options for the analyzer from the command line.
The builtins of a target and an optional aux target: their shards, and a hash table from their names ...
Definition Builtins.h:240
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)
const ssaf::SSAFOptions & getSSAFOpts() const
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 ...
bool parseLLVMArgs(llvm::raw_ostream *Errs=nullptr)
Parse the -mllvm options in FrontendOptions::LLVMArgs, setting library options in getLibraryOptions()...
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
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
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
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.
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
ssaf::SSAFOptions & getSSAFOpts()
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
const llvm::cl::LibraryOptionsContext & getLibraryOptions() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
void setInheritedDirectoryDependencies(ArrayRef< std::string > Dirs)
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.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false, bool SetOnlyIfDifferent=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
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
ArrayRef< std::string > getInheritedDirectoryDependencies() const
See InheritedDirectoryDependencies.
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()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
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:240
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:57
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:41
Identifies a module file to be loaded.
Definition Module.h:109
Describes the result of attempting to load a module.
ModuleLoader(bool BuildingModule=false)
Describes a module or submodule.
Definition Module.h:340
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:646
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:863
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:228
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.
Top level wrappers for InstallAPI frontend operations.
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