23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/MemoryBuffer.h" 25 #include "llvm/Support/Path.h" 26 #include "llvm/Support/raw_ostream.h" 28 #include <system_error> 30 using namespace clang;
36 std::unique_ptr<ASTConsumer>
38 return llvm::make_unique<ASTConsumer>();
41 void InitOnlyAction::ExecuteAction() {
48 std::unique_ptr<ASTConsumer>
50 if (std::unique_ptr<raw_ostream> OS =
56 std::unique_ptr<ASTConsumer>
64 std::unique_ptr<ASTConsumer>
69 std::unique_ptr<ASTConsumer>
74 std::unique_ptr<ASTConsumer>
80 std::unique_ptr<ASTConsumer>
83 if (!ComputeASTConsumerArguments(CI, Sysroot))
86 std::string OutputFile;
87 std::unique_ptr<raw_pwrite_stream> OS =
88 CreateOutputFile(CI, InFile, OutputFile);
95 auto Buffer = std::make_shared<PCHBuffer>();
96 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
97 Consumers.push_back(llvm::make_unique<PCHGenerator>(
104 CI, InFile, OutputFile, std::move(OS), Buffer));
106 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
110 std::string &Sysroot) {
120 std::unique_ptr<llvm::raw_pwrite_stream>
122 std::string &OutputFile) {
126 std::unique_ptr<raw_pwrite_stream> OS =
148 std::unique_ptr<ASTConsumer>
151 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
158 auto Buffer = std::make_shared<PCHBuffer>();
159 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
161 Consumers.push_back(llvm::make_unique<PCHGenerator>(
168 CI, InFile, OutputFile, std::move(OS), Buffer));
169 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
172 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
182 std::unique_ptr<raw_pwrite_stream>
189 if (ModuleMapFile.empty())
190 ModuleMapFile = InFile;
207 bool GenerateModuleInterfaceAction::BeginSourceFileAction(
219 std::unique_ptr<raw_pwrite_stream>
228 std::unique_ptr<ASTConsumer>
230 return llvm::make_unique<ASTConsumer>();
233 std::unique_ptr<ASTConsumer>
236 return llvm::make_unique<ASTConsumer>();
239 std::unique_ptr<ASTConsumer>
241 return llvm::make_unique<ASTConsumer>();
248 std::unique_ptr<ASTReader> Reader(
new ASTReader(
251 Sysroot.empty() ?
"" : Sysroot.c_str(),
268 llvm::raw_ostream &Out;
271 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
273 #define DUMP_BOOLEAN(Value, Text) \ 274 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" 276 bool ReadFullVersionInformation(StringRef FullVersion)
override {
281 <<
" Clang: " << FullVersion <<
"\n";
285 void ReadModuleName(StringRef ModuleName)
override {
286 Out.indent(2) <<
"Module name: " << ModuleName <<
"\n";
288 void ReadModuleMapFile(StringRef ModuleMapPath)
override {
289 Out.indent(2) <<
"Module map file: " << ModuleMapPath <<
"\n";
292 bool ReadLanguageOptions(
const LangOptions &LangOpts,
bool Complain,
293 bool AllowCompatibleDifferences)
override {
294 Out.indent(2) <<
"Language options:\n";
295 #define LANGOPT(Name, Bits, Default, Description) \ 296 DUMP_BOOLEAN(LangOpts.Name, Description); 297 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 298 Out.indent(4) << Description << ": " \ 299 << static_cast<unsigned>(LangOpts.get##Name()) << "\n"; 300 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 301 Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; 302 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 303 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 304 #include "clang/Basic/LangOptions.def" 307 Out.indent(4) <<
"Module features:\n";
309 Out.indent(6) << Feature <<
"\n";
315 bool ReadTargetOptions(
const TargetOptions &TargetOpts,
bool Complain,
316 bool AllowCompatibleDifferences)
override {
317 Out.indent(2) <<
"Target options:\n";
318 Out.indent(4) <<
" Triple: " << TargetOpts.
Triple <<
"\n";
319 Out.indent(4) <<
" CPU: " << TargetOpts.
CPU <<
"\n";
320 Out.indent(4) <<
" ABI: " << TargetOpts.
ABI <<
"\n";
323 Out.indent(4) <<
"Target features:\n";
334 bool Complain)
override {
335 Out.indent(2) <<
"Diagnostic options:\n";
336 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); 337 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 338 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; 339 #define VALUE_DIAGOPT(Name, Bits, Default) \ 340 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; 341 #include "clang/Basic/DiagnosticOptions.def" 343 Out.indent(4) <<
"Diagnostic flags:\n";
344 for (
const std::string &
Warning : DiagOpts->Warnings)
345 Out.indent(6) <<
"-W" << Warning <<
"\n";
346 for (
const std::string &
Remark : DiagOpts->Remarks)
347 Out.indent(6) <<
"-R" << Remark <<
"\n";
353 StringRef SpecificModuleCachePath,
354 bool Complain)
override {
355 Out.indent(2) <<
"Header search options:\n";
356 Out.indent(4) <<
"System root [-isysroot=]: '" << HSOpts.
Sysroot <<
"'\n";
357 Out.indent(4) <<
"Resource dir [ -resource-dir=]: '" << HSOpts.
ResourceDir <<
"'\n";
358 Out.indent(4) <<
"Module Cache: '" << SpecificModuleCachePath <<
"'\n";
360 "Use builtin include directories [-nobuiltininc]");
362 "Use standard system include directories [-nostdinc]");
364 "Use standard C++ include directories [-nostdinc++]");
366 "Use libc++ (rather than libstdc++) [-stdlib=]");
372 std::string &SuggestedPredefines)
override {
373 Out.indent(2) <<
"Preprocessor options:\n";
375 "Uses compiler/target-specific predefines [-undef]");
377 "Uses detailed preprocessing record (for indexing)");
379 if (!PPOpts.
Macros.empty()) {
380 Out.indent(4) <<
"Predefined macros:\n";
383 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
391 Out << I->first <<
"\n";
397 void readModuleFileExtension(
399 Out.indent(2) <<
"Module file extension '" 404 Out.write_escaped(Metadata.
UserInfo);
422 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
424 if (!OutputFileName.empty() && OutputFileName !=
"-") {
426 OutFile.reset(
new llvm::raw_fd_ostream(OutputFileName.str(), EC,
427 llvm::sys::fs::F_Text));
429 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
431 Out <<
"Information for module file '" <<
getCurrentFile() <<
"':\n";
434 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
435 bool IsRaw = (Magic.size() >= 4 && Magic[0] ==
'C' && Magic[1] ==
'P' &&
436 Magic[2] ==
'C' && Magic[3] ==
'H');
437 Out <<
" Module format: " << (IsRaw ?
"raw" :
"obj") <<
"\n";
440 DumpModuleInfoListener Listener(Out);
442 PP.getHeaderSearchInfo().getHeaderSearchOpts();
463 RawLex.LexFromRawLexer(RawTok);
466 llvm::errs() <<
"\n";
467 RawLex.LexFromRawLexer(RawTok);
479 llvm::errs() <<
"\n";
485 std::unique_ptr<raw_pwrite_stream> OS =
522 bool BinaryMode =
true;
523 bool InvalidFile =
false;
528 const char *cur = Buffer->getBufferStart();
529 const char *end = Buffer->getBufferEnd();
530 const char *next = (cur != end) ? cur + 1 : end;
535 if (end - cur > 256) end = cur + 256;
543 }
else if (*cur == 0x0A)
551 std::unique_ptr<raw_ostream> OS =
559 if (Input.isFile()) {
561 OS->write_escaped(Input.getFile());
567 (*OS) <<
"#pragma clang module contents\n";
601 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
std::string OutputFile
The output file, if any.
LangOptions & getLangOpts()
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
PreprocessorOptions & getPreprocessorOpts()
bool shouldEraseOutputFiles() override
Callback at the end of processing a single input, to determine if the output files should be erased o...
std::vector< std::pair< std::string, bool > > Macros
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Defines the clang::FileManager interface and associated types.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
ASTContext & getASTContext() const
Compiling a C++ modules TS module interface unit.
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
Options for controlling the target.
std::unique_ptr< ASTConsumer > CreateASTDumper(StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups)
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Module * getCurrentModule() const
Token - This structure provides full information about a lexed token.
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
const LangOptions & getLangOpts() const
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
static bool ComputeASTConsumerArguments(CompilerInstance &CI, std::string &Sysroot)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
CompilerInstance & getCompilerInstance() const
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
HeaderSearch & getHeaderSearchInfo() const
FrontendOptions & getFrontendOpts()
PreprocessorOutputOptions & getPreprocessorOutputOpts()
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS)
Cache tokens for use with PCH. Note that this requires a seekable stream.
bool BeginInvocation(CompilerInstance &CI) override
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
#define DUMP_BOOLEAN(Value, Text)
HeaderSearchOptions & getHeaderSearchOpts()
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string CurrentModule
The name of the current module, of which the main source file is a part.
virtual bool shouldEraseOutputFiles()
Callback at the end of processing a single input, to determine if the output files should be erased o...
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts)
DoPrintPreprocessedInput - Implement -E mode.
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc...
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
Defines the clang::Preprocessor interface.
InputKind getCurrentFileKind() const
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, StringRef BaseInput, StringRef Extension, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file and add it to the list of tracked output files, optionally deriving the outp...
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::string CPU
If given, the name of the target CPU to generate code for.
SourceManager & getSourceManager() const
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
std::string ABI
If given, the name of the target ABI to use.
File is a PCH file treated as the preamble.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
File is a PCH file treated as such.
unsigned IncludeTimestamps
Whether timestamps should be written to the produced PCH file.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
void Lex(Token &Result)
Lex the next token for this preprocessor.
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
bool isNot(tok::TokenKind K) const
Dataflow Directional Tag Classes.
FileManager & getFileManager() const
Return the current file manager to the caller.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
const FrontendInputFile & getCurrentInput() const
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Reads an AST files chain containing the contents of a translation unit.
FileID getMainFileID() const
Returns the FileID of the main source file.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool ShouldCloseOpenFile=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
virtual std::unique_ptr< ASTConsumer > CreatePCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName, const std::string &OutputFileName, std::unique_ptr< llvm::raw_pwrite_stream > OS, std::shared_ptr< PCHBuffer > Buffer) const =0
Return an ASTConsumer that can be chained with a PCHGenerator that produces a wrapper file format con...
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Abstract interface for callback invocations by the ASTReader.
std::unique_ptr< ASTConsumer > CreateDeclContextPrinter()
~SyntaxOnlyAction() override
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="")
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
std::unique_ptr< ASTConsumer > CreateASTViewer()
Preprocessor & getPreprocessor() const
Return the current preprocessor.
std::unique_ptr< ASTConsumer > CreateASTDeclNodeLister()
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
const StringRef getCurrentFile() const
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions)
Read the control block for the named AST file.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
static std::unique_ptr< llvm::raw_pwrite_stream > CreateOutputFile(CompilerInstance &CI, StringRef InFile, std::string &OutputFile)
Creates file to write the PCH into and returns a stream to write it into.
std::unique_ptr< ASTConsumer > CreateASTPrinter(std::unique_ptr< raw_ostream > OS, StringRef FilterString)
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode...
std::string Triple
The name of the target triple to compile for.
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...