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 "TGParser.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/ToolOutputFile.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include <algorithm>
26 #include <system_error>
27 using namespace llvm;
28
29 static cl::opt<std::string>
30 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
31 cl::init("-"));
32
33 static cl::opt<std::string>
34 DependFilename("d",
35 cl::desc("Dependency filename"),
36 cl::value_desc("filename"),
37 cl::init(""));
38
39 static cl::opt<std::string>
40 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
41
42 static cl::list<std::string>
43 IncludeDirs("I", cl::desc("Directory of include files"),
44 cl::value_desc("directory"), cl::Prefix);
45
46 static cl::list<std::string>
47 MacroNames("D", cl::desc("Name of the macro to be defined"),
48 cl::value_desc("macro name"), cl::Prefix);
49
50 static cl::opt<bool>
51 WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
52
53 static cl::opt<bool>
54 TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
55
56 static cl::opt<bool> NoWarnOnUnusedTemplateArgs(
57 "no-warn-on-unused-template-args",
58 cl::desc("Disable unused template argument warnings."));
59
reportError(const char * ProgName,Twine Msg)60 static int reportError(const char *ProgName, Twine Msg) {
61 errs() << ProgName << ": " << Msg;
62 errs().flush();
63 return 1;
64 }
65
66 /// Create a dependency file for `-d` option.
67 ///
68 /// This functionality is really only for the benefit of the build system.
69 /// It is similar to GCC's `-M*` family of options.
createDependencyFile(const TGParser & Parser,const char * argv0)70 static int createDependencyFile(const TGParser &Parser, const char *argv0) {
71 if (OutputFilename == "-")
72 return reportError(argv0, "the option -d must be used together with -o\n");
73
74 std::error_code EC;
75 ToolOutputFile DepOut(DependFilename, EC, sys::fs::OF_Text);
76 if (EC)
77 return reportError(argv0, "error opening " + DependFilename + ":" +
78 EC.message() + "\n");
79 DepOut.os() << OutputFilename << ":";
80 for (const auto &Dep : Parser.getDependencies()) {
81 DepOut.os() << ' ' << Dep;
82 }
83 DepOut.os() << "\n";
84 DepOut.keep();
85 return 0;
86 }
87
TableGenMain(const char * argv0,TableGenMainFn * MainFn)88 int llvm::TableGenMain(const char *argv0, TableGenMainFn *MainFn) {
89 RecordKeeper Records;
90
91 if (TimePhases)
92 Records.startPhaseTiming();
93
94 // Parse the input file.
95
96 Records.startTimer("Parse, build records");
97 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
98 MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true);
99 if (std::error_code EC = FileOrErr.getError())
100 return reportError(argv0, "Could not open input file '" + InputFilename +
101 "': " + EC.message() + "\n");
102
103 Records.saveInputFilename(InputFilename);
104
105 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
106 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
107
108 // Record the location of the include directory so that the lexer can find
109 // it later.
110 SrcMgr.setIncludeDirs(IncludeDirs);
111
112 TGParser Parser(SrcMgr, MacroNames, Records, NoWarnOnUnusedTemplateArgs);
113
114 if (Parser.ParseFile())
115 return 1;
116 Records.stopTimer();
117
118 // Write output to memory.
119 Records.startBackendTimer("Backend overall");
120 std::string OutString;
121 raw_string_ostream Out(OutString);
122 unsigned status = MainFn(Out, Records);
123 Records.stopBackendTimer();
124 if (status)
125 return 1;
126
127 // Always write the depfile, even if the main output hasn't changed.
128 // If it's missing, Ninja considers the output dirty. If this was below
129 // the early exit below and someone deleted the .inc.d file but not the .inc
130 // file, tablegen would never write the depfile.
131 if (!DependFilename.empty()) {
132 if (int Ret = createDependencyFile(Parser, argv0))
133 return Ret;
134 }
135
136 Records.startTimer("Write output");
137 bool WriteFile = true;
138 if (WriteIfChanged) {
139 // Only updates the real output file if there are any differences.
140 // This prevents recompilation of all the files depending on it if there
141 // aren't any.
142 if (auto ExistingOrErr =
143 MemoryBuffer::getFile(OutputFilename, /*IsText=*/true))
144 if (std::move(ExistingOrErr.get())->getBuffer() == Out.str())
145 WriteFile = false;
146 }
147 if (WriteFile) {
148 std::error_code EC;
149 ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_Text);
150 if (EC)
151 return reportError(argv0, "error opening " + OutputFilename + ": " +
152 EC.message() + "\n");
153 OutFile.os() << Out.str();
154 if (ErrorsPrinted == 0)
155 OutFile.keep();
156 }
157
158 Records.stopTimer();
159 Records.stopPhaseTiming();
160
161 if (ErrorsPrinted > 0)
162 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
163 return 0;
164 }
165