llc.cpp 27 KB

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