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