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 /// At the end of a compilation, print the number of warnings/errors.
230
231 /// Load the list of plugins requested in the \c FrontendOptions.
233
234 /// @}
235 /// @name Compiler Invocation and Options
236 /// @{
237
238 bool hasInvocation() const { return Invocation != nullptr; }
239
241 assert(Invocation && "Compiler instance has no invocation!");
242 return *Invocation;
243 }
244
245 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
246
247 /// setInvocation - Replace the current invocation.
248 void setInvocation(std::shared_ptr<CompilerInvocation> Value);
249
250 /// Indicates whether we should (re)build the global module index.
251 bool shouldBuildGlobalModuleIndex() const;
252
253 /// Set the flag indicating whether we should (re)build the global
254 /// module index.
255 void setBuildGlobalModuleIndex(bool Build) {
256 BuildGlobalModuleIndex = Build;
257 }
258
259 /// @}
260 /// @name Forwarding Methods
261 /// @{
262
263 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
264
266 return Invocation->getCodeGenOpts();
267 }
269 return Invocation->getCodeGenOpts();
270 }
271
273 return Invocation->getDependencyOutputOpts();
274 }
276 return Invocation->getDependencyOutputOpts();
277 }
278
280 return Invocation->getDiagnosticOpts();
281 }
283 return Invocation->getDiagnosticOpts();
284 }
285
287 return Invocation->getFileSystemOpts();
288 }
290 return Invocation->getFileSystemOpts();
291 }
292
294 return Invocation->getFrontendOpts();
295 }
297 return Invocation->getFrontendOpts();
298 }
299
301 return Invocation->getHeaderSearchOpts();
302 }
304 return Invocation->getHeaderSearchOpts();
305 }
306 std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const {
307 return Invocation->getHeaderSearchOptsPtr();
308 }
309
310 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
312 return Invocation->getAPINotesOpts();
313 }
314
315 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
316 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
317 std::shared_ptr<LangOptions> getLangOptsPtr() const {
318 return Invocation->getLangOptsPtr();
319 }
320
322 return Invocation->getPreprocessorOpts();
323 }
325 return Invocation->getPreprocessorOpts();
326 }
327
329 return Invocation->getPreprocessorOutputOpts();
330 }
332 return Invocation->getPreprocessorOutputOpts();
333 }
334
336 return Invocation->getTargetOpts();
337 }
339 return Invocation->getTargetOpts();
340 }
341
342 /// @}
343 /// @name Diagnostics Engine
344 /// @{
345
346 bool hasDiagnostics() const { return Diagnostics != nullptr; }
347
348 /// Get the current diagnostics engine.
350 assert(Diagnostics && "Compiler instance has no diagnostics!");
351 return *Diagnostics;
352 }
353
355 assert(Diagnostics && "Compiler instance has no diagnostics!");
356 return Diagnostics;
357 }
358
359 /// setDiagnostics - Replace the current diagnostics engine.
361
363 assert(Diagnostics && Diagnostics->getClient() &&
364 "Compiler instance has no diagnostic client!");
365 return *Diagnostics->getClient();
366 }
367
368 /// @}
369 /// @name VerboseOutputStream
370 /// @{
371
372 /// Replace the current stream for verbose output.
373 void setVerboseOutputStream(raw_ostream &Value);
374
375 /// Replace the current stream for verbose output.
376 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
377
378 /// Get the current stream for verbose output.
379 raw_ostream &getVerboseOutputStream() {
380 return *VerboseOutputStream;
381 }
382
383 /// @}
384 /// @name Target Info
385 /// @{
386
387 bool hasTarget() const { return Target != nullptr; }
388
390 assert(Target && "Compiler instance has no target!");
391 return *Target;
392 }
393
395 assert(Target && "Compiler instance has no target!");
396 return Target;
397 }
398
399 /// Replace the current Target.
401
402 /// @}
403 /// @name AuxTarget Info
404 /// @{
405
406 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
407
408 /// Replace the current AuxTarget.
410
411 // Create Target and AuxTarget based on current options
412 bool createTarget();
413
414 /// @}
415 /// @name Virtual File System
416 /// @{
417
418 llvm::vfs::FileSystem &getVirtualFileSystem() const;
419
420 /// @}
421 /// @name File Manager
422 /// @{
423
424 bool hasFileManager() const { return FileMgr != nullptr; }
425
426 /// Return the current file manager to the caller.
428 assert(FileMgr && "Compiler instance has no file manager!");
429 return *FileMgr;
430 }
431
433 assert(FileMgr && "Compiler instance has no file manager!");
434 return FileMgr;
435 }
436
438 llvm::BuryPointer(FileMgr.get());
439 FileMgr.resetWithoutRelease();
440 }
441
442 /// Replace the current file manager and virtual file system.
444
445 /// @}
446 /// @name Source Manager
447 /// @{
448
449 bool hasSourceManager() const { return SourceMgr != nullptr; }
450
451 /// Return the current source manager.
453 assert(SourceMgr && "Compiler instance has no source manager!");
454 return *SourceMgr;
455 }
456
458 assert(SourceMgr && "Compiler instance has no source manager!");
459 return SourceMgr;
460 }
461
463 llvm::BuryPointer(SourceMgr.get());
464 SourceMgr.resetWithoutRelease();
465 }
466
467 /// setSourceManager - Replace the current source manager.
469
470 /// @}
471 /// @name Preprocessor
472 /// @{
473
474 bool hasPreprocessor() const { return PP != nullptr; }
475
476 /// Return the current preprocessor.
478 assert(PP && "Compiler instance has no preprocessor!");
479 return *PP;
480 }
481
482 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
483
485 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
486 }
487
488 /// Replace the current preprocessor.
489 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
490
491 /// @}
492 /// @name ASTContext
493 /// @{
494
495 bool hasASTContext() const { return Context != nullptr; }
496
498 assert(Context && "Compiler instance has no AST context!");
499 return *Context;
500 }
501
503 assert(Context && "Compiler instance has no AST context!");
504 return Context;
505 }
506
508 llvm::BuryPointer(Context.get());
509 Context.resetWithoutRelease();
510 }
511
512 /// setASTContext - Replace the current AST context.
514
515 /// Replace the current Sema; the compiler instance takes ownership
516 /// of S.
517 void setSema(Sema *S);
518
519 /// @}
520 /// @name ASTConsumer
521 /// @{
522
523 bool hasASTConsumer() const { return (bool)Consumer; }
524
526 assert(Consumer && "Compiler instance has no AST consumer!");
527 return *Consumer;
528 }
529
530 /// takeASTConsumer - Remove the current AST consumer and give ownership to
531 /// the caller.
532 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
533
534 /// setASTConsumer - Replace the current AST consumer; the compiler instance
535 /// takes ownership of \p Value.
536 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
537
538 /// @}
539 /// @name Semantic analysis
540 /// @{
541 bool hasSema() const { return (bool)TheSema; }
542
543 Sema &getSema() const {
544 assert(TheSema && "Compiler instance has no Sema object!");
545 return *TheSema;
546 }
547
548 std::unique_ptr<Sema> takeSema();
549 void resetAndLeakSema();
550
551 /// @}
552 /// @name Module Management
553 /// @{
554
557
558 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
560 std::shared_ptr<ModuleDependencyCollector> Collector);
561
562 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
563 return ThePCHContainerOperations;
564 }
565
566 /// Return the appropriate PCHContainerWriter depending on the
567 /// current CodeGenOptions.
569 assert(Invocation && "cannot determine module format without invocation");
570 StringRef Format = getHeaderSearchOpts().ModuleFormat;
571 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
572 if (!Writer) {
573 if (Diagnostics)
574 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
575 llvm::report_fatal_error("unknown module format");
576 }
577 return *Writer;
578 }
579
580 /// Return the appropriate PCHContainerReader depending on the
581 /// current CodeGenOptions.
583 assert(Invocation && "cannot determine module format without invocation");
584 StringRef Format = getHeaderSearchOpts().ModuleFormat;
585 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
586 if (!Reader) {
587 if (Diagnostics)
588 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
589 llvm::report_fatal_error("unknown module format");
590 }
591 return *Reader;
592 }
593
594 /// @}
595 /// @name Code Completion
596 /// @{
597
598 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
599
601 assert(CompletionConsumer &&
602 "Compiler instance has no code completion consumer!");
603 return *CompletionConsumer;
604 }
605
606 /// setCodeCompletionConsumer - Replace the current code completion consumer;
607 /// the compiler instance takes ownership of \p Value.
609
610 /// @}
611 /// @name Frontend timer
612 /// @{
613
614 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
615
616 llvm::Timer &getFrontendTimer() const {
617 assert(FrontendTimer && "Compiler instance has no frontend timer!");
618 return *FrontendTimer;
619 }
620
621 /// @}
622 /// @name Output Files
623 /// @{
624
625 /// clearOutputFiles - Clear the output file list. The underlying output
626 /// streams must have been closed beforehand.
627 ///
628 /// \param EraseFiles - If true, attempt to erase the files from disk.
629 void clearOutputFiles(bool EraseFiles);
630
631 /// @}
632 /// @name Construction Utility Methods
633 /// @{
634
635 /// Create the diagnostics engine using the invocation's diagnostic options
636 /// and replace any existing one with it.
637 ///
638 /// Note that this routine also replaces the diagnostic client,
639 /// allocating one if one is not provided.
640 ///
641 /// \param Client If non-NULL, a diagnostic client that will be
642 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
643 /// unit.
644 ///
645 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
646 /// the diagnostic object should take ownership of the client.
647 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
648 bool ShouldOwnClient = true);
649
650 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
651 ///
652 /// If no diagnostic client is provided, this creates a
653 /// DiagnosticConsumer that is owned by the returned diagnostic
654 /// object, if using directly the caller is responsible for
655 /// releasing the returned DiagnosticsEngine's client eventually.
656 ///
657 /// \param Opts - The diagnostic options; note that the created text
658 /// diagnostic object contains a reference to these options.
659 ///
660 /// \param Client If non-NULL, a diagnostic client that will be
661 /// attached to (and, then, owned by) the returned DiagnosticsEngine
662 /// object.
663 ///
664 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
665 /// used by some diagnostics printers (for logging purposes only).
666 ///
667 /// \return The new object on success, or null on failure.
670 DiagnosticConsumer *Client = nullptr,
671 bool ShouldOwnClient = true,
672 const CodeGenOptions *CodeGenOpts = nullptr);
673
674 /// Create the file manager and replace any existing one with it.
675 ///
676 /// \return The new file manager on success, or null on failure.
679
680 /// Create the source manager and replace any existing one with it.
681 void createSourceManager(FileManager &FileMgr);
682
683 /// Create the preprocessor, using the invocation, file, and source managers,
684 /// and replace any existing one with it.
686
687 std::string getSpecificModuleCachePath(StringRef ModuleHash);
689 return getSpecificModuleCachePath(getInvocation().getModuleHash());
690 }
691
692 /// Create the AST context.
693 void createASTContext();
694
695 /// Create an external AST source to read a PCH file and attach it to the AST
696 /// context.
698 StringRef Path, DisableValidationForModuleKind DisableValidation,
699 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
700 bool OwnDeserializationListener);
701
702 /// Create an external AST source to read a PCH file.
703 ///
704 /// \return - The new object on success, or null on failure.
706 StringRef Path, StringRef Sysroot,
707 DisableValidationForModuleKind DisableValidation,
708 bool AllowPCHWithCompilerErrors, Preprocessor &PP,
709 InMemoryModuleCache &ModuleCache, ASTContext &Context,
710 const PCHContainerReader &PCHContainerRdr,
711 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
712 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
713 void *DeserializationListener, bool OwnDeserializationListener,
714 bool Preamble, bool UseGlobalModuleIndex);
715
716 /// Create a code completion consumer using the invocation; note that this
717 /// will cause the source manager to truncate the input source file at the
718 /// completion point.
720
721 /// Create a code completion consumer to print code completion results, at
722 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
724 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
725 const CodeCompleteOptions &Opts, raw_ostream &OS);
726
727 /// Create the Sema object to be used for parsing.
729 CodeCompleteConsumer *CompletionConsumer);
730
731 /// Create the frontend timer and replace any existing one with it.
732 void createFrontendTimer();
733
734 /// Create the default output file (from the invocation's options) and add it
735 /// to the list of tracked output files.
736 ///
737 /// The files created by this are usually removed on signal, and, depending
738 /// on FrontendOptions, may also use a temporary file (that is, the data is
739 /// written to a temporary file which will atomically replace the target
740 /// output on success).
741 ///
742 /// \return - Null on error.
743 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
744 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
745 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
746 bool ForceUseTemporary = false);
747
748 /// Create a new output file, optionally deriving the output path name, and
749 /// add it to the list of tracked output files.
750 ///
751 /// \return - Null on error.
752 std::unique_ptr<raw_pwrite_stream>
753 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
754 bool UseTemporary, bool CreateMissingDirectories = false);
755
756private:
757 /// Create a new output file and add it to the list of tracked output files.
758 ///
759 /// If \p OutputPath is empty, then createOutputFile will derive an output
760 /// path location as \p BaseInput, with any suffix removed, and \p Extension
761 /// appended. If \p OutputPath is not stdout and \p UseTemporary
762 /// is true, createOutputFile will create a new temporary file that must be
763 /// renamed to \p OutputPath in the end.
764 ///
765 /// \param OutputPath - If given, the path to the output file.
766 /// \param Binary - The mode to open the file in.
767 /// \param RemoveFileOnSignal - Whether the file should be registered with
768 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
769 /// multithreaded use, as the underlying signal mechanism is not reentrant
770 /// \param UseTemporary - Create a new temporary file that must be renamed to
771 /// OutputPath in the end.
772 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
773 /// missing directories in the output path.
775 createOutputFileImpl(StringRef OutputPath, bool Binary,
776 bool RemoveFileOnSignal, bool UseTemporary,
777 bool CreateMissingDirectories);
778
779public:
780 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
781
782 /// @}
783 /// @name Initialization Utility Methods
784 /// @{
785
786 /// InitializeSourceManager - Initialize the source manager to set InputFile
787 /// as the main file.
788 ///
789 /// \return True on success.
791
792 /// InitializeSourceManager - Initialize the source manager to set InputFile
793 /// as the main file.
794 ///
795 /// \return True on success.
796 static bool InitializeSourceManager(const FrontendInputFile &Input,
797 DiagnosticsEngine &Diags,
798 FileManager &FileMgr,
799 SourceManager &SourceMgr);
800
801 /// @}
802
803 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
804 OutputStream = std::move(OutStream);
805 }
806
807 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
808 return std::move(OutputStream);
809 }
810
811 void createASTReader();
812
813 bool loadModuleFile(StringRef FileName,
814 serialization::ModuleFile *&LoadedModuleFile);
815
816private:
817 /// Find a module, potentially compiling it, before reading its AST. This is
818 /// the guts of loadModule.
819 ///
820 /// For prebuilt modules, the Module is not expected to exist in
821 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
822 /// ModuleManager, then it will be loaded and looked up.
823 ///
824 /// For implicit modules, the Module is expected to already be in the
825 /// ModuleMap. First attempt to load it from the given path on disk. If that
826 /// fails, defer to compileModuleAndReadAST, which will first build and then
827 /// load it.
828 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
829 SourceLocation ImportLoc,
830 SourceLocation ModuleNameLoc,
831 bool IsInclusionDirective);
832
833public:
836 bool IsInclusionDirective) override;
837
838 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
839 StringRef Source) override;
840
842 SourceLocation ImportLoc) override;
843
846 }
847
849
850 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
851
852 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
853 DependencyCollectors.push_back(std::move(Listener));
854 }
855
857
858 InMemoryModuleCache &getModuleCache() const { return *ModuleCache; }
859};
860
861} // end namespace clang
862
863#endif
Defines the Diagnostic-related interfaces.
StringRef Filename
Definition: Format.cpp:2952
llvm::MachO::Target Target
Definition: MachO.h:40
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()
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)
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 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 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.
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:426
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:213
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.
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:982
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