LLVM  14.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 "TGParser.h"
19 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include <algorithm>
27 #include <cstdio>
28 #include <system_error>
29 using namespace llvm;
30 
32 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
33  cl::init("-"));
34 
36 DependFilename("d",
37  cl::desc("Dependency filename"),
38  cl::value_desc("filename"),
39  cl::init(""));
40 
42 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
43 
45 IncludeDirs("I", cl::desc("Directory of include files"),
46  cl::value_desc("directory"), cl::Prefix);
47 
49 MacroNames("D", cl::desc("Name of the macro to be defined"),
50  cl::value_desc("macro name"), cl::Prefix);
51 
52 static cl::opt<bool>
53 WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
54 
55 static cl::opt<bool>
56 TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
57 
58 static int reportError(const char *ProgName, Twine Msg) {
59  errs() << ProgName << ": " << Msg;
60  errs().flush();
61  return 1;
62 }
63 
64 /// Create a dependency file for `-d` option.
65 ///
66 /// This functionality is really only for the benefit of the build system.
67 /// It is similar to GCC's `-M*` family of options.
68 static int createDependencyFile(const TGParser &Parser, const char *argv0) {
69  if (OutputFilename == "-")
70  return reportError(argv0, "the option -d must be used together with -o\n");
71 
72  std::error_code EC;
74  if (EC)
75  return reportError(argv0, "error opening " + DependFilename + ":" +
76  EC.message() + "\n");
77  DepOut.os() << OutputFilename << ":";
78  for (const auto &Dep : Parser.getDependencies()) {
79  DepOut.os() << ' ' << Dep;
80  }
81  DepOut.os() << "\n";
82  DepOut.keep();
83  return 0;
84 }
85 
86 int llvm::TableGenMain(const char *argv0, TableGenMainFn *MainFn) {
87  RecordKeeper Records;
88 
89  if (TimePhases)
90  Records.startPhaseTiming();
91 
92  // Parse the input file.
93 
94  Records.startTimer("Parse, build records");
97  if (std::error_code EC = FileOrErr.getError())
98  return reportError(argv0, "Could not open input file '" + InputFilename +
99  "': " + EC.message() + "\n");
100 
102 
103  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
104  SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
105 
106  // Record the location of the include directory so that the lexer can find
107  // it later.
109 
110  TGParser Parser(SrcMgr, MacroNames, Records);
111 
112  if (Parser.ParseFile())
113  return 1;
114  Records.stopTimer();
115 
116  // Write output to memory.
117  Records.startBackendTimer("Backend overall");
118  std::string OutString;
119  raw_string_ostream Out(OutString);
120  unsigned status = MainFn(Out, Records);
121  Records.stopBackendTimer();
122  if (status)
123  return 1;
124 
125  // Always write the depfile, even if the main output hasn't changed.
126  // If it's missing, Ninja considers the output dirty. If this was below
127  // the early exit below and someone deleted the .inc.d file but not the .inc
128  // file, tablegen would never write the depfile.
129  if (!DependFilename.empty()) {
130  if (int Ret = createDependencyFile(Parser, argv0))
131  return Ret;
132  }
133 
134  Records.startTimer("Write output");
135  bool WriteFile = true;
136  if (WriteIfChanged) {
137  // Only updates the real output file if there are any differences.
138  // This prevents recompilation of all the files depending on it if there
139  // aren't any.
140  if (auto ExistingOrErr =
141  MemoryBuffer::getFile(OutputFilename, /*IsText=*/true))
142  if (std::move(ExistingOrErr.get())->getBuffer() == Out.str())
143  WriteFile = false;
144  }
145  if (WriteFile) {
146  std::error_code EC;
148  if (EC)
149  return reportError(argv0, "error opening " + OutputFilename + ": " +
150  EC.message() + "\n");
151  OutFile.os() << Out.str();
152  if (ErrorsPrinted == 0)
153  OutFile.keep();
154  }
155 
156  Records.stopTimer();
157  Records.stopPhaseTiming();
158 
159  if (ErrorsPrinted > 0)
160  return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
161  return 0;
162 }
MemoryBuffer.h
llvm
This file implements support for optimizing divisions by a constant.
Definition: AllocatorList.h:23
llvm::RecordKeeper
Definition: Record.h:1771
WriteIfChanged
static cl::opt< bool > WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"))
FileSystem.h
llvm::ToolOutputFile
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
Definition: ToolOutputFile.h:26
llvm::cl::Prefix
@ Prefix
Definition: CommandLine.h:164
llvm::TableGenMainFn
bool(raw_ostream &OS, RecordKeeper &Records) TableGenMainFn
Perform the action using Records, and write output to OS.
Definition: Main.h:23
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:625
llvm::ToolOutputFile::keep
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
Definition: ToolOutputFile.h:66
reportError
static int reportError(const char *ProgName, Twine Msg)
Definition: Main.cpp:58
llvm::errs
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Definition: raw_ostream.cpp:893
llvm::MipsISD::Ret
@ Ret
Definition: MipsISelLowering.h:116
llvm::RecordKeeper::startBackendTimer
void startBackendTimer(StringRef Name)
Start timing the overall backend.
Definition: Record.cpp:2709
CommandLine.h
InputFilename
static cl::opt< std::string > InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"))
llvm::RecordKeeper::startTimer
void startTimer(StringRef Name)
Start timing a phase. Automatically stops any previous phase timer.
Definition: Record.cpp:2687
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:246
llvm::SMLoc
Represents a location in source code.
Definition: SMLoc.h:23
llvm::SrcMgr
SourceMgr SrcMgr
Definition: Error.cpp:24
createDependencyFile
static int createDependencyFile(const TGParser &Parser, const char *argv0)
Create a dependency file for -d option.
Definition: Main.cpp:68
llvm::ErrorOr::getError
std::error_code getError() const
Definition: ErrorOr.h:153
llvm::RecordKeeper::stopBackendTimer
void stopBackendTimer()
Stop timing the overall backend.
Definition: Record.cpp:2716
llvm::cl::Positional
@ Positional
Definition: CommandLine.h:163
llvm::raw_ostream::flush
void flush()
Definition: raw_ostream.h:186
llvm::ErrorsPrinted
unsigned ErrorsPrinted
Definition: Error.cpp:25
llvm::RecordKeeper::startPhaseTiming
void startPhaseTiming()
Start phase timing; called if the –time-phases option is specified.
Definition: Record.h:1852
Error.h
llvm::cl::opt
Definition: CommandLine.h:1432
llvm::TGParser
Definition: TGParser.h:130
llvm::sys::fs::OF_Text
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:761
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::MemoryBuffer::getFileOrSTDIN
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Definition: MemoryBuffer.cpp:144
StringExtras.h
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:441
ToolOutputFile.h
MacroNames
static cl::list< std::string > MacroNames("D", cl::desc("Name of the macro to be defined"), cl::value_desc("macro name"), cl::Prefix)
llvm::RecordKeeper::stopPhaseTiming
void stopPhaseTiming()
Stop phase timing and print the report.
Definition: Record.h:1870
IncludeDirs
static cl::list< std::string > IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix)
llvm::TableGenMain
int TableGenMain(const char *argv0, TableGenMainFn *MainFn)
Definition: Main.cpp:86
TimePhases
static cl::opt< bool > TimePhases("time-phases", cl::desc("Time phases of parser and backend"))
llvm::SourceMgr::setIncludeDirs
void setIncludeDirs(const std::vector< std::string > &Dirs)
Definition: SourceMgr.h:103
llvm::RecordKeeper::stopTimer
void stopTimer()
Stop timing a phase.
Definition: Record.cpp:2702
llvm::Twine
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:83
llvm::ToolOutputFile::os
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
Definition: ToolOutputFile.h:59
llvm::TGParser::getDependencies
const TGLexer::DependenciesSetTy & getDependencies() const
Definition: TGParser.h:179
llvm::SourceMgr::AddNewSourceBuffer
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:141
llvm::cl::value_desc
Definition: CommandLine.h:422
Main.h
TGParser.h
llvm::RecordKeeper::saveInputFilename
void saveInputFilename(std::string Filename)
Definition: Record.h:1824
OutputFilename
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
llvm::sys::fs::status
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
llvm::ErrorOr
Represents either an error or a value T.
Definition: ErrorOr.h:56
llvm::cl::desc
Definition: CommandLine.h:412
llvm::raw_string_ostream::str
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
Definition: raw_ostream.h:643
Record.h
llvm::TGParser::ParseFile
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
Definition: TGParser.cpp:3720
DependFilename
static cl::opt< std::string > DependFilename("d", cl::desc("Dependency filename"), cl::value_desc("filename"), cl::init(""))
llvm::cl::list
Definition: CommandLine.h:1640