llvm-lto2.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. //===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
  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. // This program takes in a list of bitcode files, links them and performs
  10. // link-time optimization according to the provided symbol resolutions using the
  11. // resolution-based LTO interface, and outputs one or more object files.
  12. //
  13. // This program is intended to eventually replace llvm-lto which uses the legacy
  14. // LTO interface.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Bitcode/BitcodeReader.h"
  18. #include "llvm/CodeGen/CommandFlags.h"
  19. #include "llvm/Config/llvm-config.h"
  20. #include "llvm/IR/DiagnosticPrinter.h"
  21. #include "llvm/LTO/LTO.h"
  22. #include "llvm/Passes/PassPlugin.h"
  23. #include "llvm/Remarks/HotnessThresholdParser.h"
  24. #include "llvm/Support/Caching.h"
  25. #include "llvm/Support/CommandLine.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/InitLLVM.h"
  28. #include "llvm/Support/PluginLoader.h"
  29. #include "llvm/Support/TargetSelect.h"
  30. #include "llvm/Support/Threading.h"
  31. #include <atomic>
  32. using namespace llvm;
  33. using namespace lto;
  34. static codegen::RegisterCodeGenFlags CGF;
  35. static cl::opt<char>
  36. OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  37. "(default = '-O2')"),
  38. cl::Prefix, cl::ZeroOrMore, cl::init('2'));
  39. static cl::opt<char> CGOptLevel(
  40. "cg-opt-level",
  41. cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
  42. cl::init('2'));
  43. static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
  44. cl::desc("<input bitcode files>"));
  45. static cl::opt<std::string> OutputFilename("o", cl::Required,
  46. cl::desc("Output filename"),
  47. cl::value_desc("filename"));
  48. static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
  49. cl::value_desc("directory"));
  50. static cl::opt<std::string> OptPipeline("opt-pipeline",
  51. cl::desc("Optimizer Pipeline"),
  52. cl::value_desc("pipeline"));
  53. static cl::opt<std::string> AAPipeline("aa-pipeline",
  54. cl::desc("Alias Analysis Pipeline"),
  55. cl::value_desc("aapipeline"));
  56. static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
  57. static cl::opt<bool>
  58. ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
  59. cl::desc("Write out individual index and "
  60. "import files for the "
  61. "distributed backend case"));
  62. // Default to using all available threads in the system, but using only one
  63. // thread per core (no SMT).
  64. // Use -thinlto-threads=all to use hardware_concurrency() instead, which means
  65. // to use all hardware threads or cores in the system.
  66. static cl::opt<std::string> Threads("thinlto-threads");
  67. static cl::list<std::string> SymbolResolutions(
  68. "r",
  69. cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
  70. "where \"resolution\" is a sequence (which may be empty) of the\n"
  71. "following characters:\n"
  72. " p - prevailing: the linker has chosen this definition of the\n"
  73. " symbol\n"
  74. " l - local: the definition of this symbol is unpreemptable at\n"
  75. " runtime and is known to be in this linkage unit\n"
  76. " x - externally visible: the definition of this symbol is\n"
  77. " visible outside of the LTO unit\n"
  78. "A resolution for each symbol must be specified."),
  79. cl::ZeroOrMore);
  80. static cl::opt<std::string> OverrideTriple(
  81. "override-triple",
  82. cl::desc("Replace target triples in input files with this triple"));
  83. static cl::opt<std::string> DefaultTriple(
  84. "default-triple",
  85. cl::desc(
  86. "Replace unspecified target triples in input files with this triple"));
  87. static cl::opt<bool> RemarksWithHotness(
  88. "pass-remarks-with-hotness",
  89. cl::desc("With PGO, include profile count in optimization remarks"),
  90. cl::Hidden);
  91. cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
  92. RemarksHotnessThreshold(
  93. "pass-remarks-hotness-threshold",
  94. cl::desc("Minimum profile count required for an "
  95. "optimization remark to be output."
  96. " Use 'auto' to apply the threshold from profile summary."),
  97. cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);
  98. static cl::opt<std::string>
  99. RemarksFilename("pass-remarks-output",
  100. cl::desc("Output filename for pass remarks"),
  101. cl::value_desc("filename"));
  102. static cl::opt<std::string>
  103. RemarksPasses("pass-remarks-filter",
  104. cl::desc("Only record optimization remarks from passes whose "
  105. "names match the given regular expression"),
  106. cl::value_desc("regex"));
  107. static cl::opt<std::string> RemarksFormat(
  108. "pass-remarks-format",
  109. cl::desc("The format used for serializing remarks (default: YAML)"),
  110. cl::value_desc("format"), cl::init("yaml"));
  111. static cl::opt<std::string>
  112. SamplePGOFile("lto-sample-profile-file",
  113. cl::desc("Specify a SamplePGO profile file"));
  114. static cl::opt<std::string>
  115. CSPGOFile("lto-cspgo-profile-file",
  116. cl::desc("Specify a context sensitive PGO profile file"));
  117. static cl::opt<bool>
  118. RunCSIRInstr("lto-cspgo-gen",
  119. cl::desc("Run PGO context sensitive IR instrumentation"),
  120. cl::init(false), cl::Hidden);
  121. static cl::opt<bool>
  122. UseNewPM("use-new-pm",
  123. cl::desc("Run LTO passes using the new pass manager"),
  124. cl::init(LLVM_ENABLE_NEW_PASS_MANAGER), cl::Hidden);
  125. static cl::opt<bool>
  126. DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
  127. cl::desc("Print pass management debugging information"));
  128. static cl::opt<std::string>
  129. StatsFile("stats-file", cl::desc("Filename to write statistics to"));
  130. static cl::list<std::string>
  131. PassPlugins("load-pass-plugin",
  132. cl::desc("Load passes from plugin library"));
  133. static cl::opt<bool> EnableFreestanding(
  134. "lto-freestanding",
  135. cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
  136. cl::init(false), cl::Hidden);
  137. static void check(Error E, std::string Msg) {
  138. if (!E)
  139. return;
  140. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
  141. errs() << "llvm-lto2: " << Msg << ": " << EIB.message().c_str() << '\n';
  142. });
  143. exit(1);
  144. }
  145. template <typename T> static T check(Expected<T> E, std::string Msg) {
  146. if (E)
  147. return std::move(*E);
  148. check(E.takeError(), Msg);
  149. return T();
  150. }
  151. static void check(std::error_code EC, std::string Msg) {
  152. check(errorCodeToError(EC), Msg);
  153. }
  154. template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
  155. if (E)
  156. return std::move(*E);
  157. check(E.getError(), Msg);
  158. return T();
  159. }
  160. static int usage() {
  161. errs() << "Available subcommands: dump-symtab run\n";
  162. return 1;
  163. }
  164. static int run(int argc, char **argv) {
  165. cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
  166. // FIXME: Workaround PR30396 which means that a symbol can appear
  167. // more than once if it is defined in module-level assembly and
  168. // has a GV declaration. We allow (file, symbol) pairs to have multiple
  169. // resolutions and apply them in the order observed.
  170. std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
  171. CommandLineResolutions;
  172. for (std::string R : SymbolResolutions) {
  173. StringRef Rest = R;
  174. StringRef FileName, SymbolName;
  175. std::tie(FileName, Rest) = Rest.split(',');
  176. if (Rest.empty()) {
  177. llvm::errs() << "invalid resolution: " << R << '\n';
  178. return 1;
  179. }
  180. std::tie(SymbolName, Rest) = Rest.split(',');
  181. SymbolResolution Res;
  182. for (char C : Rest) {
  183. if (C == 'p')
  184. Res.Prevailing = true;
  185. else if (C == 'l')
  186. Res.FinalDefinitionInLinkageUnit = true;
  187. else if (C == 'x')
  188. Res.VisibleToRegularObj = true;
  189. else if (C == 'r')
  190. Res.LinkerRedefined = true;
  191. else {
  192. llvm::errs() << "invalid character " << C << " in resolution: " << R
  193. << '\n';
  194. return 1;
  195. }
  196. }
  197. CommandLineResolutions[{std::string(FileName), std::string(SymbolName)}]
  198. .push_back(Res);
  199. }
  200. std::vector<std::unique_ptr<MemoryBuffer>> MBs;
  201. Config Conf;
  202. Conf.CPU = codegen::getMCPU();
  203. Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  204. Conf.MAttrs = codegen::getMAttrs();
  205. if (auto RM = codegen::getExplicitRelocModel())
  206. Conf.RelocModel = RM.getValue();
  207. Conf.CodeModel = codegen::getExplicitCodeModel();
  208. Conf.DebugPassManager = DebugPassManager;
  209. if (SaveTemps)
  210. check(Conf.addSaveTemps(OutputFilename + "."),
  211. "Config::addSaveTemps failed");
  212. // Optimization remarks.
  213. Conf.RemarksFilename = RemarksFilename;
  214. Conf.RemarksPasses = RemarksPasses;
  215. Conf.RemarksWithHotness = RemarksWithHotness;
  216. Conf.RemarksHotnessThreshold = RemarksHotnessThreshold;
  217. Conf.RemarksFormat = RemarksFormat;
  218. Conf.SampleProfile = SamplePGOFile;
  219. Conf.CSIRProfile = CSPGOFile;
  220. Conf.RunCSIRInstr = RunCSIRInstr;
  221. // Run a custom pipeline, if asked for.
  222. Conf.OptPipeline = OptPipeline;
  223. Conf.AAPipeline = AAPipeline;
  224. Conf.OptLevel = OptLevel - '0';
  225. Conf.UseNewPM = UseNewPM;
  226. Conf.Freestanding = EnableFreestanding;
  227. for (auto &PluginFN : PassPlugins)
  228. Conf.PassPlugins.push_back(PluginFN);
  229. switch (CGOptLevel) {
  230. case '0':
  231. Conf.CGOptLevel = CodeGenOpt::None;
  232. break;
  233. case '1':
  234. Conf.CGOptLevel = CodeGenOpt::Less;
  235. break;
  236. case '2':
  237. Conf.CGOptLevel = CodeGenOpt::Default;
  238. break;
  239. case '3':
  240. Conf.CGOptLevel = CodeGenOpt::Aggressive;
  241. break;
  242. default:
  243. llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
  244. return 1;
  245. }
  246. if (auto FT = codegen::getExplicitFileType())
  247. Conf.CGFileType = FT.getValue();
  248. Conf.OverrideTriple = OverrideTriple;
  249. Conf.DefaultTriple = DefaultTriple;
  250. Conf.StatsFile = StatsFile;
  251. Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
  252. Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
  253. ThinBackend Backend;
  254. if (ThinLTODistributedIndexes)
  255. Backend = createWriteIndexesThinBackend(/* OldPrefix */ "",
  256. /* NewPrefix */ "",
  257. /* ShouldEmitImportsFiles */ true,
  258. /* LinkedObjectsFile */ nullptr,
  259. /* OnWrite */ {});
  260. else
  261. Backend = createInProcessThinBackend(
  262. llvm::heavyweight_hardware_concurrency(Threads));
  263. // Track whether we hit an error; in particular, in the multi-threaded case,
  264. // we can't exit() early because the rest of the threads wouldn't have had a
  265. // change to be join-ed, and that would result in a "terminate called without
  266. // an active exception". Altogether, this results in nondeterministic
  267. // behavior. Instead, we don't exit in the multi-threaded case, but we make
  268. // sure to report the error and then at the end (after joining cleanly)
  269. // exit(1).
  270. std::atomic<bool> HasErrors;
  271. std::atomic_init(&HasErrors, false);
  272. Conf.DiagHandler = [&](const DiagnosticInfo &DI) {
  273. DiagnosticPrinterRawOStream DP(errs());
  274. DI.print(DP);
  275. errs() << '\n';
  276. if (DI.getSeverity() == DS_Error)
  277. HasErrors = true;
  278. };
  279. LTO Lto(std::move(Conf), std::move(Backend));
  280. for (std::string F : InputFilenames) {
  281. std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
  282. std::unique_ptr<InputFile> Input =
  283. check(InputFile::create(MB->getMemBufferRef()), F);
  284. std::vector<SymbolResolution> Res;
  285. for (const InputFile::Symbol &Sym : Input->symbols()) {
  286. auto I = CommandLineResolutions.find({F, std::string(Sym.getName())});
  287. // If it isn't found, look for ".", which would have been added
  288. // (followed by a hash) when the symbol was promoted during module
  289. // splitting if it was defined in one part and used in the other.
  290. // Try looking up the symbol name before the suffix.
  291. if (I == CommandLineResolutions.end()) {
  292. auto SplitName = Sym.getName().rsplit(".");
  293. I = CommandLineResolutions.find({F, std::string(SplitName.first)});
  294. }
  295. if (I == CommandLineResolutions.end()) {
  296. llvm::errs() << argv[0] << ": missing symbol resolution for " << F
  297. << ',' << Sym.getName() << '\n';
  298. HasErrors = true;
  299. } else {
  300. Res.push_back(I->second.front());
  301. I->second.pop_front();
  302. if (I->second.empty())
  303. CommandLineResolutions.erase(I);
  304. }
  305. }
  306. if (HasErrors)
  307. continue;
  308. MBs.push_back(std::move(MB));
  309. check(Lto.add(std::move(Input), Res), F);
  310. }
  311. if (!CommandLineResolutions.empty()) {
  312. HasErrors = true;
  313. for (auto UnusedRes : CommandLineResolutions)
  314. llvm::errs() << argv[0] << ": unused symbol resolution for "
  315. << UnusedRes.first.first << ',' << UnusedRes.first.second
  316. << '\n';
  317. }
  318. if (HasErrors)
  319. return 1;
  320. auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> {
  321. std::string Path = OutputFilename + "." + utostr(Task);
  322. std::error_code EC;
  323. auto S = std::make_unique<raw_fd_ostream>(Path, EC, sys::fs::OF_None);
  324. check(EC, Path);
  325. return std::make_unique<CachedFileStream>(std::move(S), Path);
  326. };
  327. auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
  328. *AddStream(Task)->OS << MB->getBuffer();
  329. };
  330. FileCache Cache;
  331. if (!CacheDir.empty())
  332. Cache = check(localCache("ThinLTO", "Thin", CacheDir, AddBuffer),
  333. "failed to create cache");
  334. check(Lto.run(AddStream, Cache), "LTO::run failed");
  335. return static_cast<int>(HasErrors);
  336. }
  337. static int dumpSymtab(int argc, char **argv) {
  338. for (StringRef F : make_range(argv + 1, argv + argc)) {
  339. std::unique_ptr<MemoryBuffer> MB =
  340. check(MemoryBuffer::getFile(F), std::string(F));
  341. BitcodeFileContents BFC =
  342. check(getBitcodeFileContents(*MB), std::string(F));
  343. if (BFC.Symtab.size() >= sizeof(irsymtab::storage::Header)) {
  344. auto *Hdr = reinterpret_cast<const irsymtab::storage::Header *>(
  345. BFC.Symtab.data());
  346. outs() << "version: " << Hdr->Version << '\n';
  347. if (Hdr->Version == irsymtab::storage::Header::kCurrentVersion)
  348. outs() << "producer: " << Hdr->Producer.get(BFC.StrtabForSymtab)
  349. << '\n';
  350. }
  351. std::unique_ptr<InputFile> Input =
  352. check(InputFile::create(MB->getMemBufferRef()), std::string(F));
  353. outs() << "target triple: " << Input->getTargetTriple() << '\n';
  354. Triple TT(Input->getTargetTriple());
  355. outs() << "source filename: " << Input->getSourceFileName() << '\n';
  356. if (TT.isOSBinFormatCOFF())
  357. outs() << "linker opts: " << Input->getCOFFLinkerOpts() << '\n';
  358. if (TT.isOSBinFormatELF()) {
  359. outs() << "dependent libraries:";
  360. for (auto L : Input->getDependentLibraries())
  361. outs() << " \"" << L << "\"";
  362. outs() << '\n';
  363. }
  364. ArrayRef<std::pair<StringRef, Comdat::SelectionKind>> ComdatTable =
  365. Input->getComdatTable();
  366. for (const InputFile::Symbol &Sym : Input->symbols()) {
  367. switch (Sym.getVisibility()) {
  368. case GlobalValue::HiddenVisibility:
  369. outs() << 'H';
  370. break;
  371. case GlobalValue::ProtectedVisibility:
  372. outs() << 'P';
  373. break;
  374. case GlobalValue::DefaultVisibility:
  375. outs() << 'D';
  376. break;
  377. }
  378. auto PrintBool = [&](char C, bool B) { outs() << (B ? C : '-'); };
  379. PrintBool('U', Sym.isUndefined());
  380. PrintBool('C', Sym.isCommon());
  381. PrintBool('W', Sym.isWeak());
  382. PrintBool('I', Sym.isIndirect());
  383. PrintBool('O', Sym.canBeOmittedFromSymbolTable());
  384. PrintBool('T', Sym.isTLS());
  385. PrintBool('X', Sym.isExecutable());
  386. outs() << ' ' << Sym.getName() << '\n';
  387. if (Sym.isCommon())
  388. outs() << " size " << Sym.getCommonSize() << " align "
  389. << Sym.getCommonAlignment() << '\n';
  390. int Comdat = Sym.getComdatIndex();
  391. if (Comdat != -1) {
  392. outs() << " comdat ";
  393. switch (ComdatTable[Comdat].second) {
  394. case Comdat::Any:
  395. outs() << "any";
  396. break;
  397. case Comdat::ExactMatch:
  398. outs() << "exactmatch";
  399. break;
  400. case Comdat::Largest:
  401. outs() << "largest";
  402. break;
  403. case Comdat::NoDeduplicate:
  404. outs() << "nodeduplicate";
  405. break;
  406. case Comdat::SameSize:
  407. outs() << "samesize";
  408. break;
  409. }
  410. outs() << ' ' << ComdatTable[Comdat].first << '\n';
  411. }
  412. if (TT.isOSBinFormatCOFF() && Sym.isWeak() && Sym.isIndirect())
  413. outs() << " fallback " << Sym.getCOFFWeakExternalFallback() << '\n';
  414. if (!Sym.getSectionName().empty())
  415. outs() << " section " << Sym.getSectionName() << "\n";
  416. }
  417. outs() << '\n';
  418. }
  419. return 0;
  420. }
  421. int main(int argc, char **argv) {
  422. InitLLVM X(argc, argv);
  423. InitializeAllTargets();
  424. InitializeAllTargetMCs();
  425. InitializeAllAsmPrinters();
  426. InitializeAllAsmParsers();
  427. // FIXME: This should use llvm::cl subcommands, but it isn't currently
  428. // possible to pass an argument not associated with a subcommand to a
  429. // subcommand (e.g. -use-new-pm).
  430. if (argc < 2)
  431. return usage();
  432. StringRef Subcommand = argv[1];
  433. // Ensure that argv[0] is correct after adjusting argv/argc.
  434. argv[1] = argv[0];
  435. if (Subcommand == "dump-symtab")
  436. return dumpSymtab(argc - 1, argv + 1);
  437. if (Subcommand == "run")
  438. return run(argc - 1, argv + 1);
  439. return usage();
  440. }