llc.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
  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 is the llc code generator driver. It provides a convenient
  10. // command-line interface for generating native assembly-language code
  11. // or C code, given LLVM bitcode.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/Analysis/TargetLibraryInfo.h"
  17. #include "llvm/CodeGen/CommandFlags.h"
  18. #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
  19. #include "llvm/CodeGen/LinkAllCodegenComponents.h"
  20. #include "llvm/CodeGen/MIRParser/MIRParser.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineModuleInfo.h"
  23. #include "llvm/CodeGen/TargetPassConfig.h"
  24. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  25. #include "llvm/IR/AutoUpgrade.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DiagnosticInfo.h"
  28. #include "llvm/IR/DiagnosticPrinter.h"
  29. #include "llvm/IR/IRPrintingPasses.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/LLVMRemarkStreamer.h"
  32. #include "llvm/IR/LegacyPassManager.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/Verifier.h"
  35. #include "llvm/IRReader/IRReader.h"
  36. #include "llvm/InitializePasses.h"
  37. #include "llvm/MC/SubtargetFeature.h"
  38. #include "llvm/Pass.h"
  39. #include "llvm/Remarks/HotnessThresholdParser.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/FileSystem.h"
  43. #include "llvm/Support/FormattedStream.h"
  44. #include "llvm/Support/Host.h"
  45. #include "llvm/Support/InitLLVM.h"
  46. #include "llvm/Support/ManagedStatic.h"
  47. #include "llvm/Support/PluginLoader.h"
  48. #include "llvm/Support/SourceMgr.h"
  49. #include "llvm/Support/TargetRegistry.h"
  50. #include "llvm/Support/TargetSelect.h"
  51. #include "llvm/Support/ToolOutputFile.h"
  52. #include "llvm/Support/WithColor.h"
  53. #include "llvm/Target/TargetLoweringObjectFile.h"
  54. #include "llvm/Target/TargetMachine.h"
  55. #include "llvm/Transforms/Utils/Cloning.h"
  56. #include <memory>
  57. using namespace llvm;
  58. static codegen::RegisterCodeGenFlags CGF;
  59. // General options for llc. Other pass-specific options are specified
  60. // within the corresponding llc passes, and target-specific options
  61. // and back-end code generation options are specified with the target machine.
  62. //
  63. static cl::opt<std::string>
  64. InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
  65. static cl::opt<std::string>
  66. InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
  67. static cl::opt<std::string>
  68. OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
  69. static cl::opt<std::string>
  70. SplitDwarfOutputFile("split-dwarf-output",
  71. cl::desc(".dwo output filename"),
  72. cl::value_desc("filename"));
  73. static cl::opt<unsigned>
  74. TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
  75. cl::value_desc("N"),
  76. cl::desc("Repeat compilation N times for timing"));
  77. static cl::opt<std::string>
  78. BinutilsVersion("binutils-version", cl::Hidden,
  79. cl::desc("Produced object files can use all ELF features "
  80. "supported by this binutils version and newer."
  81. "If -no-integrated-as is specified, the generated "
  82. "assembly will consider GNU as support."
  83. "'none' means that all ELF features can be used, "
  84. "regardless of binutils support"));
  85. static cl::opt<bool>
  86. NoIntegratedAssembler("no-integrated-as", cl::Hidden,
  87. cl::desc("Disable integrated assembler"));
  88. static cl::opt<bool>
  89. PreserveComments("preserve-as-comments", cl::Hidden,
  90. cl::desc("Preserve Comments in outputted assembly"),
  91. cl::init(true));
  92. // Determine optimization level.
  93. static cl::opt<char>
  94. OptLevel("O",
  95. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  96. "(default = '-O2')"),
  97. cl::Prefix,
  98. cl::ZeroOrMore,
  99. cl::init(' '));
  100. static cl::opt<std::string>
  101. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  102. static cl::opt<std::string> SplitDwarfFile(
  103. "split-dwarf-file",
  104. cl::desc(
  105. "Specify the name of the .dwo file to encode in the DWARF output"));
  106. static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
  107. cl::desc("Do not verify input module"));
  108. static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
  109. cl::desc("Disable simplify-libcalls"));
  110. static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
  111. cl::desc("Show encoding in .s output"));
  112. static cl::opt<bool> EnableDwarfDirectory(
  113. "enable-dwarf-directory", cl::Hidden,
  114. cl::desc("Use .file directives with an explicit directory."));
  115. static cl::opt<bool> AsmVerbose("asm-verbose",
  116. cl::desc("Add comments to directives."),
  117. cl::init(true));
  118. static cl::opt<bool>
  119. CompileTwice("compile-twice", cl::Hidden,
  120. cl::desc("Run everything twice, re-using the same pass "
  121. "manager and verify the result is the same."),
  122. cl::init(false));
  123. static cl::opt<bool> DiscardValueNames(
  124. "discard-value-names",
  125. cl::desc("Discard names from Value (other than GlobalValue)."),
  126. cl::init(false), cl::Hidden);
  127. static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
  128. static cl::opt<bool> RemarksWithHotness(
  129. "pass-remarks-with-hotness",
  130. cl::desc("With PGO, include profile count in optimization remarks"),
  131. cl::Hidden);
  132. static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
  133. RemarksHotnessThreshold(
  134. "pass-remarks-hotness-threshold",
  135. cl::desc("Minimum profile count required for "
  136. "an optimization remark to be output. "
  137. "Use 'auto' to apply the threshold from profile summary."),
  138. cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
  139. static cl::opt<std::string>
  140. RemarksFilename("pass-remarks-output",
  141. cl::desc("Output filename for pass remarks"),
  142. cl::value_desc("filename"));
  143. static cl::opt<std::string>
  144. RemarksPasses("pass-remarks-filter",
  145. cl::desc("Only record optimization remarks from passes whose "
  146. "names match the given regular expression"),
  147. cl::value_desc("regex"));
  148. static cl::opt<std::string> RemarksFormat(
  149. "pass-remarks-format",
  150. cl::desc("The format used for serializing remarks (default: YAML)"),
  151. cl::value_desc("format"), cl::init("yaml"));
  152. namespace {
  153. static ManagedStatic<std::vector<std::string>> RunPassNames;
  154. struct RunPassOption {
  155. void operator=(const std::string &Val) const {
  156. if (Val.empty())
  157. return;
  158. SmallVector<StringRef, 8> PassNames;
  159. StringRef(Val).split(PassNames, ',', -1, false);
  160. for (auto PassName : PassNames)
  161. RunPassNames->push_back(std::string(PassName));
  162. }
  163. };
  164. }
  165. static RunPassOption RunPassOpt;
  166. static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
  167. "run-pass",
  168. cl::desc("Run compiler only for specified passes (comma separated list)"),
  169. cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
  170. static int compileModule(char **, LLVMContext &);
  171. LLVM_ATTRIBUTE_NORETURN static void reportError(Twine Msg,
  172. StringRef Filename = "") {
  173. SmallString<256> Prefix;
  174. if (!Filename.empty()) {
  175. if (Filename == "-")
  176. Filename = "<stdin>";
  177. ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
  178. }
  179. WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
  180. exit(1);
  181. }
  182. LLVM_ATTRIBUTE_NORETURN static void reportError(Error Err, StringRef Filename) {
  183. assert(Err);
  184. handleAllErrors(createFileError(Filename, std::move(Err)),
  185. [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
  186. llvm_unreachable("reportError() should not return");
  187. }
  188. static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
  189. Triple::OSType OS,
  190. const char *ProgName) {
  191. // If we don't yet have an output filename, make one.
  192. if (OutputFilename.empty()) {
  193. if (InputFilename == "-")
  194. OutputFilename = "-";
  195. else {
  196. // If InputFilename ends in .bc or .ll, remove it.
  197. StringRef IFN = InputFilename;
  198. if (IFN.endswith(".bc") || IFN.endswith(".ll"))
  199. OutputFilename = std::string(IFN.drop_back(3));
  200. else if (IFN.endswith(".mir"))
  201. OutputFilename = std::string(IFN.drop_back(4));
  202. else
  203. OutputFilename = std::string(IFN);
  204. switch (codegen::getFileType()) {
  205. case CGFT_AssemblyFile:
  206. if (TargetName[0] == 'c') {
  207. if (TargetName[1] == 0)
  208. OutputFilename += ".cbe.c";
  209. else if (TargetName[1] == 'p' && TargetName[2] == 'p')
  210. OutputFilename += ".cpp";
  211. else
  212. OutputFilename += ".s";
  213. } else
  214. OutputFilename += ".s";
  215. break;
  216. case CGFT_ObjectFile:
  217. if (OS == Triple::Win32)
  218. OutputFilename += ".obj";
  219. else
  220. OutputFilename += ".o";
  221. break;
  222. case CGFT_Null:
  223. OutputFilename = "-";
  224. break;
  225. }
  226. }
  227. }
  228. // Decide if we need "binary" output.
  229. bool Binary = false;
  230. switch (codegen::getFileType()) {
  231. case CGFT_AssemblyFile:
  232. break;
  233. case CGFT_ObjectFile:
  234. case CGFT_Null:
  235. Binary = true;
  236. break;
  237. }
  238. // Open the file.
  239. std::error_code EC;
  240. sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
  241. if (!Binary)
  242. OpenFlags |= sys::fs::OF_Text;
  243. auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
  244. if (EC) {
  245. reportError(EC.message());
  246. return nullptr;
  247. }
  248. return FDOut;
  249. }
  250. struct LLCDiagnosticHandler : public DiagnosticHandler {
  251. bool *HasError;
  252. LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
  253. bool handleDiagnostics(const DiagnosticInfo &DI) override {
  254. if (DI.getSeverity() == DS_Error)
  255. *HasError = true;
  256. if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
  257. if (!Remark->isEnabled())
  258. return true;
  259. DiagnosticPrinterRawOStream DP(errs());
  260. errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
  261. DI.print(DP);
  262. errs() << "\n";
  263. return true;
  264. }
  265. };
  266. static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
  267. unsigned LocCookie) {
  268. bool *HasError = static_cast<bool *>(Context);
  269. if (SMD.getKind() == SourceMgr::DK_Error)
  270. *HasError = true;
  271. SMD.print(nullptr, errs());
  272. // For testing purposes, we print the LocCookie here.
  273. if (LocCookie)
  274. WithColor::note() << "!srcloc = " << LocCookie << "\n";
  275. }
  276. // main - Entry point for the llc compiler.
  277. //
  278. int main(int argc, char **argv) {
  279. InitLLVM X(argc, argv);
  280. // Enable debug stream buffering.
  281. EnableDebugBuffering = true;
  282. LLVMContext Context;
  283. // Initialize targets first, so that --version shows registered targets.
  284. InitializeAllTargets();
  285. InitializeAllTargetMCs();
  286. InitializeAllAsmPrinters();
  287. InitializeAllAsmParsers();
  288. // Initialize codegen and IR passes used by llc so that the -print-after,
  289. // -print-before, and -stop-after options work.
  290. PassRegistry *Registry = PassRegistry::getPassRegistry();
  291. initializeCore(*Registry);
  292. initializeCodeGen(*Registry);
  293. initializeLoopStrengthReducePass(*Registry);
  294. initializeLowerIntrinsicsPass(*Registry);
  295. initializeEntryExitInstrumenterPass(*Registry);
  296. initializePostInlineEntryExitInstrumenterPass(*Registry);
  297. initializeUnreachableBlockElimLegacyPassPass(*Registry);
  298. initializeConstantHoistingLegacyPassPass(*Registry);
  299. initializeScalarOpts(*Registry);
  300. initializeVectorization(*Registry);
  301. initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
  302. initializeExpandReductionsPass(*Registry);
  303. initializeHardwareLoopsPass(*Registry);
  304. initializeTransformUtils(*Registry);
  305. // Initialize debugging passes.
  306. initializeScavengerTestPass(*Registry);
  307. // Register the target printer for --version.
  308. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  309. cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
  310. Context.setDiscardValueNames(DiscardValueNames);
  311. // Set a diagnostic handler that doesn't exit on the first error
  312. bool HasError = false;
  313. Context.setDiagnosticHandler(
  314. std::make_unique<LLCDiagnosticHandler>(&HasError));
  315. Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
  316. Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
  317. setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
  318. RemarksFormat, RemarksWithHotness,
  319. RemarksHotnessThreshold);
  320. if (Error E = RemarksFileOrErr.takeError())
  321. reportError(std::move(E), RemarksFilename);
  322. std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
  323. if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
  324. reportError("input language must be '', 'IR' or 'MIR'");
  325. // Compile the module TimeCompilations times to give better compile time
  326. // metrics.
  327. for (unsigned I = TimeCompilations; I; --I)
  328. if (int RetVal = compileModule(argv, Context))
  329. return RetVal;
  330. if (RemarksFile)
  331. RemarksFile->keep();
  332. return 0;
  333. }
  334. static bool addPass(PassManagerBase &PM, const char *argv0,
  335. StringRef PassName, TargetPassConfig &TPC) {
  336. if (PassName == "none")
  337. return false;
  338. const PassRegistry *PR = PassRegistry::getPassRegistry();
  339. const PassInfo *PI = PR->getPassInfo(PassName);
  340. if (!PI) {
  341. WithColor::error(errs(), argv0)
  342. << "run-pass " << PassName << " is not registered.\n";
  343. return true;
  344. }
  345. Pass *P;
  346. if (PI->getNormalCtor())
  347. P = PI->getNormalCtor()();
  348. else {
  349. WithColor::error(errs(), argv0)
  350. << "cannot create pass: " << PI->getPassName() << "\n";
  351. return true;
  352. }
  353. std::string Banner = std::string("After ") + std::string(P->getPassName());
  354. TPC.addMachinePrePasses();
  355. PM.add(P);
  356. TPC.addMachinePostPasses(Banner);
  357. return false;
  358. }
  359. static int compileModule(char **argv, LLVMContext &Context) {
  360. // Load the module to be compiled...
  361. SMDiagnostic Err;
  362. std::unique_ptr<Module> M;
  363. std::unique_ptr<MIRParser> MIR;
  364. Triple TheTriple;
  365. std::string CPUStr = codegen::getCPUStr(),
  366. FeaturesStr = codegen::getFeaturesStr();
  367. // Set attributes on functions as loaded from MIR from command line arguments.
  368. auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
  369. codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
  370. };
  371. auto MAttrs = codegen::getMAttrs();
  372. bool SkipModule = codegen::getMCPU() == "help" ||
  373. (!MAttrs.empty() && MAttrs.front() == "help");
  374. CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  375. switch (OptLevel) {
  376. default:
  377. WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
  378. return 1;
  379. case ' ': break;
  380. case '0': OLvl = CodeGenOpt::None; break;
  381. case '1': OLvl = CodeGenOpt::Less; break;
  382. case '2': OLvl = CodeGenOpt::Default; break;
  383. case '3': OLvl = CodeGenOpt::Aggressive; break;
  384. }
  385. // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
  386. // use that to indicate the MC default.
  387. if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
  388. StringRef V = BinutilsVersion.getValue();
  389. unsigned Num;
  390. if (V.consumeInteger(10, Num) || Num == 0 ||
  391. !(V.empty() ||
  392. (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
  393. WithColor::error(errs(), argv[0])
  394. << "invalid -binutils-version, accepting 'none' or major.minor\n";
  395. return 1;
  396. }
  397. }
  398. TargetOptions Options;
  399. auto InitializeOptions = [&](const Triple &TheTriple) {
  400. Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
  401. Options.BinutilsVersion =
  402. TargetMachine::parseBinutilsVersion(BinutilsVersion);
  403. Options.DisableIntegratedAS = NoIntegratedAssembler;
  404. Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
  405. Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
  406. Options.MCOptions.AsmVerbose = AsmVerbose;
  407. Options.MCOptions.PreserveAsmComments = PreserveComments;
  408. Options.MCOptions.IASSearchPaths = IncludeDirs;
  409. Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
  410. };
  411. Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
  412. const Target *TheTarget = nullptr;
  413. std::unique_ptr<TargetMachine> Target;
  414. // If user just wants to list available options, skip module loading
  415. if (!SkipModule) {
  416. auto SetDataLayout =
  417. [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
  418. // If we are supposed to override the target triple, do so now.
  419. std::string IRTargetTriple = DataLayoutTargetTriple.str();
  420. if (!TargetTriple.empty())
  421. IRTargetTriple = Triple::normalize(TargetTriple);
  422. TheTriple = Triple(IRTargetTriple);
  423. if (TheTriple.getTriple().empty())
  424. TheTriple.setTriple(sys::getDefaultTargetTriple());
  425. std::string Error;
  426. TheTarget =
  427. TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
  428. if (!TheTarget) {
  429. WithColor::error(errs(), argv[0]) << Error;
  430. exit(1);
  431. }
  432. // On AIX, setting the relocation model to anything other than PIC is
  433. // considered a user error.
  434. if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_)
  435. reportError("invalid relocation model, AIX only supports PIC",
  436. InputFilename);
  437. InitializeOptions(TheTriple);
  438. Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
  439. TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
  440. codegen::getExplicitCodeModel(), OLvl));
  441. assert(Target && "Could not allocate target machine!");
  442. return Target->createDataLayout().getStringRepresentation();
  443. };
  444. if (InputLanguage == "mir" ||
  445. (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
  446. MIR = createMIRParserFromFile(InputFilename, Err, Context,
  447. setMIRFunctionAttributes);
  448. if (MIR)
  449. M = MIR->parseIRModule(SetDataLayout);
  450. } else {
  451. M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
  452. }
  453. if (!M) {
  454. Err.print(argv[0], WithColor::error(errs(), argv[0]));
  455. return 1;
  456. }
  457. if (!TargetTriple.empty())
  458. M->setTargetTriple(Triple::normalize(TargetTriple));
  459. } else {
  460. TheTriple = Triple(Triple::normalize(TargetTriple));
  461. if (TheTriple.getTriple().empty())
  462. TheTriple.setTriple(sys::getDefaultTargetTriple());
  463. // Get the target specific parser.
  464. std::string Error;
  465. TheTarget =
  466. TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
  467. if (!TheTarget) {
  468. WithColor::error(errs(), argv[0]) << Error;
  469. return 1;
  470. }
  471. // On AIX, setting the relocation model to anything other than PIC is
  472. // considered a user error.
  473. if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
  474. WithColor::error(errs(), argv[0])
  475. << "invalid relocation model, AIX only supports PIC.\n";
  476. return 1;
  477. }
  478. InitializeOptions(TheTriple);
  479. Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
  480. TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
  481. codegen::getExplicitCodeModel(), OLvl));
  482. assert(Target && "Could not allocate target machine!");
  483. // If we don't have a module then just exit now. We do this down
  484. // here since the CPU/Feature help is underneath the target machine
  485. // creation.
  486. return 0;
  487. }
  488. assert(M && "Should have exited if we didn't have a module!");
  489. if (codegen::getFloatABIForCalls() != FloatABI::Default)
  490. Options.FloatABIType = codegen::getFloatABIForCalls();
  491. // Figure out where we are going to send the output.
  492. std::unique_ptr<ToolOutputFile> Out =
  493. GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
  494. if (!Out) return 1;
  495. std::unique_ptr<ToolOutputFile> DwoOut;
  496. if (!SplitDwarfOutputFile.empty()) {
  497. std::error_code EC;
  498. DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
  499. sys::fs::OF_None);
  500. if (EC)
  501. reportError(EC.message(), SplitDwarfOutputFile);
  502. }
  503. // Build up all of the passes that we want to do to the module.
  504. legacy::PassManager PM;
  505. // Add an appropriate TargetLibraryInfo pass for the module's triple.
  506. TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
  507. // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  508. if (DisableSimplifyLibCalls)
  509. TLII.disableAllFunctions();
  510. PM.add(new TargetLibraryInfoWrapperPass(TLII));
  511. // Verify module immediately to catch problems before doInitialization() is
  512. // called on any passes.
  513. if (!NoVerify && verifyModule(*M, &errs()))
  514. reportError("input module cannot be verified", InputFilename);
  515. // Override function attributes based on CPUStr, FeaturesStr, and command line
  516. // flags.
  517. codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
  518. if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
  519. WithColor::warning(errs(), argv[0])
  520. << ": warning: ignoring -mc-relax-all because filetype != obj";
  521. {
  522. raw_pwrite_stream *OS = &Out->os();
  523. // Manually do the buffering rather than using buffer_ostream,
  524. // so we can memcmp the contents in CompileTwice mode
  525. SmallVector<char, 0> Buffer;
  526. std::unique_ptr<raw_svector_ostream> BOS;
  527. if ((codegen::getFileType() != CGFT_AssemblyFile &&
  528. !Out->os().supportsSeeking()) ||
  529. CompileTwice) {
  530. BOS = std::make_unique<raw_svector_ostream>(Buffer);
  531. OS = BOS.get();
  532. }
  533. const char *argv0 = argv[0];
  534. LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
  535. MachineModuleInfoWrapperPass *MMIWP =
  536. new MachineModuleInfoWrapperPass(&LLVMTM);
  537. // Construct a custom pass pipeline that starts after instruction
  538. // selection.
  539. if (!RunPassNames->empty()) {
  540. if (!MIR) {
  541. WithColor::warning(errs(), argv[0])
  542. << "run-pass is for .mir file only.\n";
  543. return 1;
  544. }
  545. TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
  546. if (TPC.hasLimitedCodeGenPipeline()) {
  547. WithColor::warning(errs(), argv[0])
  548. << "run-pass cannot be used with "
  549. << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
  550. return 1;
  551. }
  552. TPC.setDisableVerify(NoVerify);
  553. PM.add(&TPC);
  554. PM.add(MMIWP);
  555. TPC.printAndVerify("");
  556. for (const std::string &RunPassName : *RunPassNames) {
  557. if (addPass(PM, argv0, RunPassName, TPC))
  558. return 1;
  559. }
  560. TPC.setInitialized();
  561. PM.add(createPrintMIRPass(*OS));
  562. PM.add(createFreeMachineFunctionPass());
  563. } else if (Target->addPassesToEmitFile(
  564. PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
  565. codegen::getFileType(), NoVerify, MMIWP)) {
  566. reportError("target does not support generation of this file type");
  567. }
  568. const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
  569. ->Initialize(MMIWP->getMMI().getContext(), *Target);
  570. if (MIR) {
  571. assert(MMIWP && "Forgot to create MMIWP?");
  572. if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
  573. return 1;
  574. }
  575. // Before executing passes, print the final values of the LLVM options.
  576. cl::PrintOptionValues();
  577. // If requested, run the pass manager over the same module again,
  578. // to catch any bugs due to persistent state in the passes. Note that
  579. // opt has the same functionality, so it may be worth abstracting this out
  580. // in the future.
  581. SmallVector<char, 0> CompileTwiceBuffer;
  582. if (CompileTwice) {
  583. std::unique_ptr<Module> M2(llvm::CloneModule(*M));
  584. PM.run(*M2);
  585. CompileTwiceBuffer = Buffer;
  586. Buffer.clear();
  587. }
  588. PM.run(*M);
  589. auto HasError =
  590. ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
  591. if (*HasError)
  592. return 1;
  593. // Compare the two outputs and make sure they're the same
  594. if (CompileTwice) {
  595. if (Buffer.size() != CompileTwiceBuffer.size() ||
  596. (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
  597. 0)) {
  598. errs()
  599. << "Running the pass manager twice changed the output.\n"
  600. "Writing the result of the second run to the specified output\n"
  601. "To generate the one-run comparison binary, just run without\n"
  602. "the compile-twice option\n";
  603. Out->os() << Buffer;
  604. Out->keep();
  605. return 1;
  606. }
  607. }
  608. if (BOS) {
  609. Out->os() << Buffer;
  610. }
  611. }
  612. // Declare success.
  613. Out->keep();
  614. if (DwoOut)
  615. DwoOut->keep();
  616. return 0;
  617. }