llvm-lto.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. //===-- llvm-lto: a simple command-line program to link modules with LTO --===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This program takes in a list of bitcode files, links them, performs link-time
  11. // optimization, and outputs an object file.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/StringSet.h"
  15. #include "llvm/CodeGen/CommandFlags.h"
  16. #include "llvm/LTO/LTOCodeGenerator.h"
  17. #include "llvm/LTO/LTOModule.h"
  18. #include "llvm/Support/CommandLine.h"
  19. #include "llvm/Support/FileSystem.h"
  20. #include "llvm/Support/ManagedStatic.h"
  21. #include "llvm/Support/PrettyStackTrace.h"
  22. #include "llvm/Support/Signals.h"
  23. #include "llvm/Support/TargetSelect.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. using namespace llvm;
  26. static cl::opt<char>
  27. OptLevel("O",
  28. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  29. "(default = '-O2')"),
  30. cl::Prefix,
  31. cl::ZeroOrMore,
  32. cl::init('2'));
  33. static cl::opt<bool>
  34. DisableInline("disable-inlining", cl::init(false),
  35. cl::desc("Do not run the inliner pass"));
  36. static cl::opt<bool>
  37. DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
  38. cl::desc("Do not run the GVN load PRE pass"));
  39. static cl::opt<bool>
  40. DisableLTOVectorization("disable-lto-vectorization", cl::init(false),
  41. cl::desc("Do not run loop or slp vectorization during LTO"));
  42. static cl::opt<bool>
  43. UseDiagnosticHandler("use-diagnostic-handler", cl::init(false),
  44. cl::desc("Use a diagnostic handler to test the handler interface"));
  45. static cl::list<std::string>
  46. InputFilenames(cl::Positional, cl::OneOrMore,
  47. cl::desc("<input bitcode files>"));
  48. static cl::opt<std::string>
  49. OutputFilename("o", cl::init(""),
  50. cl::desc("Override output filename"),
  51. cl::value_desc("filename"));
  52. static cl::list<std::string>
  53. ExportedSymbols("exported-symbol",
  54. cl::desc("Symbol to export from the resulting object file"),
  55. cl::ZeroOrMore);
  56. static cl::list<std::string>
  57. DSOSymbols("dso-symbol",
  58. cl::desc("Symbol to put in the symtab in the resulting dso"),
  59. cl::ZeroOrMore);
  60. static cl::opt<bool> ListSymbolsOnly(
  61. "list-symbols-only", cl::init(false),
  62. cl::desc("Instead of running LTO, list the symbols in each IR file"));
  63. static cl::opt<bool> SetMergedModule(
  64. "set-merged-module", cl::init(false),
  65. cl::desc("Use the first input module as the merged module"));
  66. namespace {
  67. struct ModuleInfo {
  68. std::vector<bool> CanBeHidden;
  69. };
  70. }
  71. static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
  72. const char *Msg, void *) {
  73. switch (Severity) {
  74. case LTO_DS_NOTE:
  75. errs() << "note: ";
  76. break;
  77. case LTO_DS_REMARK:
  78. errs() << "remark: ";
  79. break;
  80. case LTO_DS_ERROR:
  81. errs() << "error: ";
  82. break;
  83. case LTO_DS_WARNING:
  84. errs() << "warning: ";
  85. break;
  86. }
  87. errs() << Msg << "\n";
  88. }
  89. static std::unique_ptr<LTOModule>
  90. getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
  91. const TargetOptions &Options, std::string &Error) {
  92. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  93. MemoryBuffer::getFile(Path);
  94. if (std::error_code EC = BufferOrErr.getError()) {
  95. Error = EC.message();
  96. return nullptr;
  97. }
  98. Buffer = std::move(BufferOrErr.get());
  99. return std::unique_ptr<LTOModule>(LTOModule::createInLocalContext(
  100. Buffer->getBufferStart(), Buffer->getBufferSize(), Options, Error, Path));
  101. }
  102. /// \brief List symbols in each IR file.
  103. ///
  104. /// The main point here is to provide lit-testable coverage for the LTOModule
  105. /// functionality that's exposed by the C API to list symbols. Moreover, this
  106. /// provides testing coverage for modules that have been created in their own
  107. /// contexts.
  108. static int listSymbols(StringRef Command, const TargetOptions &Options) {
  109. for (auto &Filename : InputFilenames) {
  110. std::string Error;
  111. std::unique_ptr<MemoryBuffer> Buffer;
  112. std::unique_ptr<LTOModule> Module =
  113. getLocalLTOModule(Filename, Buffer, Options, Error);
  114. if (!Module) {
  115. errs() << Command << ": error loading file '" << Filename
  116. << "': " << Error << "\n";
  117. return 1;
  118. }
  119. // List the symbols.
  120. outs() << Filename << ":\n";
  121. for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
  122. outs() << Module->getSymbolName(I) << "\n";
  123. }
  124. return 0;
  125. }
  126. int __cdecl main(int argc, char **argv) { // HLSL Change - __cdecl
  127. // Print a stack trace if we signal out.
  128. sys::PrintStackTraceOnErrorSignal();
  129. PrettyStackTraceProgram X(argc, argv);
  130. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  131. cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
  132. if (OptLevel < '0' || OptLevel > '3') {
  133. errs() << argv[0] << ": optimization level must be between 0 and 3\n";
  134. return 1;
  135. }
  136. // Initialize the configured targets.
  137. InitializeAllTargets();
  138. InitializeAllTargetMCs();
  139. InitializeAllAsmPrinters();
  140. InitializeAllAsmParsers();
  141. // set up the TargetOptions for the machine
  142. TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  143. if (ListSymbolsOnly)
  144. return listSymbols(argv[0], Options);
  145. unsigned BaseArg = 0;
  146. LTOCodeGenerator CodeGen;
  147. if (UseDiagnosticHandler)
  148. CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
  149. switch (RelocModel) {
  150. case Reloc::Static:
  151. CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_STATIC);
  152. break;
  153. case Reloc::PIC_:
  154. CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC);
  155. break;
  156. case Reloc::DynamicNoPIC:
  157. CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC);
  158. break;
  159. default:
  160. CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DEFAULT);
  161. }
  162. CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
  163. CodeGen.setTargetOptions(Options);
  164. llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
  165. for (unsigned i = 0; i < DSOSymbols.size(); ++i)
  166. DSOSymbolsSet.insert(DSOSymbols[i]);
  167. std::vector<std::string> KeptDSOSyms;
  168. for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
  169. std::string error;
  170. std::unique_ptr<LTOModule> Module(
  171. LTOModule::createFromFile(InputFilenames[i].c_str(), Options, error));
  172. if (!error.empty()) {
  173. errs() << argv[0] << ": error loading file '" << InputFilenames[i]
  174. << "': " << error << "\n";
  175. return 1;
  176. }
  177. LTOModule *LTOMod = Module.get();
  178. // We use the first input module as the destination module when
  179. // SetMergedModule is true.
  180. if (SetMergedModule && i == BaseArg) {
  181. // Transfer ownership to the code generator.
  182. CodeGen.setModule(Module.release());
  183. } else if (!CodeGen.addModule(Module.get()))
  184. return 1;
  185. unsigned NumSyms = LTOMod->getSymbolCount();
  186. for (unsigned I = 0; I < NumSyms; ++I) {
  187. StringRef Name = LTOMod->getSymbolName(I);
  188. if (!DSOSymbolsSet.count(Name))
  189. continue;
  190. lto_symbol_attributes Attrs = LTOMod->getSymbolAttributes(I);
  191. unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
  192. if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
  193. KeptDSOSyms.push_back(Name);
  194. }
  195. }
  196. // Add all the exported symbols to the table of symbols to preserve.
  197. for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
  198. CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
  199. // Add all the dso symbols to the table of symbols to expose.
  200. for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
  201. CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
  202. // Set cpu and attrs strings for the default target/subtarget.
  203. CodeGen.setCpu(MCPU.c_str());
  204. CodeGen.setOptLevel(OptLevel - '0');
  205. std::string attrs;
  206. for (unsigned i = 0; i < MAttrs.size(); ++i) {
  207. if (i > 0)
  208. attrs.append(",");
  209. attrs.append(MAttrs[i]);
  210. }
  211. if (!attrs.empty())
  212. CodeGen.setAttr(attrs.c_str());
  213. if (!OutputFilename.empty()) {
  214. std::string ErrorInfo;
  215. std::unique_ptr<MemoryBuffer> Code = CodeGen.compile(
  216. DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, ErrorInfo);
  217. if (!Code) {
  218. errs() << argv[0]
  219. << ": error compiling the code: " << ErrorInfo << "\n";
  220. return 1;
  221. }
  222. std::error_code EC;
  223. raw_fd_ostream FileStream(OutputFilename, EC, sys::fs::F_None);
  224. if (EC) {
  225. errs() << argv[0] << ": error opening the file '" << OutputFilename
  226. << "': " << EC.message() << "\n";
  227. return 1;
  228. }
  229. FileStream.write(Code->getBufferStart(), Code->getBufferSize());
  230. } else {
  231. std::string ErrorInfo;
  232. const char *OutputName = nullptr;
  233. if (!CodeGen.compile_to_file(&OutputName, DisableInline,
  234. DisableGVNLoadPRE, DisableLTOVectorization,
  235. ErrorInfo)) {
  236. errs() << argv[0]
  237. << ": error compiling the code: " << ErrorInfo
  238. << "\n";
  239. return 1;
  240. }
  241. outs() << "Wrote native object file '" << OutputName << "'\n";
  242. }
  243. return 0;
  244. }