clang 20.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
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/IntrusiveRefCntPtr.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/Support/BuryPointer.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/VirtualFileSystem.h"
28#include <cassert>
29#include <list>
30#include <memory>
31#include <optional>
32#include <string>
33#include <utility>
34
35namespace llvm {
36class raw_fd_ostream;
37class Timer;
38class TimerGroup;
39}
40
41namespace clang {
42class ASTContext;
43class ASTReader;
44
45namespace serialization {
46class ModuleFile;
47}
48
49class CodeCompleteConsumer;
50class DiagnosticsEngine;
51class DiagnosticConsumer;
52class FileManager;
53class FrontendAction;
54class InMemoryModuleCache;
55class Module;
56class Preprocessor;
57class Sema;
58class SourceManager;
59class TargetInfo;
61
62/// CompilerInstance - Helper class for managing a single instance of the Clang
63/// compiler.
64///
65/// The CompilerInstance serves two purposes:
66/// (1) It manages the various objects which are necessary to run the compiler,
67/// for example the preprocessor, the target information, and the AST
68/// context.
69/// (2) It provides utility routines for constructing and manipulating the
70/// common Clang objects.
71///
72/// The compiler instance generally owns the instance of all the objects that it
73/// manages. However, clients can still share objects by manually setting the
74/// object and retaking ownership prior to destroying the CompilerInstance.
75///
76/// The compiler instance is intended to simplify clients, but not to lock them
77/// in to the compiler instance for everything. When possible, utility functions
78/// come in two forms; a short form that reuses the CompilerInstance objects,
79/// and a long form that takes explicit instances of any required objects.
81 /// The options used in this compiler instance.
82 std::shared_ptr<CompilerInvocation> Invocation;
83
84 /// The diagnostics engine instance.
86
87 /// The target being compiled for.
89
90 /// Auxiliary Target info.
92
93 /// The file manager.
95
96 /// The source manager.
98
99 /// The cache of PCM files.
101
102 /// The preprocessor.
103 std::shared_ptr<Preprocessor> PP;
104
105 /// The AST context.
107
108 /// An optional sema source that will be attached to sema.
110
111 /// The AST consumer.
112 std::unique_ptr<ASTConsumer> Consumer;
113
114 /// The code completion consumer.
115 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
116
117 /// The semantic analysis object.
118 std::unique_ptr<Sema> TheSema;
119
120 /// The frontend timer group.
121 std::unique_ptr<llvm::TimerGroup> FrontendTimerGroup;
122
123 /// The frontend timer.
124 std::unique_ptr<llvm::Timer> FrontendTimer;
125
126 /// The ASTReader, if one exists.
128
129 /// The module dependency collector for crashdumps
130 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
131
132 /// The module provider.
133 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
134
135 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
136
137 /// Records the set of modules
138 class FailedModulesSet {
139 llvm::StringSet<> Failed;
140
141 public:
142 bool hasAlreadyFailed(StringRef module) { return Failed.count(module) > 0; }
143
144 void addFailed(StringRef module) { Failed.insert(module); }
145 };
146
147 /// The set of modules that failed to build.
148 ///
149 /// This pointer will be shared among all of the compiler instances created
150 /// to (re)build modules, so that once a module fails to build anywhere,
151 /// other instances will see that the module has failed and won't try to
152 /// build it again.
153 std::shared_ptr<FailedModulesSet> FailedModules;
154
155 /// The set of top-level modules that has already been built on the
156 /// fly as part of this overall compilation action.
157 std::map<std::string, std::string, std::less<>> BuiltModules;
158
159 /// Should we delete the BuiltModules when we're done?
160 bool DeleteBuiltModules = true;
161
162 /// The location of the module-import keyword for the last module
163 /// import.
164 SourceLocation LastModuleImportLoc;
165
166 /// The result of the last module import.
167 ///
168 ModuleLoadResult LastModuleImportResult;
169
170 /// Whether we should (re)build the global module index once we
171 /// have finished with this translation unit.
172 bool BuildGlobalModuleIndex = false;
173
174 /// We have a full global module index, with all modules.
175 bool HaveFullGlobalModuleIndex = false;
176
177 /// One or more modules failed to build.
178 bool DisableGeneratingGlobalModuleIndex = false;
179
180 /// The stream for verbose output if owned, otherwise nullptr.
181 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
182
183 /// The stream for verbose output.
184 raw_ostream *VerboseOutputStream = &llvm::errs();
185
186 /// Holds information about the output file.
187 ///
188 /// If TempFilename is not empty we must rename it to Filename at the end.
189 /// TempFilename may be empty and Filename non-empty if creating the temporary
190 /// failed.
191 struct OutputFile {
192 std::string Filename;
193 std::optional<llvm::sys::fs::TempFile> File;
194
195 OutputFile(std::string filename,
196 std::optional<llvm::sys::fs::TempFile> file)
197 : Filename(std::move(filename)), File(std::move(file)) {}
198 };
199
200 /// The list of active output files.
201 std::list<OutputFile> OutputFiles;
202
203 /// Force an output buffer.
204 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
205
206 CompilerInstance(const CompilerInstance &) = delete;
207 void operator=(const CompilerInstance &) = delete;
208public:
209 explicit CompilerInstance(
210 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
211 std::make_shared<PCHContainerOperations>(),
212 InMemoryModuleCache *SharedModuleCache = nullptr);
213 ~CompilerInstance() override;
214
215 /// @name High-Level Operations
216 /// @{
217
218 /// ExecuteAction - Execute the provided action against the compiler's
219 /// CompilerInvocation object.
220 ///
221 /// This function makes the following assumptions:
222 ///
223 /// - The invocation options should be initialized. This function does not
224 /// handle the '-help' or '-version' options, clients should handle those
225 /// directly.
226 ///
227 /// - The diagnostics engine should have already been created by the client.
228 ///
229 /// - No other CompilerInstance state should have been initialized (this is
230 /// an unchecked error).
231 ///
232 /// - Clients should have initialized any LLVM target features that may be
233 /// required.
234 ///
235 /// - Clients should eventually call llvm_shutdown() upon the completion of
236 /// this routine to ensure that any managed objects are properly destroyed.
237 ///
238 /// Note that this routine may write output to 'stderr'.
239 ///
240 /// \param Act - The action to execute.
241 /// \return - True on success.
242 //
243 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
244 // of the context or else not CompilerInstance specific.
245 bool ExecuteAction(FrontendAction &Act);
246
247 /// At the end of a compilation, print the number of warnings/errors.
249
250 /// Load the list of plugins requested in the \c FrontendOptions.
252
253 /// @}
254 /// @name Compiler Invocation and Options
255 /// @{
256
257 bool hasInvocation() const { return Invocation != nullptr; }
258
260 assert(Invocation && "Compiler instance has no invocation!");
261 return *Invocation;
262 }
263
264 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
265
266 /// setInvocation - Replace the current invocation.
267 void setInvocation(std::shared_ptr<CompilerInvocation> Value);
268
269 /// Indicates whether we should (re)build the global module index.
270 bool shouldBuildGlobalModuleIndex() const;
271
272 /// Set the flag indicating whether we should (re)build the global
273 /// module index.
274 void setBuildGlobalModuleIndex(bool Build) {
275 BuildGlobalModuleIndex = Build;
276 }
277
278 /// @}
279 /// @name Forwarding Methods
280 /// @{
281
282 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
283
285 return Invocation->getCodeGenOpts();
286 }
288 return Invocation->getCodeGenOpts();
289 }
290
292 return Invocation->getDependencyOutputOpts();
293 }
295 return Invocation->getDependencyOutputOpts();
296 }
297
299 return Invocation->getDiagnosticOpts();
300 }
302 return Invocation->getDiagnosticOpts();
303 }
304
306 return Invocation->getFileSystemOpts();
307 }
309 return Invocation->getFileSystemOpts();
310 }
311
313 return Invocation->getFrontendOpts();
314 }
316 return Invocation->getFrontendOpts();
317 }
318
320 return Invocation->getHeaderSearchOpts();
321 }
323 return Invocation->getHeaderSearchOpts();
324 }
325 std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const {
326 return Invocation->getHeaderSearchOptsPtr();
327 }
328
329 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
331 return Invocation->getAPINotesOpts();
332 }
333
334 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
335 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
336 std::shared_ptr<LangOptions> getLangOptsPtr() const {
337 return Invocation->getLangOptsPtr();
338 }
339
341 return Invocation->getPreprocessorOpts();
342 }
344 return Invocation->getPreprocessorOpts();
345 }
346
348 return Invocation->getPreprocessorOutputOpts();
349 }
351 return Invocation->getPreprocessorOutputOpts();
352 }
353
355 return Invocation->getTargetOpts();
356 }
358 return Invocation->getTargetOpts();
359 }
360
361 /// @}
362 /// @name Diagnostics Engine
363 /// @{
364
365 bool hasDiagnostics() const { return Diagnostics != nullptr; }
366
367 /// Get the current diagnostics engine.
369 assert(Diagnostics && "Compiler instance has no diagnostics!");
370 return *Diagnostics;
371 }
372
374 assert(Diagnostics && "Compiler instance has no diagnostics!");
375 return Diagnostics;
376 }
377
378 /// setDiagnostics - Replace the current diagnostics engine.
380
382 assert(Diagnostics && Diagnostics->getClient() &&
383 "Compiler instance has no diagnostic client!");
384 return *Diagnostics->getClient();
385 }
386
387 /// @}
388 /// @name VerboseOutputStream
389 /// @{
390
391 /// Replace the current stream for verbose output.
392 void setVerboseOutputStream(raw_ostream &Value);
393
394 /// Replace the current stream for verbose output.
395 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
396
397 /// Get the current stream for verbose output.
398 raw_ostream &getVerboseOutputStream() {
399 return *VerboseOutputStream;
400 }
401
402 /// @}
403 /// @name Target Info
404 /// @{
405
406 bool hasTarget() const { return Target != nullptr; }
407
409 assert(Target && "Compiler instance has no target!");
410 return *Target;
411 }
412
414 assert(Target && "Compiler instance has no target!");
415 return Target;
416 }
417
418 /// Replace the current Target.
420
421 /// @}
422 /// @name AuxTarget Info
423 /// @{
424
425 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
426
427 /// Replace the current AuxTarget.
429
430 // Create Target and AuxTarget based on current options
431 bool createTarget();
432
433 /// @}
434 /// @name Virtual File System
435 /// @{
436
437 llvm::vfs::FileSystem &getVirtualFileSystem() const;
438
439 /// @}
440 /// @name File Manager
441 /// @{
442
443 bool hasFileManager() const { return FileMgr != nullptr; }
444
445 /// Return the current file manager to the caller.
447 assert(FileMgr && "Compiler instance has no file manager!");
448 return *FileMgr;
449 }
450
452 assert(FileMgr && "Compiler instance has no file manager!");
453 return FileMgr;
454 }
455
457 llvm::BuryPointer(FileMgr.get());
458 FileMgr.resetWithoutRelease();
459 }
460
461 /// Replace the current file manager and virtual file system.
463
464 /// @}
465 /// @name Source Manager
466 /// @{
467
468 bool hasSourceManager() const { return SourceMgr != nullptr; }
469
470 /// Return the current source manager.
472 assert(SourceMgr && "Compiler instance has no source manager!");
473 return *SourceMgr;
474 }
475
477 assert(SourceMgr && "Compiler instance has no source manager!");
478 return SourceMgr;
479 }
480
482 llvm::BuryPointer(SourceMgr.get());
483 SourceMgr.resetWithoutRelease();
484 }
485
486 /// setSourceManager - Replace the current source manager.
488
489 /// @}
490 /// @name Preprocessor
491 /// @{
492
493 bool hasPreprocessor() const { return PP != nullptr; }
494
495 /// Return the current preprocessor.
497 assert(PP && "Compiler instance has no preprocessor!");
498 return *PP;
499 }
500
501 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
502
504 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
505 }
506
507 /// Replace the current preprocessor.
508 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
509
510 /// @}
511 /// @name ASTContext
512 /// @{
513
514 bool hasASTContext() const { return Context != nullptr; }
515
517 assert(Context && "Compiler instance has no AST context!");
518 return *Context;
519 }
520
522 assert(Context && "Compiler instance has no AST context!");
523 return Context;
524 }
525
527 llvm::BuryPointer(Context.get());
528 Context.resetWithoutRelease();
529 }
530
531 /// setASTContext - Replace the current AST context.
533
534 /// Replace the current Sema; the compiler instance takes ownership
535 /// of S.
536 void setSema(Sema *S);
537
538 /// @}
539 /// @name ASTConsumer
540 /// @{
541
542 bool hasASTConsumer() const { return (bool)Consumer; }
543
545 assert(Consumer && "Compiler instance has no AST consumer!");
546 return *Consumer;
547 }
548
549 /// takeASTConsumer - Remove the current AST consumer and give ownership to
550 /// the caller.
551 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
552
553 /// setASTConsumer - Replace the current AST consumer; the compiler instance
554 /// takes ownership of \p Value.
555 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
556
557 /// @}
558 /// @name Semantic analysis
559 /// @{
560 bool hasSema() const { return (bool)TheSema; }
561
562 Sema &getSema() const {
563 assert(TheSema && "Compiler instance has no Sema object!");
564 return *TheSema;
565 }
566
567 std::unique_ptr<Sema> takeSema();
568 void resetAndLeakSema();
569
570 /// @}
571 /// @name Module Management
572 /// @{
573
576
577 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
579 std::shared_ptr<ModuleDependencyCollector> Collector);
580
581 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
582 return ThePCHContainerOperations;
583 }
584
585 /// Return the appropriate PCHContainerWriter depending on the
586 /// current CodeGenOptions.
588 assert(Invocation && "cannot determine module format without invocation");
589 StringRef Format = getHeaderSearchOpts().ModuleFormat;
590 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
591 if (!Writer) {
592 if (Diagnostics)
593 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
594 llvm::report_fatal_error("unknown module format");
595 }
596 return *Writer;
597 }
598
599 /// Return the appropriate PCHContainerReader depending on the
600 /// current CodeGenOptions.
602 assert(Invocation && "cannot determine module format without invocation");
603 StringRef Format = getHeaderSearchOpts().ModuleFormat;
604 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
605 if (!Reader) {
606 if (Diagnostics)
607 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
608 llvm::report_fatal_error("unknown module format");
609 }
610 return *Reader;
611 }
612
613 /// @}
614 /// @name Code Completion
615 /// @{
616
617 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
618
620 assert(CompletionConsumer &&
621 "Compiler instance has no code completion consumer!");
622 return *CompletionConsumer;
623 }
624
625 /// setCodeCompletionConsumer - Replace the current code completion consumer;
626 /// the compiler instance takes ownership of \p Value.
628
629 /// @}
630 /// @name Frontend timer
631 /// @{
632
633 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
634
635 llvm::Timer &getFrontendTimer() const {
636 assert(FrontendTimer && "Compiler instance has no frontend timer!");
637 return *FrontendTimer;
638 }
639
640 /// @}
641 /// @name Failed modules set
642 /// @{
643
644 bool hasFailedModulesSet() const { return (bool)FailedModules; }
645
647 FailedModules = std::make_shared<FailedModulesSet>();
648 }
649
650 std::shared_ptr<FailedModulesSet> getFailedModulesSetPtr() const {
651 return FailedModules;
652 }
653
654 void setFailedModulesSet(std::shared_ptr<FailedModulesSet> FMS) {
655 FailedModules = FMS;
656 }
657
658 /// }
659 /// @name Output Files
660 /// @{
661
662 /// clearOutputFiles - Clear the output file list. The underlying output
663 /// streams must have been closed beforehand.
664 ///
665 /// \param EraseFiles - If true, attempt to erase the files from disk.
666 void clearOutputFiles(bool EraseFiles);
667
668 /// @}
669 /// @name Construction Utility Methods
670 /// @{
671
672 /// Create the diagnostics engine using the invocation's diagnostic options
673 /// and replace any existing one with it.
674 ///
675 /// Note that this routine also replaces the diagnostic client,
676 /// allocating one if one is not provided.
677 ///
678 /// \param VFS is used for any IO needed when creating DiagnosticsEngine. It
679 /// doesn't replace VFS in the CompilerInstance (if any).
680 ///
681 /// \param Client If non-NULL, a diagnostic client that will be
682 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
683 /// unit.
684 ///
685 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
686 /// the diagnostic object should take ownership of the client.
687 void createDiagnostics(llvm::vfs::FileSystem &VFS,
688 DiagnosticConsumer *Client = nullptr,
689 bool ShouldOwnClient = true);
690
691 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
692 ///
693 /// If no diagnostic client is provided, this creates a
694 /// DiagnosticConsumer that is owned by the returned diagnostic
695 /// object, if using directly the caller is responsible for
696 /// releasing the returned DiagnosticsEngine's client eventually.
697 ///
698 /// \param Opts - The diagnostic options; note that the created text
699 /// diagnostic object contains a reference to these options.
700 ///
701 /// \param Client If non-NULL, a diagnostic client that will be
702 /// attached to (and, then, owned by) the returned DiagnosticsEngine
703 /// object.
704 ///
705 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
706 /// used by some diagnostics printers (for logging purposes only).
707 ///
708 /// \return The new object on success, or null on failure.
710 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions *Opts,
711 DiagnosticConsumer *Client = nullptr,
712 bool ShouldOwnClient = true,
713 const CodeGenOptions *CodeGenOpts = nullptr);
714
715 /// Create the file manager and replace any existing one with it.
716 ///
717 /// \return The new file manager on success, or null on failure.
720
721 /// Create the source manager and replace any existing one with it.
722 void createSourceManager(FileManager &FileMgr);
723
724 /// Create the preprocessor, using the invocation, file, and source managers,
725 /// and replace any existing one with it.
727
728 std::string getSpecificModuleCachePath(StringRef ModuleHash);
730 return getSpecificModuleCachePath(getInvocation().getModuleHash());
731 }
732
733 /// Create the AST context.
734 void createASTContext();
735
736 /// Create an external AST source to read a PCH file and attach it to the AST
737 /// context.
739 StringRef Path, DisableValidationForModuleKind DisableValidation,
740 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
741 bool OwnDeserializationListener);
742
743 /// Create an external AST source to read a PCH file.
744 ///
745 /// \return - The new object on success, or null on failure.
747 StringRef Path, StringRef Sysroot,
748 DisableValidationForModuleKind DisableValidation,
749 bool AllowPCHWithCompilerErrors, Preprocessor &PP,
750 InMemoryModuleCache &ModuleCache, ASTContext &Context,
751 const PCHContainerReader &PCHContainerRdr,
752 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
753 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
754 void *DeserializationListener, bool OwnDeserializationListener,
755 bool Preamble, bool UseGlobalModuleIndex);
756
757 /// Create a code completion consumer using the invocation; note that this
758 /// will cause the source manager to truncate the input source file at the
759 /// completion point.
761
762 /// Create a code completion consumer to print code completion results, at
763 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
765 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
766 const CodeCompleteOptions &Opts, raw_ostream &OS);
767
768 /// Create the Sema object to be used for parsing.
770 CodeCompleteConsumer *CompletionConsumer);
771
772 /// Create the frontend timer and replace any existing one with it.
773 void createFrontendTimer();
774
775 /// Create the default output file (from the invocation's options) and add it
776 /// to the list of tracked output files.
777 ///
778 /// The files created by this are usually removed on signal, and, depending
779 /// on FrontendOptions, may also use a temporary file (that is, the data is
780 /// written to a temporary file which will atomically replace the target
781 /// output on success).
782 ///
783 /// \return - Null on error.
784 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
785 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
786 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
787 bool ForceUseTemporary = false);
788
789 /// Create a new output file, optionally deriving the output path name, and
790 /// add it to the list of tracked output files.
791 ///
792 /// \return - Null on error.
793 std::unique_ptr<raw_pwrite_stream>
794 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
795 bool UseTemporary, bool CreateMissingDirectories = false);
796
797private:
798 /// Create a new output file and add it to the list of tracked output files.
799 ///
800 /// If \p OutputPath is empty, then createOutputFile will derive an output
801 /// path location as \p BaseInput, with any suffix removed, and \p Extension
802 /// appended. If \p OutputPath is not stdout and \p UseTemporary
803 /// is true, createOutputFile will create a new temporary file that must be
804 /// renamed to \p OutputPath in the end.
805 ///
806 /// \param OutputPath - If given, the path to the output file.
807 /// \param Binary - The mode to open the file in.
808 /// \param RemoveFileOnSignal - Whether the file should be registered with
809 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
810 /// multithreaded use, as the underlying signal mechanism is not reentrant
811 /// \param UseTemporary - Create a new temporary file that must be renamed to
812 /// OutputPath in the end.
813 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
814 /// missing directories in the output path.
816 createOutputFileImpl(StringRef OutputPath, bool Binary,
817 bool RemoveFileOnSignal, bool UseTemporary,
818 bool CreateMissingDirectories);
819
820public:
821 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
822
823 /// @}
824 /// @name Initialization Utility Methods
825 /// @{
826
827 /// InitializeSourceManager - Initialize the source manager to set InputFile
828 /// as the main file.
829 ///
830 /// \return True on success.
832
833 /// InitializeSourceManager - Initialize the source manager to set InputFile
834 /// as the main file.
835 ///
836 /// \return True on success.
837 static bool InitializeSourceManager(const FrontendInputFile &Input,
838 DiagnosticsEngine &Diags,
839 FileManager &FileMgr,
840 SourceManager &SourceMgr);
841
842 /// @}
843
844 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
845 OutputStream = std::move(OutStream);
846 }
847
848 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
849 return std::move(OutputStream);
850 }
851
852 void createASTReader();
853
854 bool loadModuleFile(StringRef FileName,
855 serialization::ModuleFile *&LoadedModuleFile);
856
857private:
858 /// Find a module, potentially compiling it, before reading its AST. This is
859 /// the guts of loadModule.
860 ///
861 /// For prebuilt modules, the Module is not expected to exist in
862 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
863 /// ModuleManager, then it will be loaded and looked up.
864 ///
865 /// For implicit modules, the Module is expected to already be in the
866 /// ModuleMap. First attempt to load it from the given path on disk. If that
867 /// fails, defer to compileModuleAndReadAST, which will first build and then
868 /// load it.
869 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
870 SourceLocation ImportLoc,
871 SourceLocation ModuleNameLoc,
872 bool IsInclusionDirective);
873
874public:
877 bool IsInclusionDirective) override;
878
879 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
880 StringRef Source) override;
881
883 SourceLocation ImportLoc) override;
884
887 }
888
890
891 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
892
893 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
894 DependencyCollectors.push_back(std::move(Listener));
895 }
896
898
899 InMemoryModuleCache &getModuleCache() const { return *ModuleCache; }
900};
901
902} // end namespace clang
903
904#endif
Defines the Diagnostic-related interfaces.
IndirectLocalPath & Path
StringRef Filename
Definition: Format.cpp:3032
llvm::MachO::Target Target
Definition: MachO.h:51
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:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
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...
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
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 createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
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.
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)
void createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
const DiagnosticOptions & getDiagnosticOpts() const
std::string getSpecificModuleCachePath()
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
void setInvocation(std::shared_ptr< CompilerInvocation > Value)
setInvocation - Replace the current invocation.
std::shared_ptr< FailedModulesSet > getFailedModulesSetPtr() const
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 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
std::unique_ptr< Sema > takeSema()
const PreprocessorOptions & getPreprocessorOpts() const
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
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< LangOptions > getLangOptsPtr() const
InMemoryModuleCache & getModuleCache() 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.
std::shared_ptr< HeaderSearchOptions > getHeaderSearchOptsPtr() const
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
void setFailedModulesSet(std::shared_ptr< FailedModulesSet > FMS)
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
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.
HeaderSearchOptions & getHeaderSearchOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
void setDiagnostics(DiagnosticsEngine *Value)
setDiagnostics - Replace the current diagnostics engine.
bool hasCodeCompletionConsumer() const
const LangOptions & getLangOpts() const
bool hasFailedModulesSet() const
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
TargetInfo & getTarget() const
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()
LangOptions & getLangOpts()
const APINotesOptions & getAPINotesOpts() const
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr() const
CodeCompleteConsumer & getCodeCompletionConsumer() const
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
APINotesOptions & getAPINotesOpts()
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool loadModuleFile(StringRef FileName, serialization::ModuleFile *&LoadedModuleFile)
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
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...
Definition: Diagnostic.h:1684
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
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.
In-memory cache for modules.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
Describes the result of attempting to load a module.
Definition: ModuleLoader.h:35
Abstract interface for a module loader.
Definition: ModuleLoader.h:82
Describes a module or submodule.
Definition: Module.h:115
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:414
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.
Definition: Preprocessor.h:138
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Exposes information about the current target.
Definition: TargetInfo.h:220
Options for controlling the target.
Definition: TargetOptions.h:26
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:130
Defines the clang::TargetInfo interface.
@ ModuleFile
The module file (.pcm). Required.
The JSON file list parser is used to communicate input to InstallAPI.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1096
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