1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
|
//===-- llvm-cgdata.cpp - LLVM CodeGen Data Tool --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// llvm-cgdata parses raw codegen data embedded in compiled binary files, and
// merges them into a single .cgdata file. It can also inspect and maninuplate
// a .cgdata file. This .cgdata can contain various codegen data like outlining
// information, and it can be used to optimize the code in the subsequent build.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include "llvm/CGData/CodeGenDataReader.h"
#include "llvm/CGData/CodeGenDataWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/Binary.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/LLVMDriver.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/WithColor.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
enum CGDataFormat {
Invalid,
Text,
Binary,
};
enum CGDataAction {
Convert,
Merge,
Show,
};
// Command-line option boilerplate.
namespace {
enum ID {
OPT_INVALID = 0, // This is not an option ID.
#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
#include "Opts.inc"
#undef OPTION
};
#define OPTTABLE_STR_TABLE_CODE
#include "Opts.inc"
#undef OPTTABLE_STR_TABLE_CODE
#define OPTTABLE_PREFIXES_TABLE_CODE
#include "Opts.inc"
#undef OPTTABLE_PREFIXES_TABLE_CODE
using namespace llvm::opt;
static constexpr opt::OptTable::Info InfoTable[] = {
#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
#include "Opts.inc"
#undef OPTION
};
class CGDataOptTable : public opt::GenericOptTable {
public:
CGDataOptTable()
: GenericOptTable(OptionStrTable, OptionPrefixesTable, InfoTable) {}
};
} // end anonymous namespace
// Options
static StringRef ToolName;
static StringRef OutputFilename = "-";
static StringRef Filename;
static bool ShowCGDataVersion;
static bool SkipTrim;
static CGDataAction Action;
static std::optional<CGDataFormat> OutputFormat;
static std::vector<std::string> InputFilenames;
static void exitWithError(Twine Message, StringRef Whence = "",
StringRef Hint = "") {
WithColor::error();
if (!Whence.empty())
errs() << Whence << ": ";
errs() << Message << "\n";
if (!Hint.empty())
WithColor::note() << Hint << "\n";
::exit(1);
}
static void exitWithError(Error E, StringRef Whence = "") {
if (E.isA<CGDataError>()) {
handleAllErrors(std::move(E), [&](const CGDataError &IPE) {
exitWithError(IPE.message(), Whence);
});
return;
}
exitWithError(toString(std::move(E)), Whence);
}
static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
exitWithError(EC.message(), Whence);
}
static int convert_main(int argc, const char *argv[]) {
std::error_code EC;
raw_fd_ostream OS(OutputFilename, EC,
OutputFormat == CGDataFormat::Text
? sys::fs::OF_TextWithCRLF
: sys::fs::OF_None);
if (EC)
exitWithErrorCode(EC, OutputFilename);
auto FS = vfs::getRealFileSystem();
auto ReaderOrErr = CodeGenDataReader::create(Filename, *FS);
if (Error E = ReaderOrErr.takeError())
exitWithError(std::move(E), Filename);
CodeGenDataWriter Writer;
auto Reader = ReaderOrErr->get();
if (Reader->hasOutlinedHashTree()) {
OutlinedHashTreeRecord Record(Reader->releaseOutlinedHashTree());
Writer.addRecord(Record);
}
if (Reader->hasStableFunctionMap()) {
StableFunctionMapRecord Record(Reader->releaseStableFunctionMap());
Writer.addRecord(Record);
}
if (OutputFormat == CGDataFormat::Text) {
if (Error E = Writer.writeText(OS))
exitWithError(std::move(E));
} else {
if (Error E = Writer.write(OS))
exitWithError(std::move(E));
}
return 0;
}
static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
OutlinedHashTreeRecord &GlobalOutlineRecord,
StableFunctionMapRecord &GlobalFunctionMapRecord);
static bool handleArchive(StringRef Filename, Archive &Arch,
OutlinedHashTreeRecord &GlobalOutlineRecord,
StableFunctionMapRecord &GlobalFunctionMapRecord) {
bool Result = true;
Error Err = Error::success();
for (const auto &Child : Arch.children(Err)) {
auto BuffOrErr = Child.getMemoryBufferRef();
if (Error E = BuffOrErr.takeError())
exitWithError(std::move(E), Filename);
auto NameOrErr = Child.getName();
if (Error E = NameOrErr.takeError())
exitWithError(std::move(E), Filename);
std::string Name = (Filename + "(" + NameOrErr.get() + ")").str();
Result &= handleBuffer(Name, BuffOrErr.get(), GlobalOutlineRecord,
GlobalFunctionMapRecord);
}
if (Err)
exitWithError(std::move(Err), Filename);
return Result;
}
static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
OutlinedHashTreeRecord &GlobalOutlineRecord,
StableFunctionMapRecord &GlobalFunctionMapRecord) {
Expected<std::unique_ptr<object::Binary>> BinOrErr =
object::createBinary(Buffer);
if (Error E = BinOrErr.takeError())
exitWithError(std::move(E), Filename);
bool Result = true;
if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) {
if (Error E = CodeGenDataReader::mergeFromObjectFile(
Obj, GlobalOutlineRecord, GlobalFunctionMapRecord))
exitWithError(std::move(E), Filename);
} else if (auto *Arch = dyn_cast<Archive>(BinOrErr->get())) {
Result &= handleArchive(Filename, *Arch, GlobalOutlineRecord,
GlobalFunctionMapRecord);
} else {
// TODO: Support for the MachO universal binary format.
errs() << "Error: unsupported binary file: " << Filename << "\n";
Result = false;
}
return Result;
}
static bool handleFile(StringRef Filename,
OutlinedHashTreeRecord &GlobalOutlineRecord,
StableFunctionMapRecord &GlobalFunctionMapRecord) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = BuffOrErr.getError())
exitWithErrorCode(EC, Filename);
return handleBuffer(Filename, *BuffOrErr.get(), GlobalOutlineRecord,
GlobalFunctionMapRecord);
}
static int merge_main(int argc, const char *argv[]) {
bool Result = true;
OutlinedHashTreeRecord GlobalOutlineRecord;
StableFunctionMapRecord GlobalFunctionMapRecord;
for (auto &Filename : InputFilenames)
Result &=
handleFile(Filename, GlobalOutlineRecord, GlobalFunctionMapRecord);
if (!Result)
exitWithError("failed to merge codegen data files.");
GlobalFunctionMapRecord.finalize(SkipTrim);
CodeGenDataWriter Writer;
if (!GlobalOutlineRecord.empty())
Writer.addRecord(GlobalOutlineRecord);
if (!GlobalFunctionMapRecord.empty())
Writer.addRecord(GlobalFunctionMapRecord);
std::error_code EC;
raw_fd_ostream OS(OutputFilename, EC,
OutputFormat == CGDataFormat::Text
? sys::fs::OF_TextWithCRLF
: sys::fs::OF_None);
if (EC)
exitWithErrorCode(EC, OutputFilename);
if (OutputFormat == CGDataFormat::Text) {
if (Error E = Writer.writeText(OS))
exitWithError(std::move(E));
} else {
if (Error E = Writer.write(OS))
exitWithError(std::move(E));
}
return 0;
}
static int show_main(int argc, const char *argv[]) {
std::error_code EC;
raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF);
if (EC)
exitWithErrorCode(EC, OutputFilename);
auto FS = vfs::getRealFileSystem();
auto ReaderOrErr = CodeGenDataReader::create(Filename, *FS);
if (Error E = ReaderOrErr.takeError())
exitWithError(std::move(E), Filename);
auto Reader = ReaderOrErr->get();
if (ShowCGDataVersion)
OS << "Version: " << Reader->getVersion() << "\n";
if (Reader->hasOutlinedHashTree()) {
auto Tree = Reader->releaseOutlinedHashTree();
OS << "Outlined hash tree:\n";
OS << " Total Node Count: " << Tree->size() << "\n";
OS << " Terminal Node Count: " << Tree->size(/*GetTerminalCountOnly=*/true)
<< "\n";
OS << " Depth: " << Tree->depth() << "\n";
}
if (Reader->hasStableFunctionMap()) {
auto Map = Reader->releaseStableFunctionMap();
OS << "Stable function map:\n";
OS << " Unique hash Count: " << Map->size() << "\n";
OS << " Total function Count: "
<< Map->size(StableFunctionMap::TotalFunctionCount) << "\n";
OS << " Mergeable function Count: "
<< Map->size(StableFunctionMap::MergeableFunctionCount) << "\n";
}
return 0;
}
static void parseArgs(int argc, char **argv) {
CGDataOptTable Tbl;
ToolName = argv[0];
llvm::BumpPtrAllocator A;
llvm::StringSaver Saver{A};
llvm::opt::InputArgList Args =
Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) {
llvm::errs() << Msg << '\n';
std::exit(1);
});
if (Args.hasArg(OPT_help)) {
Tbl.printHelp(
llvm::outs(),
"llvm-cgdata <action> [options] (<binary files>|<.cgdata file>)",
ToolName.str().c_str());
std::exit(0);
}
if (Args.hasArg(OPT_version)) {
cl::PrintVersionMessage();
std::exit(0);
}
ShowCGDataVersion = Args.hasArg(OPT_cgdata_version);
SkipTrim = Args.hasArg(OPT_skip_trim);
if (opt::Arg *A = Args.getLastArg(OPT_format)) {
StringRef OF = A->getValue();
OutputFormat = StringSwitch<CGDataFormat>(OF)
.Case("text", CGDataFormat::Text)
.Case("binary", CGDataFormat::Binary)
.Default(CGDataFormat::Invalid);
if (OutputFormat == CGDataFormat::Invalid)
exitWithError("unsupported format '" + OF + "'");
}
InputFilenames = Args.getAllArgValues(OPT_INPUT);
if (InputFilenames.empty())
exitWithError("No input file is specified.");
Filename = InputFilenames[0];
if (Args.hasArg(OPT_output)) {
OutputFilename = Args.getLastArgValue(OPT_output);
for (auto &Filename : InputFilenames)
if (Filename == OutputFilename)
exitWithError(
"Input file name cannot be the same as the output file name!\n");
}
opt::Arg *ActionArg = nullptr;
for (opt::Arg *Arg : Args.filtered(OPT_action_group)) {
if (ActionArg)
exitWithError("Only one action is allowed.");
ActionArg = Arg;
}
if (!ActionArg)
exitWithError("One action is required.");
switch (ActionArg->getOption().getID()) {
case OPT_show:
if (InputFilenames.size() != 1)
exitWithError("only one input file is allowed.");
Action = CGDataAction::Show;
break;
case OPT_convert:
// The default output format is text for convert.
if (!OutputFormat)
OutputFormat = CGDataFormat::Text;
if (InputFilenames.size() != 1)
exitWithError("only one input file is allowed.");
Action = CGDataAction::Convert;
break;
case OPT_merge:
// The default output format is binary for merge.
if (!OutputFormat)
OutputFormat = CGDataFormat::Binary;
Action = CGDataAction::Merge;
break;
default:
llvm_unreachable("unrecognized action");
}
}
int llvm_cgdata_main(int argc, char **argvNonConst, const llvm::ToolContext &) {
const char **argv = const_cast<const char **>(argvNonConst);
parseArgs(argc, argvNonConst);
switch (Action) {
case CGDataAction::Convert:
return convert_main(argc, argv);
case CGDataAction::Merge:
return merge_main(argc, argv);
case CGDataAction::Show:
return show_main(argc, argv);
}
llvm_unreachable("unrecognized action");
}
|