llvm-exegesis.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. //===-- llvm-exegesis.cpp ---------------------------------------*- C++ -*-===//
  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. /// \file
  10. /// Measures execution properties (latencies/uops) of an instruction.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "lib/Analysis.h"
  14. #include "lib/BenchmarkResult.h"
  15. #include "lib/BenchmarkRunner.h"
  16. #include "lib/Clustering.h"
  17. #include "lib/Error.h"
  18. #include "lib/LlvmState.h"
  19. #include "lib/PerfHelper.h"
  20. #include "lib/ProgressMeter.h"
  21. #include "lib/SnippetFile.h"
  22. #include "lib/SnippetRepetitor.h"
  23. #include "lib/Target.h"
  24. #include "lib/TargetSelect.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/ADT/Twine.h"
  27. #include "llvm/MC/MCInstBuilder.h"
  28. #include "llvm/MC/MCObjectFileInfo.h"
  29. #include "llvm/MC/MCParser/MCAsmParser.h"
  30. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  31. #include "llvm/MC/MCRegisterInfo.h"
  32. #include "llvm/MC/MCSubtargetInfo.h"
  33. #include "llvm/MC/TargetRegistry.h"
  34. #include "llvm/Object/ObjectFile.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/FileSystem.h"
  37. #include "llvm/Support/Format.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/InitLLVM.h"
  40. #include "llvm/Support/Path.h"
  41. #include "llvm/Support/SourceMgr.h"
  42. #include "llvm/Support/TargetSelect.h"
  43. #include <algorithm>
  44. #include <string>
  45. namespace llvm {
  46. namespace exegesis {
  47. static cl::opt<int> OpcodeIndex(
  48. "opcode-index",
  49. cl::desc("opcode to measure, by index, or -1 to measure all opcodes"),
  50. cl::cat(BenchmarkOptions), cl::init(0));
  51. static cl::opt<std::string>
  52. OpcodeNames("opcode-name",
  53. cl::desc("comma-separated list of opcodes to measure, by name"),
  54. cl::cat(BenchmarkOptions), cl::init(""));
  55. static cl::opt<std::string> SnippetsFile("snippets-file",
  56. cl::desc("code snippets to measure"),
  57. cl::cat(BenchmarkOptions),
  58. cl::init(""));
  59. static cl::opt<std::string>
  60. BenchmarkFile("benchmarks-file",
  61. cl::desc("File to read (analysis mode) or write "
  62. "(latency/uops/inverse_throughput modes) benchmark "
  63. "results. “-” uses stdin/stdout."),
  64. cl::cat(Options), cl::init(""));
  65. static cl::opt<exegesis::InstructionBenchmark::ModeE> BenchmarkMode(
  66. "mode", cl::desc("the mode to run"), cl::cat(Options),
  67. cl::values(clEnumValN(exegesis::InstructionBenchmark::Latency, "latency",
  68. "Instruction Latency"),
  69. clEnumValN(exegesis::InstructionBenchmark::InverseThroughput,
  70. "inverse_throughput",
  71. "Instruction Inverse Throughput"),
  72. clEnumValN(exegesis::InstructionBenchmark::Uops, "uops",
  73. "Uop Decomposition"),
  74. // When not asking for a specific benchmark mode,
  75. // we'll analyse the results.
  76. clEnumValN(exegesis::InstructionBenchmark::Unknown, "analysis",
  77. "Analysis")));
  78. static cl::opt<exegesis::InstructionBenchmark::ResultAggregationModeE>
  79. ResultAggMode(
  80. "result-aggregation-mode",
  81. cl::desc("How to aggregate multi-values result"),
  82. cl::cat(BenchmarkOptions),
  83. cl::values(clEnumValN(exegesis::InstructionBenchmark::Min, "min",
  84. "Keep min reading"),
  85. clEnumValN(exegesis::InstructionBenchmark::Max, "max",
  86. "Keep max reading"),
  87. clEnumValN(exegesis::InstructionBenchmark::Mean, "mean",
  88. "Compute mean of all readings"),
  89. clEnumValN(exegesis::InstructionBenchmark::MinVariance,
  90. "min-variance",
  91. "Keep readings set with min-variance")),
  92. cl::init(exegesis::InstructionBenchmark::Min));
  93. static cl::opt<exegesis::InstructionBenchmark::RepetitionModeE> RepetitionMode(
  94. "repetition-mode", cl::desc("how to repeat the instruction snippet"),
  95. cl::cat(BenchmarkOptions),
  96. cl::values(
  97. clEnumValN(exegesis::InstructionBenchmark::Duplicate, "duplicate",
  98. "Duplicate the snippet"),
  99. clEnumValN(exegesis::InstructionBenchmark::Loop, "loop",
  100. "Loop over the snippet"),
  101. clEnumValN(exegesis::InstructionBenchmark::AggregateMin, "min",
  102. "All of the above and take the minimum of measurements")),
  103. cl::init(exegesis::InstructionBenchmark::Duplicate));
  104. static cl::opt<bool> BenchmarkMeasurementsPrintProgress(
  105. "measurements-print-progress",
  106. cl::desc("Produce progress indicator when performing measurements"),
  107. cl::cat(BenchmarkOptions), cl::init(false));
  108. static cl::opt<exegesis::BenchmarkPhaseSelectorE> BenchmarkPhaseSelector(
  109. "benchmark-phase",
  110. cl::desc(
  111. "it is possible to stop the benchmarking process after some phase"),
  112. cl::cat(BenchmarkOptions),
  113. cl::values(
  114. clEnumValN(exegesis::BenchmarkPhaseSelectorE::PrepareSnippet,
  115. "prepare-snippet",
  116. "Only generate the minimal instruction sequence"),
  117. clEnumValN(exegesis::BenchmarkPhaseSelectorE::PrepareAndAssembleSnippet,
  118. "prepare-and-assemble-snippet",
  119. "Same as prepare-snippet, but also dumps an excerpt of the "
  120. "sequence (hex encoded)"),
  121. clEnumValN(exegesis::BenchmarkPhaseSelectorE::AssembleMeasuredCode,
  122. "assemble-measured-code",
  123. "Same as prepare-and-assemble-snippet, but also creates the "
  124. "full sequence "
  125. "that can be dumped to a file using --dump-object-to-disk"),
  126. clEnumValN(
  127. exegesis::BenchmarkPhaseSelectorE::Measure, "measure",
  128. "Same as prepare-measured-code, but also runs the measurement "
  129. "(default)")),
  130. cl::init(exegesis::BenchmarkPhaseSelectorE::Measure));
  131. static cl::opt<unsigned>
  132. NumRepetitions("num-repetitions",
  133. cl::desc("number of time to repeat the asm snippet"),
  134. cl::cat(BenchmarkOptions), cl::init(10000));
  135. static cl::opt<unsigned>
  136. LoopBodySize("loop-body-size",
  137. cl::desc("when repeating the instruction snippet by looping "
  138. "over it, duplicate the snippet until the loop body "
  139. "contains at least this many instruction"),
  140. cl::cat(BenchmarkOptions), cl::init(0));
  141. static cl::opt<unsigned> MaxConfigsPerOpcode(
  142. "max-configs-per-opcode",
  143. cl::desc(
  144. "allow to snippet generator to generate at most that many configs"),
  145. cl::cat(BenchmarkOptions), cl::init(1));
  146. static cl::opt<bool> IgnoreInvalidSchedClass(
  147. "ignore-invalid-sched-class",
  148. cl::desc("ignore instructions that do not define a sched class"),
  149. cl::cat(BenchmarkOptions), cl::init(false));
  150. static cl::opt<exegesis::InstructionBenchmarkFilter> AnalysisSnippetFilter(
  151. "analysis-filter", cl::desc("Filter the benchmarks before analysing them"),
  152. cl::cat(BenchmarkOptions),
  153. cl::values(
  154. clEnumValN(exegesis::InstructionBenchmarkFilter::All, "all",
  155. "Keep all benchmarks (default)"),
  156. clEnumValN(exegesis::InstructionBenchmarkFilter::RegOnly, "reg-only",
  157. "Keep only those benchmarks that do *NOT* involve memory"),
  158. clEnumValN(exegesis::InstructionBenchmarkFilter::WithMem, "mem-only",
  159. "Keep only the benchmarks that *DO* involve memory")),
  160. cl::init(exegesis::InstructionBenchmarkFilter::All));
  161. static cl::opt<exegesis::InstructionBenchmarkClustering::ModeE>
  162. AnalysisClusteringAlgorithm(
  163. "analysis-clustering", cl::desc("the clustering algorithm to use"),
  164. cl::cat(AnalysisOptions),
  165. cl::values(clEnumValN(exegesis::InstructionBenchmarkClustering::Dbscan,
  166. "dbscan", "use DBSCAN/OPTICS algorithm"),
  167. clEnumValN(exegesis::InstructionBenchmarkClustering::Naive,
  168. "naive", "one cluster per opcode")),
  169. cl::init(exegesis::InstructionBenchmarkClustering::Dbscan));
  170. static cl::opt<unsigned> AnalysisDbscanNumPoints(
  171. "analysis-numpoints",
  172. cl::desc("minimum number of points in an analysis cluster (dbscan only)"),
  173. cl::cat(AnalysisOptions), cl::init(3));
  174. static cl::opt<float> AnalysisClusteringEpsilon(
  175. "analysis-clustering-epsilon",
  176. cl::desc("epsilon for benchmark point clustering"),
  177. cl::cat(AnalysisOptions), cl::init(0.1));
  178. static cl::opt<float> AnalysisInconsistencyEpsilon(
  179. "analysis-inconsistency-epsilon",
  180. cl::desc("epsilon for detection of when the cluster is different from the "
  181. "LLVM schedule profile values"),
  182. cl::cat(AnalysisOptions), cl::init(0.1));
  183. static cl::opt<std::string>
  184. AnalysisClustersOutputFile("analysis-clusters-output-file", cl::desc(""),
  185. cl::cat(AnalysisOptions), cl::init(""));
  186. static cl::opt<std::string>
  187. AnalysisInconsistenciesOutputFile("analysis-inconsistencies-output-file",
  188. cl::desc(""), cl::cat(AnalysisOptions),
  189. cl::init(""));
  190. static cl::opt<bool> AnalysisDisplayUnstableOpcodes(
  191. "analysis-display-unstable-clusters",
  192. cl::desc("if there is more than one benchmark for an opcode, said "
  193. "benchmarks may end up not being clustered into the same cluster "
  194. "if the measured performance characteristics are different. by "
  195. "default all such opcodes are filtered out. this flag will "
  196. "instead show only such unstable opcodes"),
  197. cl::cat(AnalysisOptions), cl::init(false));
  198. static cl::opt<bool> AnalysisOverrideBenchmarksTripleAndCpu(
  199. "analysis-override-benchmark-triple-and-cpu",
  200. cl::desc("By default, we analyze the benchmarks for the triple/CPU they "
  201. "were measured for, but if you want to analyze them for some "
  202. "other combination (specified via -mtriple/-mcpu), you can "
  203. "pass this flag."),
  204. cl::cat(AnalysisOptions), cl::init(false));
  205. static cl::opt<std::string>
  206. TripleName("mtriple",
  207. cl::desc("Target triple. See -version for available targets"),
  208. cl::cat(Options));
  209. static cl::opt<std::string>
  210. MCPU("mcpu",
  211. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  212. cl::value_desc("cpu-name"), cl::cat(Options), cl::init("native"));
  213. static cl::opt<bool> DumpObjectToDisk(
  214. "dump-object-to-disk",
  215. cl::desc("dumps the generated benchmark object to disk "
  216. "and prints a message to access it (default = false)"),
  217. cl::cat(BenchmarkOptions), cl::init(false));
  218. static ExitOnError ExitOnErr("llvm-exegesis error: ");
  219. // Helper function that logs the error(s) and exits.
  220. template <typename... ArgTs> static void ExitWithError(ArgTs &&... Args) {
  221. ExitOnErr(make_error<Failure>(std::forward<ArgTs>(Args)...));
  222. }
  223. // Check Err. If it's in a failure state log the file error(s) and exit.
  224. static void ExitOnFileError(const Twine &FileName, Error Err) {
  225. if (Err) {
  226. ExitOnErr(createFileError(FileName, std::move(Err)));
  227. }
  228. }
  229. // Check E. If it's in a success state then return the contained value.
  230. // If it's in a failure state log the file error(s) and exit.
  231. template <typename T>
  232. T ExitOnFileError(const Twine &FileName, Expected<T> &&E) {
  233. ExitOnFileError(FileName, E.takeError());
  234. return std::move(*E);
  235. }
  236. // Checks that only one of OpcodeNames, OpcodeIndex or SnippetsFile is provided,
  237. // and returns the opcode indices or {} if snippets should be read from
  238. // `SnippetsFile`.
  239. static std::vector<unsigned> getOpcodesOrDie(const LLVMState &State) {
  240. const size_t NumSetFlags = (OpcodeNames.empty() ? 0 : 1) +
  241. (OpcodeIndex == 0 ? 0 : 1) +
  242. (SnippetsFile.empty() ? 0 : 1);
  243. if (NumSetFlags != 1) {
  244. ExitOnErr.setBanner("llvm-exegesis: ");
  245. ExitWithError("please provide one and only one of 'opcode-index', "
  246. "'opcode-name' or 'snippets-file'");
  247. }
  248. if (!SnippetsFile.empty())
  249. return {};
  250. if (OpcodeIndex > 0)
  251. return {static_cast<unsigned>(OpcodeIndex)};
  252. if (OpcodeIndex < 0) {
  253. std::vector<unsigned> Result;
  254. unsigned NumOpcodes = State.getInstrInfo().getNumOpcodes();
  255. Result.reserve(NumOpcodes);
  256. for (unsigned I = 0, E = NumOpcodes; I < E; ++I)
  257. Result.push_back(I);
  258. return Result;
  259. }
  260. // Resolve opcode name -> opcode.
  261. const auto ResolveName = [&State](StringRef OpcodeName) -> unsigned {
  262. const auto &Map = State.getOpcodeNameToOpcodeIdxMapping();
  263. auto I = Map.find(OpcodeName);
  264. if (I != Map.end())
  265. return I->getSecond();
  266. return 0u;
  267. };
  268. SmallVector<StringRef, 2> Pieces;
  269. StringRef(OpcodeNames.getValue())
  270. .split(Pieces, ",", /* MaxSplit */ -1, /* KeepEmpty */ false);
  271. std::vector<unsigned> Result;
  272. Result.reserve(Pieces.size());
  273. for (const StringRef &OpcodeName : Pieces) {
  274. if (unsigned Opcode = ResolveName(OpcodeName))
  275. Result.push_back(Opcode);
  276. else
  277. ExitWithError(Twine("unknown opcode ").concat(OpcodeName));
  278. }
  279. return Result;
  280. }
  281. // Generates code snippets for opcode `Opcode`.
  282. static Expected<std::vector<BenchmarkCode>>
  283. generateSnippets(const LLVMState &State, unsigned Opcode,
  284. const BitVector &ForbiddenRegs) {
  285. const Instruction &Instr = State.getIC().getInstr(Opcode);
  286. const MCInstrDesc &InstrDesc = Instr.Description;
  287. // Ignore instructions that we cannot run.
  288. if (InstrDesc.isPseudo() || InstrDesc.usesCustomInsertionHook())
  289. return make_error<Failure>(
  290. "Unsupported opcode: isPseudo/usesCustomInserter");
  291. if (InstrDesc.isBranch() || InstrDesc.isIndirectBranch())
  292. return make_error<Failure>("Unsupported opcode: isBranch/isIndirectBranch");
  293. if (InstrDesc.isCall() || InstrDesc.isReturn())
  294. return make_error<Failure>("Unsupported opcode: isCall/isReturn");
  295. const std::vector<InstructionTemplate> InstructionVariants =
  296. State.getExegesisTarget().generateInstructionVariants(
  297. Instr, MaxConfigsPerOpcode);
  298. SnippetGenerator::Options SnippetOptions;
  299. SnippetOptions.MaxConfigsPerOpcode = MaxConfigsPerOpcode;
  300. const std::unique_ptr<SnippetGenerator> Generator =
  301. State.getExegesisTarget().createSnippetGenerator(BenchmarkMode, State,
  302. SnippetOptions);
  303. if (!Generator)
  304. ExitWithError("cannot create snippet generator");
  305. std::vector<BenchmarkCode> Benchmarks;
  306. for (const InstructionTemplate &Variant : InstructionVariants) {
  307. if (Benchmarks.size() >= MaxConfigsPerOpcode)
  308. break;
  309. if (auto Err = Generator->generateConfigurations(Variant, Benchmarks,
  310. ForbiddenRegs))
  311. return std::move(Err);
  312. }
  313. return Benchmarks;
  314. }
  315. static void runBenchmarkConfigurations(
  316. const LLVMState &State, ArrayRef<BenchmarkCode> Configurations,
  317. ArrayRef<std::unique_ptr<const SnippetRepetitor>> Repetitors,
  318. const BenchmarkRunner &Runner) {
  319. assert(!Configurations.empty() && "Don't have any configurations to run.");
  320. std::optional<raw_fd_ostream> FileOstr;
  321. if (BenchmarkFile != "-") {
  322. int ResultFD = 0;
  323. // Create output file or open existing file and truncate it, once.
  324. ExitOnErr(errorCodeToError(openFileForWrite(BenchmarkFile, ResultFD,
  325. sys::fs::CD_CreateAlways,
  326. sys::fs::OF_TextWithCRLF)));
  327. FileOstr.emplace(ResultFD, true /*shouldClose*/);
  328. }
  329. raw_ostream &Ostr = FileOstr ? *FileOstr : outs();
  330. std::optional<ProgressMeter<>> Meter;
  331. if (BenchmarkMeasurementsPrintProgress)
  332. Meter.emplace(Configurations.size());
  333. for (const BenchmarkCode &Conf : Configurations) {
  334. ProgressMeter<>::ProgressMeterStep MeterStep(Meter ? &*Meter : nullptr);
  335. SmallVector<InstructionBenchmark, 2> AllResults;
  336. for (const std::unique_ptr<const SnippetRepetitor> &Repetitor :
  337. Repetitors) {
  338. auto RC = ExitOnErr(Runner.getRunnableConfiguration(
  339. Conf, NumRepetitions, LoopBodySize, *Repetitor));
  340. AllResults.emplace_back(
  341. ExitOnErr(Runner.runConfiguration(std::move(RC), DumpObjectToDisk)));
  342. }
  343. InstructionBenchmark &Result = AllResults.front();
  344. // If any of our measurements failed, pretend they all have failed.
  345. if (AllResults.size() > 1 &&
  346. any_of(AllResults, [](const InstructionBenchmark &R) {
  347. return R.Measurements.empty();
  348. }))
  349. Result.Measurements.clear();
  350. if (RepetitionMode == InstructionBenchmark::RepetitionModeE::AggregateMin) {
  351. for (const InstructionBenchmark &OtherResult :
  352. ArrayRef<InstructionBenchmark>(AllResults).drop_front()) {
  353. llvm::append_range(Result.AssembledSnippet,
  354. OtherResult.AssembledSnippet);
  355. // Aggregate measurements, but only iff all measurements succeeded.
  356. if (Result.Measurements.empty())
  357. continue;
  358. assert(OtherResult.Measurements.size() == Result.Measurements.size() &&
  359. "Expected to have identical number of measurements.");
  360. for (auto I : zip(Result.Measurements, OtherResult.Measurements)) {
  361. BenchmarkMeasure &Measurement = std::get<0>(I);
  362. const BenchmarkMeasure &NewMeasurement = std::get<1>(I);
  363. assert(Measurement.Key == NewMeasurement.Key &&
  364. "Expected measurements to be symmetric");
  365. Measurement.PerInstructionValue =
  366. std::min(Measurement.PerInstructionValue,
  367. NewMeasurement.PerInstructionValue);
  368. Measurement.PerSnippetValue = std::min(
  369. Measurement.PerSnippetValue, NewMeasurement.PerSnippetValue);
  370. }
  371. }
  372. }
  373. ExitOnFileError(BenchmarkFile, Result.writeYamlTo(State, Ostr));
  374. }
  375. }
  376. void benchmarkMain() {
  377. if (BenchmarkPhaseSelector == BenchmarkPhaseSelectorE::Measure) {
  378. #ifndef HAVE_LIBPFM
  379. ExitWithError(
  380. "benchmarking unavailable, LLVM was built without libpfm. You can pass "
  381. "--skip-measurements to skip the actual benchmarking.");
  382. #else
  383. if (exegesis::pfm::pfmInitialize())
  384. ExitWithError("cannot initialize libpfm");
  385. #endif
  386. }
  387. InitializeAllAsmPrinters();
  388. InitializeAllAsmParsers();
  389. InitializeAllExegesisTargets();
  390. const LLVMState State = ExitOnErr(LLVMState::Create(TripleName, MCPU));
  391. // Preliminary check to ensure features needed for requested
  392. // benchmark mode are present on target CPU and/or OS.
  393. if (BenchmarkPhaseSelector == BenchmarkPhaseSelectorE::Measure)
  394. ExitOnErr(State.getExegesisTarget().checkFeatureSupport());
  395. const std::unique_ptr<BenchmarkRunner> Runner =
  396. ExitOnErr(State.getExegesisTarget().createBenchmarkRunner(
  397. BenchmarkMode, State, BenchmarkPhaseSelector, ResultAggMode));
  398. if (!Runner) {
  399. ExitWithError("cannot create benchmark runner");
  400. }
  401. const auto Opcodes = getOpcodesOrDie(State);
  402. SmallVector<std::unique_ptr<const SnippetRepetitor>, 2> Repetitors;
  403. if (RepetitionMode != InstructionBenchmark::RepetitionModeE::AggregateMin)
  404. Repetitors.emplace_back(SnippetRepetitor::Create(RepetitionMode, State));
  405. else {
  406. for (InstructionBenchmark::RepetitionModeE RepMode :
  407. {InstructionBenchmark::RepetitionModeE::Duplicate,
  408. InstructionBenchmark::RepetitionModeE::Loop})
  409. Repetitors.emplace_back(SnippetRepetitor::Create(RepMode, State));
  410. }
  411. BitVector AllReservedRegs;
  412. llvm::for_each(Repetitors,
  413. [&AllReservedRegs](
  414. const std::unique_ptr<const SnippetRepetitor> &Repetitor) {
  415. AllReservedRegs |= Repetitor->getReservedRegs();
  416. });
  417. std::vector<BenchmarkCode> Configurations;
  418. if (!Opcodes.empty()) {
  419. for (const unsigned Opcode : Opcodes) {
  420. // Ignore instructions without a sched class if
  421. // -ignore-invalid-sched-class is passed.
  422. if (IgnoreInvalidSchedClass &&
  423. State.getInstrInfo().get(Opcode).getSchedClass() == 0) {
  424. errs() << State.getInstrInfo().getName(Opcode)
  425. << ": ignoring instruction without sched class\n";
  426. continue;
  427. }
  428. auto ConfigsForInstr = generateSnippets(State, Opcode, AllReservedRegs);
  429. if (!ConfigsForInstr) {
  430. logAllUnhandledErrors(
  431. ConfigsForInstr.takeError(), errs(),
  432. Twine(State.getInstrInfo().getName(Opcode)).concat(": "));
  433. continue;
  434. }
  435. std::move(ConfigsForInstr->begin(), ConfigsForInstr->end(),
  436. std::back_inserter(Configurations));
  437. }
  438. } else {
  439. Configurations = ExitOnErr(readSnippets(State, SnippetsFile));
  440. }
  441. if (NumRepetitions == 0) {
  442. ExitOnErr.setBanner("llvm-exegesis: ");
  443. ExitWithError("--num-repetitions must be greater than zero");
  444. }
  445. // Write to standard output if file is not set.
  446. if (BenchmarkFile.empty())
  447. BenchmarkFile = "-";
  448. if (!Configurations.empty())
  449. runBenchmarkConfigurations(State, Configurations, Repetitors, *Runner);
  450. exegesis::pfm::pfmTerminate();
  451. }
  452. // Prints the results of running analysis pass `Pass` to file `OutputFilename`
  453. // if OutputFilename is non-empty.
  454. template <typename Pass>
  455. static void maybeRunAnalysis(const Analysis &Analyzer, const std::string &Name,
  456. const std::string &OutputFilename) {
  457. if (OutputFilename.empty())
  458. return;
  459. if (OutputFilename != "-") {
  460. errs() << "Printing " << Name << " results to file '" << OutputFilename
  461. << "'\n";
  462. }
  463. std::error_code ErrorCode;
  464. raw_fd_ostream ClustersOS(OutputFilename, ErrorCode,
  465. sys::fs::FA_Read | sys::fs::FA_Write);
  466. if (ErrorCode)
  467. ExitOnFileError(OutputFilename, errorCodeToError(ErrorCode));
  468. if (auto Err = Analyzer.run<Pass>(ClustersOS))
  469. ExitOnFileError(OutputFilename, std::move(Err));
  470. }
  471. static void filterPoints(MutableArrayRef<InstructionBenchmark> Points,
  472. const MCInstrInfo &MCII) {
  473. if (AnalysisSnippetFilter == exegesis::InstructionBenchmarkFilter::All)
  474. return;
  475. bool WantPointsWithMemOps =
  476. AnalysisSnippetFilter == exegesis::InstructionBenchmarkFilter::WithMem;
  477. for (InstructionBenchmark &Point : Points) {
  478. if (!Point.Error.empty())
  479. continue;
  480. if (WantPointsWithMemOps ==
  481. any_of(Point.Key.Instructions, [&MCII](const MCInst &Inst) {
  482. const MCInstrDesc &MCDesc = MCII.get(Inst.getOpcode());
  483. return MCDesc.mayLoad() || MCDesc.mayStore();
  484. }))
  485. continue;
  486. Point.Error = "filtered out by user";
  487. }
  488. }
  489. static void analysisMain() {
  490. ExitOnErr.setBanner("llvm-exegesis: ");
  491. if (BenchmarkFile.empty())
  492. ExitWithError("--benchmarks-file must be set");
  493. if (AnalysisClustersOutputFile.empty() &&
  494. AnalysisInconsistenciesOutputFile.empty()) {
  495. ExitWithError(
  496. "for --mode=analysis: At least one of --analysis-clusters-output-file "
  497. "and --analysis-inconsistencies-output-file must be specified");
  498. }
  499. InitializeAllAsmPrinters();
  500. InitializeAllDisassemblers();
  501. InitializeAllExegesisTargets();
  502. auto MemoryBuffer = ExitOnFileError(
  503. BenchmarkFile,
  504. errorOrToExpected(MemoryBuffer::getFile(BenchmarkFile, /*IsText=*/true)));
  505. const auto TriplesAndCpus = ExitOnFileError(
  506. BenchmarkFile,
  507. InstructionBenchmark::readTriplesAndCpusFromYamls(*MemoryBuffer));
  508. if (TriplesAndCpus.empty()) {
  509. errs() << "no benchmarks to analyze\n";
  510. return;
  511. }
  512. if (TriplesAndCpus.size() > 1) {
  513. ExitWithError("analysis file contains benchmarks from several CPUs. This "
  514. "is unsupported.");
  515. }
  516. auto TripleAndCpu = *TriplesAndCpus.begin();
  517. if (AnalysisOverrideBenchmarksTripleAndCpu) {
  518. llvm::errs() << "overridding file CPU name (" << TripleAndCpu.CpuName
  519. << ") with provided tripled (" << TripleName
  520. << ") and CPU name (" << MCPU << ")\n";
  521. TripleAndCpu.LLVMTriple = TripleName;
  522. TripleAndCpu.CpuName = MCPU;
  523. }
  524. llvm::errs() << "using Triple '" << TripleAndCpu.LLVMTriple << "' and CPU '"
  525. << TripleAndCpu.CpuName << "'\n";
  526. // Read benchmarks.
  527. const LLVMState State = ExitOnErr(
  528. LLVMState::Create(TripleAndCpu.LLVMTriple, TripleAndCpu.CpuName));
  529. std::vector<InstructionBenchmark> Points = ExitOnFileError(
  530. BenchmarkFile, InstructionBenchmark::readYamls(State, *MemoryBuffer));
  531. outs() << "Parsed " << Points.size() << " benchmark points\n";
  532. if (Points.empty()) {
  533. errs() << "no benchmarks to analyze\n";
  534. return;
  535. }
  536. // FIXME: Merge points from several runs (latency and uops).
  537. filterPoints(Points, State.getInstrInfo());
  538. const auto Clustering = ExitOnErr(InstructionBenchmarkClustering::create(
  539. Points, AnalysisClusteringAlgorithm, AnalysisDbscanNumPoints,
  540. AnalysisClusteringEpsilon, &State.getSubtargetInfo(),
  541. &State.getInstrInfo()));
  542. const Analysis Analyzer(State, Clustering, AnalysisInconsistencyEpsilon,
  543. AnalysisDisplayUnstableOpcodes);
  544. maybeRunAnalysis<Analysis::PrintClusters>(Analyzer, "analysis clusters",
  545. AnalysisClustersOutputFile);
  546. maybeRunAnalysis<Analysis::PrintSchedClassInconsistencies>(
  547. Analyzer, "sched class consistency analysis",
  548. AnalysisInconsistenciesOutputFile);
  549. }
  550. } // namespace exegesis
  551. } // namespace llvm
  552. int main(int Argc, char **Argv) {
  553. using namespace llvm;
  554. InitLLVM X(Argc, Argv);
  555. // Initialize targets so we can print them when flag --version is specified.
  556. InitializeAllTargetInfos();
  557. InitializeAllTargets();
  558. InitializeAllTargetMCs();
  559. // Register the Target and CPU printer for --version.
  560. cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);
  561. // Enable printing of available targets when flag --version is specified.
  562. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  563. cl::HideUnrelatedOptions({&llvm::exegesis::Options,
  564. &llvm::exegesis::BenchmarkOptions,
  565. &llvm::exegesis::AnalysisOptions});
  566. cl::ParseCommandLineOptions(Argc, Argv,
  567. "llvm host machine instruction characteristics "
  568. "measurment and analysis.\n");
  569. exegesis::ExitOnErr.setExitCodeMapper([](const Error &Err) {
  570. if (Err.isA<exegesis::ClusteringError>())
  571. return EXIT_SUCCESS;
  572. return EXIT_FAILURE;
  573. });
  574. if (exegesis::BenchmarkMode == exegesis::InstructionBenchmark::Unknown) {
  575. exegesis::analysisMain();
  576. } else {
  577. exegesis::benchmarkMain();
  578. }
  579. return EXIT_SUCCESS;
  580. }