llvm-lto.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. //===- llvm-lto: a simple command-line program to link modules with LTO ---===//
  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, performs link-time
  10. // optimization, and outputs an object file.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm-c/lto.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/StringSet.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/Bitcode/BitcodeReader.h"
  22. #include "llvm/Bitcode/BitcodeWriter.h"
  23. #include "llvm/CodeGen/CommandFlags.h"
  24. #include "llvm/IR/DiagnosticInfo.h"
  25. #include "llvm/IR/DiagnosticPrinter.h"
  26. #include "llvm/IR/LLVMContext.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/ModuleSummaryIndex.h"
  29. #include "llvm/IR/Verifier.h"
  30. #include "llvm/IRReader/IRReader.h"
  31. #include "llvm/LTO/legacy/LTOCodeGenerator.h"
  32. #include "llvm/LTO/legacy/LTOModule.h"
  33. #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
  34. #include "llvm/Support/Allocator.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Error.h"
  38. #include "llvm/Support/ErrorHandling.h"
  39. #include "llvm/Support/ErrorOr.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/InitLLVM.h"
  42. #include "llvm/Support/MemoryBuffer.h"
  43. #include "llvm/Support/Path.h"
  44. #include "llvm/Support/SourceMgr.h"
  45. #include "llvm/Support/TargetSelect.h"
  46. #include "llvm/Support/ToolOutputFile.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Support/WithColor.h"
  49. #include "llvm/Target/TargetOptions.h"
  50. #include <algorithm>
  51. #include <cassert>
  52. #include <cstdint>
  53. #include <cstdlib>
  54. #include <list>
  55. #include <map>
  56. #include <memory>
  57. #include <string>
  58. #include <system_error>
  59. #include <tuple>
  60. #include <utility>
  61. #include <vector>
  62. using namespace llvm;
  63. static codegen::RegisterCodeGenFlags CGF;
  64. static cl::OptionCategory LTOCategory("LTO Options");
  65. static cl::opt<char>
  66. OptLevel("O",
  67. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  68. "(default = '-O2')"),
  69. cl::Prefix, cl::ZeroOrMore, cl::init('2'), cl::cat(LTOCategory));
  70. static cl::opt<bool>
  71. IndexStats("thinlto-index-stats",
  72. cl::desc("Print statistic for the index in every input files"),
  73. cl::init(false), cl::cat(LTOCategory));
  74. static cl::opt<bool> DisableVerify(
  75. "disable-verify", cl::init(false),
  76. cl::desc("Do not run the verifier during the optimization pipeline"),
  77. cl::cat(LTOCategory));
  78. static cl::opt<bool> EnableFreestanding(
  79. "lto-freestanding", cl::init(false),
  80. cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
  81. cl::cat(LTOCategory));
  82. static cl::opt<bool> UseDiagnosticHandler(
  83. "use-diagnostic-handler", cl::init(false),
  84. cl::desc("Use a diagnostic handler to test the handler interface"),
  85. cl::cat(LTOCategory));
  86. static cl::opt<bool>
  87. ThinLTO("thinlto", cl::init(false),
  88. cl::desc("Only write combined global index for ThinLTO backends"),
  89. cl::cat(LTOCategory));
  90. enum ThinLTOModes {
  91. THINLINK,
  92. THINDISTRIBUTE,
  93. THINEMITIMPORTS,
  94. THINPROMOTE,
  95. THINIMPORT,
  96. THININTERNALIZE,
  97. THINOPT,
  98. THINCODEGEN,
  99. THINALL
  100. };
  101. cl::opt<ThinLTOModes> ThinLTOMode(
  102. "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
  103. cl::values(
  104. clEnumValN(
  105. THINLINK, "thinlink",
  106. "ThinLink: produces the index by linking only the summaries."),
  107. clEnumValN(THINDISTRIBUTE, "distributedindexes",
  108. "Produces individual indexes for distributed backends."),
  109. clEnumValN(THINEMITIMPORTS, "emitimports",
  110. "Emit imports files for distributed backends."),
  111. clEnumValN(THINPROMOTE, "promote",
  112. "Perform pre-import promotion (requires -thinlto-index)."),
  113. clEnumValN(THINIMPORT, "import",
  114. "Perform both promotion and "
  115. "cross-module importing (requires "
  116. "-thinlto-index)."),
  117. clEnumValN(THININTERNALIZE, "internalize",
  118. "Perform internalization driven by -exported-symbol "
  119. "(requires -thinlto-index)."),
  120. clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
  121. clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
  122. clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")),
  123. cl::cat(LTOCategory));
  124. static cl::opt<std::string>
  125. ThinLTOIndex("thinlto-index",
  126. cl::desc("Provide the index produced by a ThinLink, required "
  127. "to perform the promotion and/or importing."),
  128. cl::cat(LTOCategory));
  129. static cl::opt<std::string> ThinLTOPrefixReplace(
  130. "thinlto-prefix-replace",
  131. cl::desc("Control where files for distributed backends are "
  132. "created. Expects 'oldprefix;newprefix' and if path "
  133. "prefix of output file is oldprefix it will be "
  134. "replaced with newprefix."),
  135. cl::cat(LTOCategory));
  136. static cl::opt<std::string> ThinLTOModuleId(
  137. "thinlto-module-id",
  138. cl::desc("For the module ID for the file to process, useful to "
  139. "match what is in the index."),
  140. cl::cat(LTOCategory));
  141. static cl::opt<std::string> ThinLTOCacheDir("thinlto-cache-dir",
  142. cl::desc("Enable ThinLTO caching."),
  143. cl::cat(LTOCategory));
  144. static cl::opt<int> ThinLTOCachePruningInterval(
  145. "thinlto-cache-pruning-interval", cl::init(1200),
  146. cl::desc("Set ThinLTO cache pruning interval."), cl::cat(LTOCategory));
  147. static cl::opt<uint64_t> ThinLTOCacheMaxSizeBytes(
  148. "thinlto-cache-max-size-bytes",
  149. cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."),
  150. cl::cat(LTOCategory));
  151. static cl::opt<int> ThinLTOCacheMaxSizeFiles(
  152. "thinlto-cache-max-size-files", cl::init(1000000),
  153. cl::desc("Set ThinLTO cache pruning directory maximum number of files."),
  154. cl::cat(LTOCategory));
  155. static cl::opt<unsigned> ThinLTOCacheEntryExpiration(
  156. "thinlto-cache-entry-expiration", cl::init(604800) /* 1w */,
  157. cl::desc("Set ThinLTO cache entry expiration time."), cl::cat(LTOCategory));
  158. static cl::opt<std::string> ThinLTOSaveTempsPrefix(
  159. "thinlto-save-temps",
  160. cl::desc("Save ThinLTO temp files using filenames created by adding "
  161. "suffixes to the given file path prefix."),
  162. cl::cat(LTOCategory));
  163. static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
  164. "thinlto-save-objects",
  165. cl::desc("Save ThinLTO generated object files using filenames created in "
  166. "the given directory."),
  167. cl::cat(LTOCategory));
  168. static cl::opt<bool> SaveLinkedModuleFile(
  169. "save-linked-module", cl::init(false),
  170. cl::desc("Write linked LTO module to file before optimize"),
  171. cl::cat(LTOCategory));
  172. static cl::opt<bool>
  173. SaveModuleFile("save-merged-module", cl::init(false),
  174. cl::desc("Write merged LTO module to file before CodeGen"),
  175. cl::cat(LTOCategory));
  176. static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
  177. cl::desc("<input bitcode files>"),
  178. cl::cat(LTOCategory));
  179. static cl::opt<std::string> OutputFilename("o", cl::init(""),
  180. cl::desc("Override output filename"),
  181. cl::value_desc("filename"),
  182. cl::cat(LTOCategory));
  183. static cl::list<std::string> ExportedSymbols(
  184. "exported-symbol",
  185. cl::desc("List of symbols to export from the resulting object file"),
  186. cl::ZeroOrMore, cl::cat(LTOCategory));
  187. static cl::list<std::string>
  188. DSOSymbols("dso-symbol",
  189. cl::desc("Symbol to put in the symtab in the resulting dso"),
  190. cl::ZeroOrMore, cl::cat(LTOCategory));
  191. static cl::opt<bool> ListSymbolsOnly(
  192. "list-symbols-only", cl::init(false),
  193. cl::desc("Instead of running LTO, list the symbols in each IR file"),
  194. cl::cat(LTOCategory));
  195. static cl::opt<bool> ListDependentLibrariesOnly(
  196. "list-dependent-libraries-only", cl::init(false),
  197. cl::desc(
  198. "Instead of running LTO, list the dependent libraries in each IR file"),
  199. cl::cat(LTOCategory));
  200. static cl::opt<bool> QueryHasCtorDtor(
  201. "query-hasCtorDtor", cl::init(false),
  202. cl::desc("Queries LTOModule::hasCtorDtor() on each IR file"));
  203. static cl::opt<bool>
  204. SetMergedModule("set-merged-module", cl::init(false),
  205. cl::desc("Use the first input module as the merged module"),
  206. cl::cat(LTOCategory));
  207. static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
  208. cl::desc("Number of backend threads"),
  209. cl::cat(LTOCategory));
  210. static cl::opt<bool> RestoreGlobalsLinkage(
  211. "restore-linkage", cl::init(false),
  212. cl::desc("Restore original linkage of globals prior to CodeGen"),
  213. cl::cat(LTOCategory));
  214. static cl::opt<bool> CheckHasObjC(
  215. "check-for-objc", cl::init(false),
  216. cl::desc("Only check if the module has objective-C defined in it"),
  217. cl::cat(LTOCategory));
  218. static cl::opt<bool> PrintMachOCPUOnly(
  219. "print-macho-cpu-only", cl::init(false),
  220. cl::desc("Instead of running LTO, print the mach-o cpu in each IR file"),
  221. cl::cat(LTOCategory));
  222. static cl::opt<bool> UseNewPM(
  223. "use-new-pm", cl::desc("Run LTO passes using the new pass manager"),
  224. cl::init(LLVM_ENABLE_NEW_PASS_MANAGER), cl::Hidden, cl::cat(LTOCategory));
  225. static cl::opt<bool>
  226. DebugPassManager("debug-pass-manager", cl::init(false), cl::Hidden,
  227. cl::desc("Print pass management debugging information"),
  228. cl::cat(LTOCategory));
  229. namespace {
  230. struct ModuleInfo {
  231. BitVector CanBeHidden;
  232. };
  233. } // end anonymous namespace
  234. static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
  235. const char *Msg, void *) {
  236. errs() << "llvm-lto: ";
  237. switch (Severity) {
  238. case LTO_DS_NOTE:
  239. errs() << "note: ";
  240. break;
  241. case LTO_DS_REMARK:
  242. errs() << "remark: ";
  243. break;
  244. case LTO_DS_ERROR:
  245. errs() << "error: ";
  246. break;
  247. case LTO_DS_WARNING:
  248. errs() << "warning: ";
  249. break;
  250. }
  251. errs() << Msg << "\n";
  252. }
  253. static std::string CurrentActivity;
  254. namespace {
  255. struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
  256. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  257. raw_ostream &OS = errs();
  258. OS << "llvm-lto: ";
  259. switch (DI.getSeverity()) {
  260. case DS_Error:
  261. OS << "error";
  262. break;
  263. case DS_Warning:
  264. OS << "warning";
  265. break;
  266. case DS_Remark:
  267. OS << "remark";
  268. break;
  269. case DS_Note:
  270. OS << "note";
  271. break;
  272. }
  273. if (!CurrentActivity.empty())
  274. OS << ' ' << CurrentActivity;
  275. OS << ": ";
  276. DiagnosticPrinterRawOStream DP(OS);
  277. DI.print(DP);
  278. OS << '\n';
  279. if (DI.getSeverity() == DS_Error)
  280. exit(1);
  281. return true;
  282. }
  283. };
  284. }
  285. static void error(const Twine &Msg) {
  286. errs() << "llvm-lto: " << Msg << '\n';
  287. exit(1);
  288. }
  289. static void error(std::error_code EC, const Twine &Prefix) {
  290. if (EC)
  291. error(Prefix + ": " + EC.message());
  292. }
  293. template <typename T>
  294. static void error(const ErrorOr<T> &V, const Twine &Prefix) {
  295. error(V.getError(), Prefix);
  296. }
  297. static void maybeVerifyModule(const Module &Mod) {
  298. if (!DisableVerify && verifyModule(Mod, &errs()))
  299. error("Broken Module");
  300. }
  301. static std::unique_ptr<LTOModule>
  302. getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
  303. const TargetOptions &Options) {
  304. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  305. MemoryBuffer::getFile(Path);
  306. error(BufferOrErr, "error loading file '" + Path + "'");
  307. Buffer = std::move(BufferOrErr.get());
  308. CurrentActivity = ("loading file '" + Path + "'").str();
  309. std::unique_ptr<LLVMContext> Context = std::make_unique<LLVMContext>();
  310. Context->setDiagnosticHandler(std::make_unique<LLVMLTODiagnosticHandler>(),
  311. true);
  312. ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
  313. std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
  314. Options, Path);
  315. CurrentActivity = "";
  316. maybeVerifyModule((*Ret)->getModule());
  317. return std::move(*Ret);
  318. }
  319. /// Print some statistics on the index for each input files.
  320. static void printIndexStats() {
  321. for (auto &Filename : InputFilenames) {
  322. ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
  323. std::unique_ptr<ModuleSummaryIndex> Index =
  324. ExitOnErr(getModuleSummaryIndexForFile(Filename));
  325. // Skip files without a module summary.
  326. if (!Index)
  327. report_fatal_error(Twine(Filename) + " does not contain an index");
  328. unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
  329. for (auto &Summaries : *Index) {
  330. for (auto &Summary : Summaries.second.SummaryList) {
  331. Refs += Summary->refs().size();
  332. if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
  333. Functions++;
  334. Calls += FuncSummary->calls().size();
  335. } else if (isa<AliasSummary>(Summary.get()))
  336. Alias++;
  337. else
  338. Globals++;
  339. }
  340. }
  341. outs() << "Index " << Filename << " contains "
  342. << (Alias + Globals + Functions) << " nodes (" << Functions
  343. << " functions, " << Alias << " alias, " << Globals
  344. << " globals) and " << (Calls + Refs) << " edges (" << Refs
  345. << " refs and " << Calls << " calls)\n";
  346. }
  347. }
  348. /// Load each IR file and dump certain information based on active flags.
  349. ///
  350. /// The main point here is to provide lit-testable coverage for the LTOModule
  351. /// functionality that's exposed by the C API. Moreover, this provides testing
  352. /// coverage for modules that have been created in their own contexts.
  353. static void testLTOModule(const TargetOptions &Options) {
  354. for (auto &Filename : InputFilenames) {
  355. std::unique_ptr<MemoryBuffer> Buffer;
  356. std::unique_ptr<LTOModule> Module =
  357. getLocalLTOModule(Filename, Buffer, Options);
  358. if (ListSymbolsOnly) {
  359. // List the symbols.
  360. outs() << Filename << ":\n";
  361. for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
  362. outs() << Module->getSymbolName(I) << "\n";
  363. }
  364. if (QueryHasCtorDtor)
  365. outs() << Filename
  366. << ": hasCtorDtor = " << (Module->hasCtorDtor() ? "true" : "false")
  367. << "\n";
  368. }
  369. }
  370. static std::unique_ptr<MemoryBuffer> loadFile(StringRef Filename) {
  371. ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename.str() +
  372. "': ");
  373. return ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
  374. }
  375. static void listDependentLibraries() {
  376. for (auto &Filename : InputFilenames) {
  377. auto Buffer = loadFile(Filename);
  378. std::string E;
  379. std::unique_ptr<lto::InputFile> Input(LTOModule::createInputFile(
  380. Buffer->getBufferStart(), Buffer->getBufferSize(), Filename.c_str(),
  381. E));
  382. if (!Input)
  383. error(E);
  384. // List the dependent libraries.
  385. outs() << Filename << ":\n";
  386. for (size_t I = 0, C = LTOModule::getDependentLibraryCount(Input.get());
  387. I != C; ++I) {
  388. size_t L = 0;
  389. const char *S = LTOModule::getDependentLibrary(Input.get(), I, &L);
  390. assert(S);
  391. outs() << StringRef(S, L) << "\n";
  392. }
  393. }
  394. }
  395. static void printMachOCPUOnly() {
  396. LLVMContext Context;
  397. Context.setDiagnosticHandler(std::make_unique<LLVMLTODiagnosticHandler>(),
  398. true);
  399. TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  400. for (auto &Filename : InputFilenames) {
  401. ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
  402. LTOModule::createFromFile(Context, Filename, Options);
  403. if (!ModuleOrErr)
  404. error(ModuleOrErr, "llvm-lto: ");
  405. Expected<uint32_t> CPUType = (*ModuleOrErr)->getMachOCPUType();
  406. Expected<uint32_t> CPUSubType = (*ModuleOrErr)->getMachOCPUSubType();
  407. if (!CPUType)
  408. error("Error while printing mach-o cputype: " +
  409. toString(CPUType.takeError()));
  410. if (!CPUSubType)
  411. error("Error while printing mach-o cpusubtype: " +
  412. toString(CPUSubType.takeError()));
  413. outs() << llvm::format("%s:\ncputype: %u\ncpusubtype: %u\n",
  414. Filename.c_str(), *CPUType, *CPUSubType);
  415. }
  416. }
  417. /// Create a combined index file from the input IR files and write it.
  418. ///
  419. /// This is meant to enable testing of ThinLTO combined index generation,
  420. /// currently available via the gold plugin via -thinlto.
  421. static void createCombinedModuleSummaryIndex() {
  422. ModuleSummaryIndex CombinedIndex(/*HaveGVs=*/false);
  423. uint64_t NextModuleId = 0;
  424. for (auto &Filename : InputFilenames) {
  425. ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
  426. std::unique_ptr<MemoryBuffer> MB =
  427. ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
  428. ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, NextModuleId++));
  429. }
  430. // In order to use this index for testing, specifically import testing, we
  431. // need to update any indirect call edges created from SamplePGO, so that they
  432. // point to the correct GUIDs.
  433. updateIndirectCalls(CombinedIndex);
  434. std::error_code EC;
  435. assert(!OutputFilename.empty());
  436. raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
  437. sys::fs::OpenFlags::OF_None);
  438. error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
  439. writeIndexToFile(CombinedIndex, OS);
  440. OS.close();
  441. }
  442. /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
  443. /// \p NewPrefix strings, if it was specified.
  444. static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
  445. std::string &NewPrefix) {
  446. assert(ThinLTOPrefixReplace.empty() ||
  447. ThinLTOPrefixReplace.find(';') != StringRef::npos);
  448. StringRef PrefixReplace = ThinLTOPrefixReplace;
  449. std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
  450. OldPrefix = Split.first.str();
  451. NewPrefix = Split.second.str();
  452. }
  453. /// Given the original \p Path to an output file, replace any path
  454. /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
  455. /// resulting directory if it does not yet exist.
  456. static std::string getThinLTOOutputFile(const std::string &Path,
  457. const std::string &OldPrefix,
  458. const std::string &NewPrefix) {
  459. if (OldPrefix.empty() && NewPrefix.empty())
  460. return Path;
  461. SmallString<128> NewPath(Path);
  462. llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
  463. StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
  464. if (!ParentPath.empty()) {
  465. // Make sure the new directory exists, creating it if necessary.
  466. if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
  467. error(EC, "error creating the directory '" + ParentPath + "'");
  468. }
  469. return std::string(NewPath.str());
  470. }
  471. namespace thinlto {
  472. std::vector<std::unique_ptr<MemoryBuffer>>
  473. loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
  474. std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
  475. for (auto &ModPath : Index.modulePaths()) {
  476. const auto &Filename = ModPath.first();
  477. std::string CurrentActivity = ("loading file '" + Filename + "'").str();
  478. auto InputOrErr = MemoryBuffer::getFile(Filename);
  479. error(InputOrErr, "error " + CurrentActivity);
  480. InputBuffers.push_back(std::move(*InputOrErr));
  481. }
  482. return InputBuffers;
  483. }
  484. std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
  485. if (ThinLTOIndex.empty())
  486. report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
  487. ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
  488. "': ");
  489. return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
  490. }
  491. static std::unique_ptr<lto::InputFile> loadInputFile(MemoryBufferRef Buffer) {
  492. ExitOnError ExitOnErr("llvm-lto: error loading input '" +
  493. Buffer.getBufferIdentifier().str() + "': ");
  494. return ExitOnErr(lto::InputFile::create(Buffer));
  495. }
  496. static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile &File,
  497. LLVMContext &CTX) {
  498. auto &Mod = File.getSingleBitcodeModule();
  499. auto ModuleOrErr = Mod.parseModule(CTX);
  500. if (!ModuleOrErr) {
  501. handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
  502. SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
  503. SourceMgr::DK_Error, EIB.message());
  504. Err.print("llvm-lto", errs());
  505. });
  506. report_fatal_error("Can't load module, abort.");
  507. }
  508. maybeVerifyModule(**ModuleOrErr);
  509. if (ThinLTOModuleId.getNumOccurrences()) {
  510. if (InputFilenames.size() != 1)
  511. report_fatal_error("Can't override the module id for multiple files");
  512. (*ModuleOrErr)->setModuleIdentifier(ThinLTOModuleId);
  513. }
  514. return std::move(*ModuleOrErr);
  515. }
  516. static void writeModuleToFile(Module &TheModule, StringRef Filename) {
  517. std::error_code EC;
  518. raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::OF_None);
  519. error(EC, "error opening the file '" + Filename + "'");
  520. maybeVerifyModule(TheModule);
  521. WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
  522. }
  523. class ThinLTOProcessing {
  524. public:
  525. ThinLTOCodeGenerator ThinGenerator;
  526. ThinLTOProcessing(const TargetOptions &Options) {
  527. ThinGenerator.setCodePICModel(codegen::getExplicitRelocModel());
  528. ThinGenerator.setTargetOptions(Options);
  529. ThinGenerator.setCacheDir(ThinLTOCacheDir);
  530. ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
  531. ThinGenerator.setCacheEntryExpiration(ThinLTOCacheEntryExpiration);
  532. ThinGenerator.setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
  533. ThinGenerator.setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
  534. ThinGenerator.setFreestanding(EnableFreestanding);
  535. ThinGenerator.setUseNewPM(UseNewPM);
  536. ThinGenerator.setDebugPassManager(DebugPassManager);
  537. // Add all the exported symbols to the table of symbols to preserve.
  538. for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
  539. ThinGenerator.preserveSymbol(ExportedSymbols[i]);
  540. }
  541. void run() {
  542. switch (ThinLTOMode) {
  543. case THINLINK:
  544. return thinLink();
  545. case THINDISTRIBUTE:
  546. return distributedIndexes();
  547. case THINEMITIMPORTS:
  548. return emitImports();
  549. case THINPROMOTE:
  550. return promote();
  551. case THINIMPORT:
  552. return import();
  553. case THININTERNALIZE:
  554. return internalize();
  555. case THINOPT:
  556. return optimize();
  557. case THINCODEGEN:
  558. return codegen();
  559. case THINALL:
  560. return runAll();
  561. }
  562. }
  563. private:
  564. /// Load the input files, create the combined index, and write it out.
  565. void thinLink() {
  566. // Perform "ThinLink": just produce the index
  567. if (OutputFilename.empty())
  568. report_fatal_error(
  569. "OutputFilename is necessary to store the combined index.\n");
  570. LLVMContext Ctx;
  571. std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
  572. for (unsigned i = 0; i < InputFilenames.size(); ++i) {
  573. auto &Filename = InputFilenames[i];
  574. std::string CurrentActivity = "loading file '" + Filename + "'";
  575. auto InputOrErr = MemoryBuffer::getFile(Filename);
  576. error(InputOrErr, "error " + CurrentActivity);
  577. InputBuffers.push_back(std::move(*InputOrErr));
  578. ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
  579. }
  580. auto CombinedIndex = ThinGenerator.linkCombinedIndex();
  581. if (!CombinedIndex)
  582. report_fatal_error("ThinLink didn't create an index");
  583. std::error_code EC;
  584. raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
  585. error(EC, "error opening the file '" + OutputFilename + "'");
  586. writeIndexToFile(*CombinedIndex, OS);
  587. }
  588. /// Load the combined index from disk, then compute and generate
  589. /// individual index files suitable for ThinLTO distributed backend builds
  590. /// on the files mentioned on the command line (these must match the index
  591. /// content).
  592. void distributedIndexes() {
  593. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  594. report_fatal_error("Can't handle a single output filename and multiple "
  595. "input files, do not provide an output filename and "
  596. "the output files will be suffixed from the input "
  597. "ones.");
  598. std::string OldPrefix, NewPrefix;
  599. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  600. auto Index = loadCombinedIndex();
  601. for (auto &Filename : InputFilenames) {
  602. LLVMContext Ctx;
  603. auto Buffer = loadFile(Filename);
  604. auto Input = loadInputFile(Buffer->getMemBufferRef());
  605. auto TheModule = loadModuleFromInput(*Input, Ctx);
  606. // Build a map of module to the GUIDs and summary objects that should
  607. // be written to its index.
  608. std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
  609. ThinGenerator.gatherImportedSummariesForModule(
  610. *TheModule, *Index, ModuleToSummariesForIndex, *Input);
  611. std::string OutputName = OutputFilename;
  612. if (OutputName.empty()) {
  613. OutputName = Filename + ".thinlto.bc";
  614. }
  615. OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
  616. std::error_code EC;
  617. raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::OF_None);
  618. error(EC, "error opening the file '" + OutputName + "'");
  619. writeIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
  620. }
  621. }
  622. /// Load the combined index from disk, compute the imports, and emit
  623. /// the import file lists for each module to disk.
  624. void emitImports() {
  625. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  626. report_fatal_error("Can't handle a single output filename and multiple "
  627. "input files, do not provide an output filename and "
  628. "the output files will be suffixed from the input "
  629. "ones.");
  630. std::string OldPrefix, NewPrefix;
  631. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  632. auto Index = loadCombinedIndex();
  633. for (auto &Filename : InputFilenames) {
  634. LLVMContext Ctx;
  635. auto Buffer = loadFile(Filename);
  636. auto Input = loadInputFile(Buffer->getMemBufferRef());
  637. auto TheModule = loadModuleFromInput(*Input, Ctx);
  638. std::string OutputName = OutputFilename;
  639. if (OutputName.empty()) {
  640. OutputName = Filename + ".imports";
  641. }
  642. OutputName =
  643. getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
  644. ThinGenerator.emitImports(*TheModule, OutputName, *Index, *Input);
  645. }
  646. }
  647. /// Load the combined index from disk, then load every file referenced by
  648. /// the index and add them to the generator, finally perform the promotion
  649. /// on the files mentioned on the command line (these must match the index
  650. /// content).
  651. void promote() {
  652. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  653. report_fatal_error("Can't handle a single output filename and multiple "
  654. "input files, do not provide an output filename and "
  655. "the output files will be suffixed from the input "
  656. "ones.");
  657. auto Index = loadCombinedIndex();
  658. for (auto &Filename : InputFilenames) {
  659. LLVMContext Ctx;
  660. auto Buffer = loadFile(Filename);
  661. auto Input = loadInputFile(Buffer->getMemBufferRef());
  662. auto TheModule = loadModuleFromInput(*Input, Ctx);
  663. ThinGenerator.promote(*TheModule, *Index, *Input);
  664. std::string OutputName = OutputFilename;
  665. if (OutputName.empty()) {
  666. OutputName = Filename + ".thinlto.promoted.bc";
  667. }
  668. writeModuleToFile(*TheModule, OutputName);
  669. }
  670. }
  671. /// Load the combined index from disk, then load every file referenced by
  672. /// the index and add them to the generator, then performs the promotion and
  673. /// cross module importing on the files mentioned on the command line
  674. /// (these must match the index content).
  675. void import() {
  676. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  677. report_fatal_error("Can't handle a single output filename and multiple "
  678. "input files, do not provide an output filename and "
  679. "the output files will be suffixed from the input "
  680. "ones.");
  681. auto Index = loadCombinedIndex();
  682. auto InputBuffers = loadAllFilesForIndex(*Index);
  683. for (auto &MemBuffer : InputBuffers)
  684. ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
  685. MemBuffer->getBuffer());
  686. for (auto &Filename : InputFilenames) {
  687. LLVMContext Ctx;
  688. auto Buffer = loadFile(Filename);
  689. auto Input = loadInputFile(Buffer->getMemBufferRef());
  690. auto TheModule = loadModuleFromInput(*Input, Ctx);
  691. ThinGenerator.crossModuleImport(*TheModule, *Index, *Input);
  692. std::string OutputName = OutputFilename;
  693. if (OutputName.empty()) {
  694. OutputName = Filename + ".thinlto.imported.bc";
  695. }
  696. writeModuleToFile(*TheModule, OutputName);
  697. }
  698. }
  699. void internalize() {
  700. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  701. report_fatal_error("Can't handle a single output filename and multiple "
  702. "input files, do not provide an output filename and "
  703. "the output files will be suffixed from the input "
  704. "ones.");
  705. if (ExportedSymbols.empty())
  706. errs() << "Warning: -internalize will not perform without "
  707. "-exported-symbol\n";
  708. auto Index = loadCombinedIndex();
  709. auto InputBuffers = loadAllFilesForIndex(*Index);
  710. for (auto &MemBuffer : InputBuffers)
  711. ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
  712. MemBuffer->getBuffer());
  713. for (auto &Filename : InputFilenames) {
  714. LLVMContext Ctx;
  715. auto Buffer = loadFile(Filename);
  716. auto Input = loadInputFile(Buffer->getMemBufferRef());
  717. auto TheModule = loadModuleFromInput(*Input, Ctx);
  718. ThinGenerator.internalize(*TheModule, *Index, *Input);
  719. std::string OutputName = OutputFilename;
  720. if (OutputName.empty()) {
  721. OutputName = Filename + ".thinlto.internalized.bc";
  722. }
  723. writeModuleToFile(*TheModule, OutputName);
  724. }
  725. }
  726. void optimize() {
  727. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  728. report_fatal_error("Can't handle a single output filename and multiple "
  729. "input files, do not provide an output filename and "
  730. "the output files will be suffixed from the input "
  731. "ones.");
  732. if (!ThinLTOIndex.empty())
  733. errs() << "Warning: -thinlto-index ignored for optimize stage";
  734. for (auto &Filename : InputFilenames) {
  735. LLVMContext Ctx;
  736. auto Buffer = loadFile(Filename);
  737. auto Input = loadInputFile(Buffer->getMemBufferRef());
  738. auto TheModule = loadModuleFromInput(*Input, Ctx);
  739. ThinGenerator.optimize(*TheModule);
  740. std::string OutputName = OutputFilename;
  741. if (OutputName.empty()) {
  742. OutputName = Filename + ".thinlto.imported.bc";
  743. }
  744. writeModuleToFile(*TheModule, OutputName);
  745. }
  746. }
  747. void codegen() {
  748. if (InputFilenames.size() != 1 && !OutputFilename.empty())
  749. report_fatal_error("Can't handle a single output filename and multiple "
  750. "input files, do not provide an output filename and "
  751. "the output files will be suffixed from the input "
  752. "ones.");
  753. if (!ThinLTOIndex.empty())
  754. errs() << "Warning: -thinlto-index ignored for codegen stage";
  755. std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
  756. for (auto &Filename : InputFilenames) {
  757. LLVMContext Ctx;
  758. auto InputOrErr = MemoryBuffer::getFile(Filename);
  759. error(InputOrErr, "error " + CurrentActivity);
  760. InputBuffers.push_back(std::move(*InputOrErr));
  761. ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
  762. }
  763. ThinGenerator.setCodeGenOnly(true);
  764. ThinGenerator.run();
  765. for (auto BinName :
  766. zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
  767. std::string OutputName = OutputFilename;
  768. if (OutputName.empty())
  769. OutputName = std::get<1>(BinName) + ".thinlto.o";
  770. else if (OutputName == "-") {
  771. outs() << std::get<0>(BinName)->getBuffer();
  772. return;
  773. }
  774. std::error_code EC;
  775. raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::OF_None);
  776. error(EC, "error opening the file '" + OutputName + "'");
  777. OS << std::get<0>(BinName)->getBuffer();
  778. }
  779. }
  780. /// Full ThinLTO process
  781. void runAll() {
  782. if (!OutputFilename.empty())
  783. report_fatal_error("Do not provide an output filename for ThinLTO "
  784. " processing, the output files will be suffixed from "
  785. "the input ones.");
  786. if (!ThinLTOIndex.empty())
  787. errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
  788. LLVMContext Ctx;
  789. std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
  790. for (unsigned i = 0; i < InputFilenames.size(); ++i) {
  791. auto &Filename = InputFilenames[i];
  792. std::string CurrentActivity = "loading file '" + Filename + "'";
  793. auto InputOrErr = MemoryBuffer::getFile(Filename);
  794. error(InputOrErr, "error " + CurrentActivity);
  795. InputBuffers.push_back(std::move(*InputOrErr));
  796. ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
  797. }
  798. if (!ThinLTOSaveTempsPrefix.empty())
  799. ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
  800. if (!ThinLTOGeneratedObjectsDir.empty()) {
  801. ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
  802. ThinGenerator.run();
  803. return;
  804. }
  805. ThinGenerator.run();
  806. auto &Binaries = ThinGenerator.getProducedBinaries();
  807. if (Binaries.size() != InputFilenames.size())
  808. report_fatal_error("Number of output objects does not match the number "
  809. "of inputs");
  810. for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
  811. auto OutputName = InputFilenames[BufID] + ".thinlto.o";
  812. std::error_code EC;
  813. raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::OF_None);
  814. error(EC, "error opening the file '" + OutputName + "'");
  815. OS << Binaries[BufID]->getBuffer();
  816. }
  817. }
  818. /// Load the combined index from disk, then load every file referenced by
  819. };
  820. } // end namespace thinlto
  821. int main(int argc, char **argv) {
  822. InitLLVM X(argc, argv);
  823. cl::HideUnrelatedOptions({&LTOCategory, &getColorCategory()});
  824. cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
  825. if (OptLevel < '0' || OptLevel > '3')
  826. error("optimization level must be between 0 and 3");
  827. // Initialize the configured targets.
  828. InitializeAllTargets();
  829. InitializeAllTargetMCs();
  830. InitializeAllAsmPrinters();
  831. InitializeAllAsmParsers();
  832. // set up the TargetOptions for the machine
  833. TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  834. if (ListSymbolsOnly || QueryHasCtorDtor) {
  835. testLTOModule(Options);
  836. return 0;
  837. }
  838. if (ListDependentLibrariesOnly) {
  839. listDependentLibraries();
  840. return 0;
  841. }
  842. if (IndexStats) {
  843. printIndexStats();
  844. return 0;
  845. }
  846. if (CheckHasObjC) {
  847. for (auto &Filename : InputFilenames) {
  848. ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
  849. Filename + "': ");
  850. std::unique_ptr<MemoryBuffer> BufferOrErr =
  851. ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
  852. auto Buffer = std::move(BufferOrErr.get());
  853. if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
  854. outs() << "Bitcode " << Filename << " contains ObjC\n";
  855. else
  856. outs() << "Bitcode " << Filename << " does not contain ObjC\n";
  857. }
  858. return 0;
  859. }
  860. if (PrintMachOCPUOnly) {
  861. printMachOCPUOnly();
  862. return 0;
  863. }
  864. if (ThinLTOMode.getNumOccurrences()) {
  865. if (ThinLTOMode.getNumOccurrences() > 1)
  866. report_fatal_error("You can't specify more than one -thinlto-action");
  867. thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
  868. ThinLTOProcessor.run();
  869. return 0;
  870. }
  871. if (ThinLTO) {
  872. createCombinedModuleSummaryIndex();
  873. return 0;
  874. }
  875. unsigned BaseArg = 0;
  876. LLVMContext Context;
  877. Context.setDiagnosticHandler(std::make_unique<LLVMLTODiagnosticHandler>(),
  878. true);
  879. LTOCodeGenerator CodeGen(Context);
  880. CodeGen.setDisableVerify(DisableVerify);
  881. if (UseDiagnosticHandler)
  882. CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
  883. CodeGen.setCodePICModel(codegen::getExplicitRelocModel());
  884. CodeGen.setFreestanding(EnableFreestanding);
  885. CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
  886. CodeGen.setTargetOptions(Options);
  887. CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
  888. StringSet<MallocAllocator> DSOSymbolsSet;
  889. for (unsigned i = 0; i < DSOSymbols.size(); ++i)
  890. DSOSymbolsSet.insert(DSOSymbols[i]);
  891. std::vector<std::string> KeptDSOSyms;
  892. for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
  893. CurrentActivity = "loading file '" + InputFilenames[i] + "'";
  894. ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
  895. LTOModule::createFromFile(Context, InputFilenames[i], Options);
  896. std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
  897. CurrentActivity = "";
  898. unsigned NumSyms = Module->getSymbolCount();
  899. for (unsigned I = 0; I < NumSyms; ++I) {
  900. StringRef Name = Module->getSymbolName(I);
  901. if (!DSOSymbolsSet.count(Name))
  902. continue;
  903. lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
  904. unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
  905. if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
  906. KeptDSOSyms.push_back(std::string(Name));
  907. }
  908. // We use the first input module as the destination module when
  909. // SetMergedModule is true.
  910. if (SetMergedModule && i == BaseArg) {
  911. // Transfer ownership to the code generator.
  912. CodeGen.setModule(std::move(Module));
  913. } else if (!CodeGen.addModule(Module.get())) {
  914. // Print a message here so that we know addModule() did not abort.
  915. error("error adding file '" + InputFilenames[i] + "'");
  916. }
  917. }
  918. // Add all the exported symbols to the table of symbols to preserve.
  919. for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
  920. CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
  921. // Add all the dso symbols to the table of symbols to expose.
  922. for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
  923. CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
  924. // Set cpu and attrs strings for the default target/subtarget.
  925. CodeGen.setCpu(codegen::getMCPU());
  926. CodeGen.setOptLevel(OptLevel - '0');
  927. CodeGen.setAttrs(codegen::getMAttrs());
  928. CodeGen.setUseNewPM(UseNewPM);
  929. if (auto FT = codegen::getExplicitFileType())
  930. CodeGen.setFileType(FT.getValue());
  931. if (!OutputFilename.empty()) {
  932. if (SaveLinkedModuleFile) {
  933. std::string ModuleFilename = OutputFilename;
  934. ModuleFilename += ".linked.bc";
  935. std::string ErrMsg;
  936. if (!CodeGen.writeMergedModules(ModuleFilename))
  937. error("writing linked module failed.");
  938. }
  939. if (!CodeGen.optimize()) {
  940. // Diagnostic messages should have been printed by the handler.
  941. error("error optimizing the code");
  942. }
  943. if (SaveModuleFile) {
  944. std::string ModuleFilename = OutputFilename;
  945. ModuleFilename += ".merged.bc";
  946. std::string ErrMsg;
  947. if (!CodeGen.writeMergedModules(ModuleFilename))
  948. error("writing merged module failed.");
  949. }
  950. auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> {
  951. std::string PartFilename = OutputFilename;
  952. if (Parallelism != 1)
  953. PartFilename += "." + utostr(Task);
  954. std::error_code EC;
  955. auto S =
  956. std::make_unique<raw_fd_ostream>(PartFilename, EC, sys::fs::OF_None);
  957. if (EC)
  958. error("error opening the file '" + PartFilename + "': " + EC.message());
  959. return std::make_unique<CachedFileStream>(std::move(S));
  960. };
  961. if (!CodeGen.compileOptimized(AddStream, Parallelism))
  962. // Diagnostic messages should have been printed by the handler.
  963. error("error compiling the code");
  964. } else {
  965. if (Parallelism != 1)
  966. error("-j must be specified together with -o");
  967. if (SaveModuleFile)
  968. error(": -save-merged-module must be specified with -o");
  969. const char *OutputName = nullptr;
  970. if (!CodeGen.compile_to_file(&OutputName))
  971. error("error compiling the code");
  972. // Diagnostic messages should have been printed by the handler.
  973. outs() << "Wrote native object file '" << OutputName << "'\n";
  974. }
  975. return 0;
  976. }