LLVM 22.0.0git
Main.cpp
Go to the documentation of this file.
1//===- Main.cpp - Top-Level TableGen implementation -----------------------===//
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// TableGen is a tool which can be used to build up a description of something,
10// then invoke one or more "tablegen backends" to emit information about the
11// description in some predefined format. In practice, this is used by the LLVM
12// code generators to automate generation of a code generator through a
13// high-level description of the target.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/TableGen/Main.h"
18#include "TGLexer.h"
19#include "TGParser.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/SMLoc.h"
32#include "llvm/TableGen/Error.h"
36#include <memory>
37#include <string>
38#include <system_error>
39#include <utility>
40using namespace llvm;
41
43OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
44 cl::init("-"));
45
48 cl::desc("Dependency filename"),
49 cl::value_desc("filename"),
50 cl::init(""));
51
54
56IncludeDirs("I", cl::desc("Directory of include files"),
57 cl::value_desc("directory"), cl::Prefix);
58
60MacroNames("D", cl::desc("Name of the macro to be defined"),
61 cl::value_desc("macro name"), cl::Prefix);
62
63static cl::opt<bool>
64WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
65
66static cl::opt<bool>
67TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
68
70 "long-string-literals",
71 cl::desc("when emitting large string tables, prefer string literals over "
72 "comma-separated char literals. This can be a readability and "
73 "compile-time performance win, but upsets some compilers"),
74 cl::Hidden, cl::init(true));
75
77 "no-warn-on-unused-template-args",
78 cl::desc("Disable unused template argument warnings."));
79
80static int reportError(const char *ProgName, Twine Msg) {
81 errs() << ProgName << ": " << Msg;
82 errs().flush();
83 return 1;
84}
85
86/// Create a dependency file for `-d` option.
87///
88/// This functionality is really only for the benefit of the build system.
89/// It is similar to GCC's `-M*` family of options.
90static int createDependencyFile(const TGParser &Parser, const char *argv0) {
91 if (OutputFilename == "-")
92 return reportError(argv0, "the option -d must be used together with -o\n");
93
94 std::error_code EC;
96 if (EC)
97 return reportError(argv0, "error opening " + DependFilename + ":" +
98 EC.message() + "\n");
99 DepOut.os() << OutputFilename << ":";
100 for (const auto &Dep : Parser.getDependencies()) {
101 DepOut.os() << ' ' << Dep;
102 }
103 DepOut.os() << "\n";
104 DepOut.keep();
105 return 0;
106}
107
108static int WriteOutput(const TGParser &Parser, const char *argv0,
109 StringRef Filename, StringRef Content) {
110 if (WriteIfChanged) {
111 // Only updates the real output file if there are any differences.
112 // This prevents recompilation of all the files depending on it if there
113 // aren't any.
114 if (auto ExistingOrErr = MemoryBuffer::getFile(Filename, /*IsText=*/true))
115 if (std::move(ExistingOrErr.get())->getBuffer() == Content)
116 return 0;
117 }
118 std::error_code EC;
119 ToolOutputFile OutFile(Filename, EC, sys::fs::OF_Text);
120 if (EC)
121 return reportError(argv0, "error opening " + Filename + ": " +
122 EC.message() + "\n");
123 OutFile.os() << Content;
124 if (ErrorsPrinted == 0)
125 OutFile.keep();
126
127 return 0;
128}
129
130int llvm::TableGenMain(const char *argv0, MultiFileTableGenMainFn MainFn) {
131 RecordKeeper Records;
132 TGTimer &Timer = Records.getTimer();
133
134 if (TimePhases)
135 Timer.startPhaseTiming();
136
137 // Parse the input file.
138
139 Timer.startTimer("Parse, build records");
142 if (std::error_code EC = FileOrErr.getError())
143 return reportError(argv0, "Could not open input file '" + InputFilename +
144 "': " + EC.message() + "\n");
145
146 Records.saveInputFilename(InputFilename);
147
148 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
149 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
150
151 // Record the location of the include directory so that the lexer can find
152 // it later.
153 SrcMgr.setIncludeDirs(IncludeDirs);
154 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
155
157
158 if (Parser.ParseFile())
159 return 1;
161
162 // Return early if any other errors were generated during parsing
163 // (e.g., assert failures).
164 if (ErrorsPrinted > 0)
165 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
166
167 // Write output to memory.
168 Timer.startBackendTimer("Backend overall");
169 TableGenOutputFiles OutFiles;
170 unsigned status = 0;
171 // ApplyCallback will return true if it did not apply any callback. In that
172 // case, attempt to apply the MainFn.
174 if (TableGen::Emitter::ApplyCallback(Records, OutFiles, FilenamePrefix))
175 status = MainFn ? MainFn(OutFiles, Records) : 1;
176 Timer.stopBackendTimer();
177 if (status)
178 return 1;
179
180 // Always write the depfile, even if the main output hasn't changed.
181 // If it's missing, Ninja considers the output dirty. If this was below
182 // the early exit below and someone deleted the .inc.d file but not the .inc
183 // file, tablegen would never write the depfile.
184 if (!DependFilename.empty()) {
185 if (int Ret = createDependencyFile(Parser, argv0))
186 return Ret;
187 }
188
189 Timer.startTimer("Write output");
190 if (int Ret = WriteOutput(Parser, argv0, OutputFilename, OutFiles.MainFile))
191 return Ret;
192 for (auto [Suffix, Content] : OutFiles.AdditionalFiles) {
194 // TODO: Format using the split-file convention when writing to stdout?
195 if (Filename != "-") {
196 sys::path::replace_extension(Filename, "");
197 Filename.append(Suffix);
198 }
199 if (int Ret = WriteOutput(Parser, argv0, Filename, Content))
200 return Ret;
201 }
202
204 Timer.stopPhaseTiming();
205
206 if (ErrorsPrinted > 0)
207 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
208 return 0;
209}
210
211int llvm::TableGenMain(const char *argv0, TableGenMainFn MainFn) {
212 return TableGenMain(argv0, [&MainFn](TableGenOutputFiles &OutFiles,
213 const RecordKeeper &Records) {
214 std::string S;
215 raw_string_ostream OS(S);
216 int Res = MainFn(OS, Records);
217 OutFiles = {S, {}};
218 return Res;
219 });
220}
Provides ErrorOr<T> smart pointer.
static cl::opt< bool > NoWarnOnUnusedTemplateArgs("no-warn-on-unused-template-args", cl::desc("Disable unused template argument warnings."))
static cl::list< std::string > IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix)
static int createDependencyFile(const TGParser &Parser, const char *argv0)
Create a dependency file for -d option.
Definition Main.cpp:90
static cl::opt< bool > WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"))
static cl::opt< std::string > DependFilename("d", cl::desc("Dependency filename"), cl::value_desc("filename"), cl::init(""))
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
static cl::opt< bool > TimePhases("time-phases", cl::desc("Time phases of parser and backend"))
static int WriteOutput(const TGParser &Parser, const char *argv0, StringRef Filename, StringRef Content)
Definition Main.cpp:108
static cl::opt< std::string > InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"))
static cl::list< std::string > MacroNames("D", cl::desc("Name of the macro to be defined"), cl::value_desc("macro name"), cl::Prefix)
static int reportError(const char *ProgName, Twine Msg)
Definition Main.cpp:80
Defines the virtual file system interface vfs::FileSystem.
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Represents a location in source code.
Definition SMLoc.h:22
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
const TGLexer::DependenciesSetTy & getDependencies() const
Definition TGParser.h:193
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
This class is used to track the amount of time spent between invocations of its startTimer()/stopTime...
Definition Timer.h:87
LLVM_ABI void stopTimer()
Stop the timer.
Definition Timer.cpp:159
LLVM_ABI void startTimer()
Start the timer running.
Definition Timer.cpp:150
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
A raw_ostream that writes to an std::string.
bool ApplyCallback(const RecordKeeper &Records, TableGenOutputFiles &OutFiles, StringRef FilenamePrefix)
Apply callback for any command line option registered above.
initializer< Ty > init(const Ty &Val)
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:755
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:579
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition Path.cpp:480
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
unsigned ErrorsPrinted
Definition Error.cpp:25
function_ref< bool(TableGenOutputFiles &OutFiles, const RecordKeeper &Records)> MultiFileTableGenMainFn
Perform the action using Records, and store output in OutFiles.
Definition Main.h:37
function_ref< bool(raw_ostream &OS, const RecordKeeper &Records)> TableGenMainFn
Returns true on error, false otherwise.
Definition Main.h:32
cl::opt< bool > EmitLongStrLiterals
Controls emitting large character arrays as strings or character arrays.
SourceMgr SrcMgr
Definition Error.cpp:24
int TableGenMain(const char *argv0, TableGenMainFn MainFn=nullptr)
Definition Main.cpp:211
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::map< StringRef, std::string > AdditionalFiles
Definition Main.h:28
std::string MainFile
Definition Main.h:25