LLVM 24.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 <set>
38#include <string>
39#include <system_error>
40#include <utility>
41using namespace llvm;
42
44OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
45 cl::init("-"));
46
49 cl::desc("Dependency filename"),
50 cl::value_desc("filename"),
51 cl::init(""));
52
55
57IncludeDirs("I", cl::desc("Directory of include files"),
58 cl::value_desc("directory"), cl::Prefix);
59
61MacroNames("D", cl::desc("Name of the macro to be defined"),
62 cl::value_desc("macro name"), cl::Prefix);
63
64static cl::opt<bool>
65WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
66
67static cl::opt<bool>
68TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
69
71 "long-string-literals",
72 cl::desc("when emitting large string tables, prefer string literals over "
73 "comma-separated char literals. This can be a readability and "
74 "compile-time performance win, but upsets some compilers"),
75 cl::Hidden, cl::init(true));
76
78 "no-warn-on-unused-template-args",
79 cl::desc("Disable unused template argument warnings."));
80
81static cl::opt<bool> Preprocess("E", cl::desc("Write preprocessed output"));
82
83static int reportError(const char *ProgName, Twine Msg) {
84 errs() << ProgName << ": " << Msg;
85 errs().flush();
86 return 1;
87}
88
89namespace {
90/// Encapsulate file, line and column numbers from SourceMgr.
91struct SMCoords {
92 unsigned Buf = 0;
93 unsigned Line = 0;
94 unsigned Col = 0;
95 SMCoords() = default;
96 SMCoords(const SourceMgr &Mgr, SMLoc Loc) {
97 Buf = Mgr.FindBufferContainingLoc(Loc);
98 // TODO: Find a faster way to do this. For example we don't need the column
99 // number for every token, only the first token on each output line.
100 std::tie(Line, Col) = Mgr.getLineAndColumn(Loc, Buf);
101 }
102};
103} // end anonymous namespace
104
105/// Create preprocessed output for `-E` option.
106static int preprocessInput(TGLexer &Lex, raw_ostream &OS) {
107 SMCoords Last;
108 while (true) {
109 Lex.Lex();
110 if (Lex.getCode() == tgtok::Eof || Lex.getCode() == tgtok::Error)
111 break;
112 SMCoords This(SrcMgr, Lex.getLoc());
113 if (This.Buf == Last.Buf && This.Line == Last.Line) {
114 // Add a single space between tokens on the same line. This is overkill in
115 // many cases but at least it will parse correctly.
116 OS << ' ';
117 } else {
118 // Always start a new line when including a new file or popping back out
119 // to the previous file. This is just a heuristic to make the output look
120 // reasonably pretty.
121 if (Last.Buf)
122 OS << '\n';
123 // Indent the first token on a line to its original indentation, to make
124 // the output look pretty.
125 OS.indent(This.Col - 1);
126 }
127
128 const char *Start = Lex.getLoc().getPointer();
129 const char *End = Lex.getLocRange().End.getPointer();
130 StringRef Text(Start, End - Start);
131 OS << Text;
132
133 Last = This;
134 // A code block is the only kind of token that can span multiple lines.
135 // Record the line it ends on, so that a following token on that line stays
136 // on the same output line. Count '\n' characters to match how SourceMgr
137 // counts lines.
138 if (Lex.getCode() == tgtok::CodeFragment)
139 Last.Line += Text.count('\n');
140 }
141 if (Last.Buf != 0)
142 OS << '\n';
143 return Lex.getCode() == tgtok::Error;
144}
145
146/// Create a dependency file for `-d` option.
147///
148/// This functionality is really only for the benefit of the build system.
149/// It is similar to GCC's `-M*` family of options.
150static int createDependencyFile(const char *argv0) {
151 if (OutputFilename == "-")
152 return reportError(argv0, "the option -d must be used together with -o\n");
153
154 std::error_code EC;
156 if (EC)
157 return reportError(argv0, "error opening " + DependFilename + ":" +
158 EC.message() + "\n");
159 DepOut.os() << OutputFilename << ":";
160
161 // Emit the primary input file as a dependency. This matches C compilers like
162 // Clang and GCC. Without it, a .td file with no `include` directives would
163 // produce a depfile listing zero dependencies. CMake's
164 // `cmake_transform_depfile` then collapses that to a 0-byte file, which Ninja
165 // treats as a missing depfile and re-runs the rule on every incremental
166 // build.
167 if (InputFilename != "-")
168 DepOut.os() << ' ' << InputFilename;
169
170 // Every other buffer in SrcMgr was added by an include directive, and its
171 // identifier is the path that the include resolved to. Buffer 1 is the main
172 // file. Use a set to sort the list and remove duplicates.
173 std::set<std::string> Dependencies;
174 for (unsigned I = 2, E = SrcMgr.getNumBuffers(); I <= E; ++I)
175 Dependencies.insert(SrcMgr.getMemoryBuffer(I)->getBufferIdentifier().str());
176 for (const std::string &Dep : Dependencies)
177 DepOut.os() << ' ' << Dep;
178 DepOut.os() << "\n";
179 DepOut.keep();
180 return 0;
181}
182
183static int WriteOutput(const char *argv0, StringRef Filename,
184 StringRef Content) {
185 if (WriteIfChanged) {
186 // Only updates the real output file if there are any differences.
187 // This prevents recompilation of all the files depending on it if there
188 // aren't any.
189 if (auto ExistingOrErr = MemoryBuffer::getFile(Filename, /*IsText=*/true))
190 if (std::move(ExistingOrErr.get())->getBuffer() == Content)
191 return 0;
192 }
193 std::error_code EC;
194 // On z/OS, text files default to IBM-1047, but generated files are UTF-8.
195 // OF_ForceUTF8 has no effect on other platforms.
196 ToolOutputFile OutFile(Filename, EC,
198 if (EC)
199 return reportError(argv0, "error opening " + Filename + ": " +
200 EC.message() + "\n");
201 OutFile.os() << Content;
202 if (ErrorsPrinted == 0)
203 OutFile.keep();
204
205 return 0;
206}
207
208int llvm::TableGenMain(const char *argv0, MultiFileTableGenMainFn MainFn) {
211 if (std::error_code EC = FileOrErr.getError())
212 return reportError(argv0, "Could not open input file '" + InputFilename +
213 "': " + EC.message() + "\n");
214
215 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
216 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
217
218 // Record the location of the include directory so that the lexer can find
219 // it later.
220 SrcMgr.setIncludeDirs(IncludeDirs);
221 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
222
223 if (Preprocess) {
225 std::string OutString;
226 raw_string_ostream Out(OutString);
227 if (int Ret = preprocessInput(Lex, Out))
228 return Ret;
229 // Return early if the lexer printed errors but still reached EOF (e.g., a
230 // NUL character in the source).
231 if (ErrorsPrinted > 0)
232 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
233 if (!DependFilename.empty()) {
234 if (int Ret = createDependencyFile(argv0))
235 return Ret;
236 }
237 return WriteOutput(argv0, OutputFilename, OutString);
238 }
239
240 RecordKeeper Records;
241 Records.saveInputFilename(InputFilename);
242
243 TGTimer &Timer = Records.getTimer();
244 if (TimePhases)
245 Timer.startPhaseTiming();
246
247 // Parse the input file.
248
249 Timer.startTimer("Parse, build records");
250
252
253 if (Parser.ParseFile())
254 return 1;
256
257 // Return early if any other errors were generated during parsing
258 // (e.g., assert failures).
259 if (ErrorsPrinted > 0)
260 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
261
262 // Write output to memory.
263 Timer.startBackendTimer("Backend overall");
264 TableGenOutputFiles OutFiles;
265 unsigned status = 0;
266 // ApplyCallback will return true if it did not apply any callback. In that
267 // case, attempt to apply the MainFn.
269 if (TableGen::Emitter::ApplyCallback(Records, OutFiles, FilenamePrefix))
270 status = MainFn ? MainFn(OutFiles, Records) : 1;
271 Timer.stopBackendTimer();
272 if (status)
273 return 1;
274
275 // Always write the depfile, even if the main output hasn't changed.
276 // If it's missing, Ninja considers the output dirty. If this was below
277 // the early exit below and someone deleted the .inc.d file but not the .inc
278 // file, tablegen would never write the depfile.
279 if (!DependFilename.empty()) {
280 if (int Ret = createDependencyFile(argv0))
281 return Ret;
282 }
283
284 Timer.startTimer("Write output");
285 if (int Ret = WriteOutput(argv0, OutputFilename, OutFiles.MainFile))
286 return Ret;
287 for (auto [Suffix, Content] : OutFiles.AdditionalFiles) {
289 // TODO: Format using the split-file convention when writing to stdout?
290 if (Filename != "-") {
292 Filename.append(Suffix);
293 }
294 if (int Ret = WriteOutput(argv0, Filename, Content))
295 return Ret;
296 }
297
299 Timer.stopPhaseTiming();
300
301 if (ErrorsPrinted > 0)
302 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
303 return 0;
304}
305
306int llvm::TableGenMain(const char *argv0, TableGenMainFn MainFn) {
307 return TableGenMain(argv0, [&MainFn](TableGenOutputFiles &OutFiles,
308 const RecordKeeper &Records) {
309 std::string S;
310 raw_string_ostream OS(S);
311 int Res = MainFn(OS, Records);
312 OutFiles = {std::move(S), {}};
313 return Res;
314 });
315}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Provides ErrorOr<T> smart pointer.
#define I(x, y, z)
Definition MD5.cpp:57
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 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 createDependencyFile(const char *argv0)
Create a dependency file for -d option.
Definition Main.cpp:150
static int preprocessInput(TGLexer &Lex, raw_ostream &OS)
Create preprocessed output for -E option.
Definition Main.cpp:106
static cl::opt< std::string > InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"))
static int WriteOutput(const char *argv0, StringRef Filename, StringRef Content)
Definition Main.cpp:183
static cl::list< std::string > MacroNames("D", cl::desc("Name of the macro to be defined"), cl::value_desc("macro name"), cl::Prefix)
static cl::opt< bool > Preprocess("E", cl::desc("Write preprocessed output"))
static int reportError(const char *ProgName, Twine Msg)
Definition Main.cpp:83
static constexpr StringLiteral Filename
const char * Msg
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
constexpr const char * getPointer() const
Definition SMLoc.h:33
SMLoc End
Definition SMLoc.h:49
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
LLVM_ABI std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file.
LLVM_ABI unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition SourceMgr.cpp:97
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TGLexer - TableGen Lexer class.
Definition TGLexer.h:193
SMRange getLocRange() const
Definition TGLexer.cpp:97
tgtok::TokKind Lex()
Definition TGLexer.h:212
tgtok::TokKind getCode() const
Definition TGLexer.h:214
SMLoc getLoc() const
Definition TGLexer.cpp:95
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
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI 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:793
@ OF_ForceUTF8
The file should be tagged as UTF-8 rather than the default IBM-1047 encoding.
Definition FileSystem.h:832
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:596
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:491
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.
LLVM_ABI 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
LLVM_ABI cl::opt< bool > EmitLongStrLiterals
Controls emitting large character arrays as strings or character arrays.
LLVM_ABI SourceMgr SrcMgr
Definition Error.cpp:24
LLVM_ABI int TableGenMain(const char *argv0, TableGenMainFn MainFn=nullptr)
Definition Main.cpp:306
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
std::map< StringRef, std::string > AdditionalFiles
Definition Main.h:28
std::string MainFile
Definition Main.h:25