LLVM 20.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/SMLoc.h"
30#include "llvm/TableGen/Error.h"
34#include <memory>
35#include <string>
36#include <system_error>
37#include <utility>
38using namespace llvm;
39
41OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
42 cl::init("-"));
43
46 cl::desc("Dependency filename"),
47 cl::value_desc("filename"),
48 cl::init(""));
49
52
54IncludeDirs("I", cl::desc("Directory of include files"),
55 cl::value_desc("directory"), cl::Prefix);
56
58MacroNames("D", cl::desc("Name of the macro to be defined"),
59 cl::value_desc("macro name"), cl::Prefix);
60
61static cl::opt<bool>
62WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
63
64static cl::opt<bool>
65TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
66
68 "no-warn-on-unused-template-args",
69 cl::desc("Disable unused template argument warnings."));
70
71static int reportError(const char *ProgName, Twine Msg) {
72 errs() << ProgName << ": " << Msg;
73 errs().flush();
74 return 1;
75}
76
77/// Create a dependency file for `-d` option.
78///
79/// This functionality is really only for the benefit of the build system.
80/// It is similar to GCC's `-M*` family of options.
81static int createDependencyFile(const TGParser &Parser, const char *argv0) {
82 if (OutputFilename == "-")
83 return reportError(argv0, "the option -d must be used together with -o\n");
84
85 std::error_code EC;
87 if (EC)
88 return reportError(argv0, "error opening " + DependFilename + ":" +
89 EC.message() + "\n");
90 DepOut.os() << OutputFilename << ":";
91 for (const auto &Dep : Parser.getDependencies()) {
92 DepOut.os() << ' ' << Dep;
93 }
94 DepOut.os() << "\n";
95 DepOut.keep();
96 return 0;
97}
98
99int llvm::TableGenMain(const char *argv0,
100 std::function<TableGenMainFn> MainFn) {
101 RecordKeeper Records;
102 TGTimer &Timer = Records.getTimer();
103
104 if (TimePhases)
105 Timer.startPhaseTiming();
106
107 // Parse the input file.
108
109 Timer.startTimer("Parse, build records");
112 if (std::error_code EC = FileOrErr.getError())
113 return reportError(argv0, "Could not open input file '" + InputFilename +
114 "': " + EC.message() + "\n");
115
116 Records.saveInputFilename(InputFilename);
117
118 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
119 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
120
121 // Record the location of the include directory so that the lexer can find
122 // it later.
124
126
127 if (Parser.ParseFile())
128 return 1;
130
131 // Write output to memory.
132 Timer.startBackendTimer("Backend overall");
133 std::string OutString;
134 raw_string_ostream Out(OutString);
135 unsigned status = 0;
136 // ApplyCallback will return true if it did not apply any callback. In that
137 // case, attempt to apply the MainFn.
138 if (TableGen::Emitter::ApplyCallback(Records, Out))
139 status = MainFn ? MainFn(Out, Records) : 1;
140 Timer.stopBackendTimer();
141 if (status)
142 return 1;
143
144 // Always write the depfile, even if the main output hasn't changed.
145 // If it's missing, Ninja considers the output dirty. If this was below
146 // the early exit below and someone deleted the .inc.d file but not the .inc
147 // file, tablegen would never write the depfile.
148 if (!DependFilename.empty()) {
149 if (int Ret = createDependencyFile(Parser, argv0))
150 return Ret;
151 }
152
153 Timer.startTimer("Write output");
154 bool WriteFile = true;
155 if (WriteIfChanged) {
156 // Only updates the real output file if there are any differences.
157 // This prevents recompilation of all the files depending on it if there
158 // aren't any.
159 if (auto ExistingOrErr =
160 MemoryBuffer::getFile(OutputFilename, /*IsText=*/true))
161 if (std::move(ExistingOrErr.get())->getBuffer() == OutString)
162 WriteFile = false;
163 }
164 if (WriteFile) {
165 std::error_code EC;
167 if (EC)
168 return reportError(argv0, "error opening " + OutputFilename + ": " +
169 EC.message() + "\n");
170 OutFile.os() << OutString;
171 if (ErrorsPrinted == 0)
172 OutFile.keep();
173 }
174
176 Timer.stopPhaseTiming();
177
178 if (ErrorsPrinted > 0)
179 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
180 return 0;
181}
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:81
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 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:71
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:23
void setIncludeDirs(const std::vector< std::string > &Dirs)
Definition: SourceMgr.h:106
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:144
const TGLexer::DependenciesSetTy & getDependencies() const
Definition: TGParser.h:197
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
Definition: TGParser.cpp:4401
This class is used to track the amount of time spent between invocations of its startTimer()/stopTime...
Definition: Timer.h:79
void stopTimer()
Stop the timer.
Definition: Timer.cpp:197
void startTimer()
Start the timer running.
Definition: Timer.cpp:190
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:81
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
bool ApplyCallback(const RecordKeeper &Records, raw_ostream &OS)
Apply callback for any command line option registered above.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:758
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
unsigned ErrorsPrinted
Definition: Error.cpp:25
SourceMgr SrcMgr
Definition: Error.cpp:24
int TableGenMain(const char *argv0, std::function< TableGenMainFn > MainFn=nullptr)
Definition: Main.cpp:99
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.