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