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