llvm-exegesis.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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/SnippetFile.h"
  21. #include "lib/SnippetRepetitor.h"
  22. #include "lib/Target.h"
  23. #include "lib/TargetSelect.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/MC/MCInstBuilder.h"
  27. #include "llvm/MC/MCObjectFileInfo.h"
  28. #include "llvm/MC/MCParser/MCAsmParser.h"
  29. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  30. #include "llvm/MC/MCRegisterInfo.h"
  31. #include "llvm/MC/MCSubtargetInfo.h"
  32. #include "llvm/Object/ObjectFile.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Format.h"
  35. #include "llvm/Support/Path.h"
  36. #include "llvm/Support/SourceMgr.h"
  37. #include "llvm/Support/TargetRegistry.h"
  38. #include "llvm/Support/TargetSelect.h"
  39. #include <algorithm>
  40. #include <string>
  41. namespace llvm {
  42. namespace exegesis {
  43. static cl::OptionCategory Options("llvm-exegesis options");
  44. static cl::OptionCategory BenchmarkOptions("llvm-exegesis benchmark options");
  45. static cl::OptionCategory AnalysisOptions("llvm-exegesis analysis options");
  46. static cl::opt<int> OpcodeIndex(
  47. "opcode-index",
  48. cl::desc("opcode to measure, by index, or -1 to measure all opcodes"),
  49. cl::cat(BenchmarkOptions), cl::init(0));
  50. static cl::opt<std::string>
  51. OpcodeNames("opcode-name",
  52. cl::desc("comma-separated list of opcodes to measure, by name"),
  53. cl::cat(BenchmarkOptions), cl::init(""));
  54. static cl::opt<std::string> SnippetsFile("snippets-file",
  55. cl::desc("code snippets to measure"),
  56. cl::cat(BenchmarkOptions),
  57. cl::init(""));
  58. static cl::opt<std::string>
  59. BenchmarkFile("benchmarks-file",
  60. cl::desc("File to read (analysis mode) or write "
  61. "(latency/uops/inverse_throughput modes) benchmark "
  62. "results. “-” uses stdin/stdout."),
  63. cl::cat(Options), cl::init(""));
  64. static cl::opt<exegesis::InstructionBenchmark::ModeE> BenchmarkMode(
  65. "mode", cl::desc("the mode to run"), cl::cat(Options),
  66. cl::values(clEnumValN(exegesis::InstructionBenchmark::Latency, "latency",
  67. "Instruction Latency"),
  68. clEnumValN(exegesis::InstructionBenchmark::InverseThroughput,
  69. "inverse_throughput",
  70. "Instruction Inverse Throughput"),
  71. clEnumValN(exegesis::InstructionBenchmark::Uops, "uops",
  72. "Uop Decomposition"),
  73. // When not asking for a specific benchmark mode,
  74. // we'll analyse the results.
  75. clEnumValN(exegesis::InstructionBenchmark::Unknown, "analysis",
  76. "Analysis")));
  77. static cl::opt<exegesis::InstructionBenchmark::ResultAggregationModeE>
  78. ResultAggMode(
  79. "result-aggregation-mode",
  80. cl::desc("How to aggregate multi-values result"), cl::cat(Options),
  81. cl::values(clEnumValN(exegesis::InstructionBenchmark::Min, "min",
  82. "Keep min reading"),
  83. clEnumValN(exegesis::InstructionBenchmark::Max, "max",
  84. "Keep max reading"),
  85. clEnumValN(exegesis::InstructionBenchmark::Mean, "mean",
  86. "Compute mean of all readings"),
  87. clEnumValN(exegesis::InstructionBenchmark::MinVariance,
  88. "min-variance",
  89. "Keep readings set with min-variance")),
  90. cl::init(exegesis::InstructionBenchmark::Min));
  91. static cl::opt<exegesis::InstructionBenchmark::RepetitionModeE> RepetitionMode(
  92. "repetition-mode", cl::desc("how to repeat the instruction snippet"),
  93. cl::cat(BenchmarkOptions),
  94. cl::values(
  95. clEnumValN(exegesis::InstructionBenchmark::Duplicate, "duplicate",
  96. "Duplicate the snippet"),
  97. clEnumValN(exegesis::InstructionBenchmark::Loop, "loop",
  98. "Loop over the snippet"),
  99. clEnumValN(exegesis::InstructionBenchmark::AggregateMin, "min",
  100. "All of the above and take the minimum of measurements")),
  101. cl::init(exegesis::InstructionBenchmark::Duplicate));
  102. static cl::opt<unsigned>
  103. NumRepetitions("num-repetitions",
  104. cl::desc("number of time to repeat the asm snippet"),
  105. cl::cat(BenchmarkOptions), cl::init(10000));
  106. static cl::opt<unsigned> MaxConfigsPerOpcode(
  107. "max-configs-per-opcode",
  108. cl::desc(
  109. "allow to snippet generator to generate at most that many configs"),
  110. cl::cat(BenchmarkOptions), cl::init(1));
  111. static cl::opt<bool> IgnoreInvalidSchedClass(
  112. "ignore-invalid-sched-class",
  113. cl::desc("ignore instructions that do not define a sched class"),
  114. cl::cat(BenchmarkOptions), cl::init(false));
  115. static cl::opt<exegesis::InstructionBenchmarkClustering::ModeE>
  116. AnalysisClusteringAlgorithm(
  117. "analysis-clustering", cl::desc("the clustering algorithm to use"),
  118. cl::cat(AnalysisOptions),
  119. cl::values(clEnumValN(exegesis::InstructionBenchmarkClustering::Dbscan,
  120. "dbscan", "use DBSCAN/OPTICS algorithm"),
  121. clEnumValN(exegesis::InstructionBenchmarkClustering::Naive,
  122. "naive", "one cluster per opcode")),
  123. cl::init(exegesis::InstructionBenchmarkClustering::Dbscan));
  124. static cl::opt<unsigned> AnalysisDbscanNumPoints(
  125. "analysis-numpoints",
  126. cl::desc("minimum number of points in an analysis cluster (dbscan only)"),
  127. cl::cat(AnalysisOptions), cl::init(3));
  128. static cl::opt<float> AnalysisClusteringEpsilon(
  129. "analysis-clustering-epsilon",
  130. cl::desc("epsilon for benchmark point clustering"),
  131. cl::cat(AnalysisOptions), cl::init(0.1));
  132. static cl::opt<float> AnalysisInconsistencyEpsilon(
  133. "analysis-inconsistency-epsilon",
  134. cl::desc("epsilon for detection of when the cluster is different from the "
  135. "LLVM schedule profile values"),
  136. cl::cat(AnalysisOptions), cl::init(0.1));
  137. static cl::opt<std::string>
  138. AnalysisClustersOutputFile("analysis-clusters-output-file", cl::desc(""),
  139. cl::cat(AnalysisOptions), cl::init(""));
  140. static cl::opt<std::string>
  141. AnalysisInconsistenciesOutputFile("analysis-inconsistencies-output-file",
  142. cl::desc(""), cl::cat(AnalysisOptions),
  143. cl::init(""));
  144. static cl::opt<bool> AnalysisDisplayUnstableOpcodes(
  145. "analysis-display-unstable-clusters",
  146. cl::desc("if there is more than one benchmark for an opcode, said "
  147. "benchmarks may end up not being clustered into the same cluster "
  148. "if the measured performance characteristics are different. by "
  149. "default all such opcodes are filtered out. this flag will "
  150. "instead show only such unstable opcodes"),
  151. cl::cat(AnalysisOptions), cl::init(false));
  152. static cl::opt<std::string> CpuName(
  153. "mcpu",
  154. cl::desc("cpu name to use for pfm counters, leave empty to autodetect"),
  155. cl::cat(Options), cl::init(""));
  156. static cl::opt<bool>
  157. DumpObjectToDisk("dump-object-to-disk",
  158. cl::desc("dumps the generated benchmark object to disk "
  159. "and prints a message to access it"),
  160. cl::cat(BenchmarkOptions), cl::init(true));
  161. static ExitOnError ExitOnErr("llvm-exegesis error: ");
  162. // Helper function that logs the error(s) and exits.
  163. template <typename... ArgTs> static void ExitWithError(ArgTs &&... Args) {
  164. ExitOnErr(make_error<Failure>(std::forward<ArgTs>(Args)...));
  165. }
  166. // Check Err. If it's in a failure state log the file error(s) and exit.
  167. static void ExitOnFileError(const Twine &FileName, Error Err) {
  168. if (Err) {
  169. ExitOnErr(createFileError(FileName, std::move(Err)));
  170. }
  171. }
  172. // Check E. If it's in a success state then return the contained value.
  173. // If it's in a failure state log the file error(s) and exit.
  174. template <typename T>
  175. T ExitOnFileError(const Twine &FileName, Expected<T> &&E) {
  176. ExitOnFileError(FileName, E.takeError());
  177. return std::move(*E);
  178. }
  179. // Checks that only one of OpcodeNames, OpcodeIndex or SnippetsFile is provided,
  180. // and returns the opcode indices or {} if snippets should be read from
  181. // `SnippetsFile`.
  182. static std::vector<unsigned> getOpcodesOrDie(const MCInstrInfo &MCInstrInfo) {
  183. const size_t NumSetFlags = (OpcodeNames.empty() ? 0 : 1) +
  184. (OpcodeIndex == 0 ? 0 : 1) +
  185. (SnippetsFile.empty() ? 0 : 1);
  186. if (NumSetFlags != 1) {
  187. ExitOnErr.setBanner("llvm-exegesis: ");
  188. ExitWithError("please provide one and only one of 'opcode-index', "
  189. "'opcode-name' or 'snippets-file'");
  190. }
  191. if (!SnippetsFile.empty())
  192. return {};
  193. if (OpcodeIndex > 0)
  194. return {static_cast<unsigned>(OpcodeIndex)};
  195. if (OpcodeIndex < 0) {
  196. std::vector<unsigned> Result;
  197. for (unsigned I = 1, E = MCInstrInfo.getNumOpcodes(); I < E; ++I)
  198. Result.push_back(I);
  199. return Result;
  200. }
  201. // Resolve opcode name -> opcode.
  202. const auto ResolveName = [&MCInstrInfo](StringRef OpcodeName) -> unsigned {
  203. for (unsigned I = 1, E = MCInstrInfo.getNumOpcodes(); I < E; ++I)
  204. if (MCInstrInfo.getName(I) == OpcodeName)
  205. return I;
  206. return 0u;
  207. };
  208. SmallVector<StringRef, 2> Pieces;
  209. StringRef(OpcodeNames.getValue())
  210. .split(Pieces, ",", /* MaxSplit */ -1, /* KeepEmpty */ false);
  211. std::vector<unsigned> Result;
  212. for (const StringRef &OpcodeName : Pieces) {
  213. if (unsigned Opcode = ResolveName(OpcodeName))
  214. Result.push_back(Opcode);
  215. else
  216. ExitWithError(Twine("unknown opcode ").concat(OpcodeName));
  217. }
  218. return Result;
  219. }
  220. // Generates code snippets for opcode `Opcode`.
  221. static Expected<std::vector<BenchmarkCode>>
  222. generateSnippets(const LLVMState &State, unsigned Opcode,
  223. const BitVector &ForbiddenRegs) {
  224. const Instruction &Instr = State.getIC().getInstr(Opcode);
  225. const MCInstrDesc &InstrDesc = Instr.Description;
  226. // Ignore instructions that we cannot run.
  227. if (InstrDesc.isPseudo())
  228. return make_error<Failure>("Unsupported opcode: isPseudo");
  229. if (InstrDesc.isBranch() || InstrDesc.isIndirectBranch())
  230. return make_error<Failure>("Unsupported opcode: isBranch/isIndirectBranch");
  231. if (InstrDesc.isCall() || InstrDesc.isReturn())
  232. return make_error<Failure>("Unsupported opcode: isCall/isReturn");
  233. const std::vector<InstructionTemplate> InstructionVariants =
  234. State.getExegesisTarget().generateInstructionVariants(
  235. Instr, MaxConfigsPerOpcode);
  236. SnippetGenerator::Options SnippetOptions;
  237. SnippetOptions.MaxConfigsPerOpcode = MaxConfigsPerOpcode;
  238. const std::unique_ptr<SnippetGenerator> Generator =
  239. State.getExegesisTarget().createSnippetGenerator(BenchmarkMode, State,
  240. SnippetOptions);
  241. if (!Generator)
  242. ExitWithError("cannot create snippet generator");
  243. std::vector<BenchmarkCode> Benchmarks;
  244. for (const InstructionTemplate &Variant : InstructionVariants) {
  245. if (Benchmarks.size() >= MaxConfigsPerOpcode)
  246. break;
  247. if (auto Err = Generator->generateConfigurations(Variant, Benchmarks,
  248. ForbiddenRegs))
  249. return std::move(Err);
  250. }
  251. return Benchmarks;
  252. }
  253. void benchmarkMain() {
  254. #ifndef HAVE_LIBPFM
  255. ExitWithError("benchmarking unavailable, LLVM was built without libpfm.");
  256. #endif
  257. if (exegesis::pfm::pfmInitialize())
  258. ExitWithError("cannot initialize libpfm");
  259. InitializeNativeTarget();
  260. InitializeNativeTargetAsmPrinter();
  261. InitializeNativeTargetAsmParser();
  262. InitializeNativeExegesisTarget();
  263. const LLVMState State(CpuName);
  264. // Preliminary check to ensure features needed for requested
  265. // benchmark mode are present on target CPU and/or OS.
  266. ExitOnErr(State.getExegesisTarget().checkFeatureSupport());
  267. const std::unique_ptr<BenchmarkRunner> Runner =
  268. ExitOnErr(State.getExegesisTarget().createBenchmarkRunner(
  269. BenchmarkMode, State, ResultAggMode));
  270. if (!Runner) {
  271. ExitWithError("cannot create benchmark runner");
  272. }
  273. const auto Opcodes = getOpcodesOrDie(State.getInstrInfo());
  274. SmallVector<std::unique_ptr<const SnippetRepetitor>, 2> Repetitors;
  275. if (RepetitionMode != InstructionBenchmark::RepetitionModeE::AggregateMin)
  276. Repetitors.emplace_back(SnippetRepetitor::Create(RepetitionMode, State));
  277. else {
  278. for (InstructionBenchmark::RepetitionModeE RepMode :
  279. {InstructionBenchmark::RepetitionModeE::Duplicate,
  280. InstructionBenchmark::RepetitionModeE::Loop})
  281. Repetitors.emplace_back(SnippetRepetitor::Create(RepMode, State));
  282. }
  283. BitVector AllReservedRegs;
  284. llvm::for_each(Repetitors,
  285. [&AllReservedRegs](
  286. const std::unique_ptr<const SnippetRepetitor> &Repetitor) {
  287. AllReservedRegs |= Repetitor->getReservedRegs();
  288. });
  289. std::vector<BenchmarkCode> Configurations;
  290. if (!Opcodes.empty()) {
  291. for (const unsigned Opcode : Opcodes) {
  292. // Ignore instructions without a sched class if
  293. // -ignore-invalid-sched-class is passed.
  294. if (IgnoreInvalidSchedClass &&
  295. State.getInstrInfo().get(Opcode).getSchedClass() == 0) {
  296. errs() << State.getInstrInfo().getName(Opcode)
  297. << ": ignoring instruction without sched class\n";
  298. continue;
  299. }
  300. auto ConfigsForInstr = generateSnippets(State, Opcode, AllReservedRegs);
  301. if (!ConfigsForInstr) {
  302. logAllUnhandledErrors(
  303. ConfigsForInstr.takeError(), errs(),
  304. Twine(State.getInstrInfo().getName(Opcode)).concat(": "));
  305. continue;
  306. }
  307. std::move(ConfigsForInstr->begin(), ConfigsForInstr->end(),
  308. std::back_inserter(Configurations));
  309. }
  310. } else {
  311. Configurations = ExitOnErr(readSnippets(State, SnippetsFile));
  312. }
  313. if (NumRepetitions == 0) {
  314. ExitOnErr.setBanner("llvm-exegesis: ");
  315. ExitWithError("--num-repetitions must be greater than zero");
  316. }
  317. // Write to standard output if file is not set.
  318. if (BenchmarkFile.empty())
  319. BenchmarkFile = "-";
  320. for (const BenchmarkCode &Conf : Configurations) {
  321. InstructionBenchmark Result = ExitOnErr(Runner->runConfiguration(
  322. Conf, NumRepetitions, Repetitors, DumpObjectToDisk));
  323. ExitOnFileError(BenchmarkFile, Result.writeYaml(State, BenchmarkFile));
  324. }
  325. exegesis::pfm::pfmTerminate();
  326. }
  327. // Prints the results of running analysis pass `Pass` to file `OutputFilename`
  328. // if OutputFilename is non-empty.
  329. template <typename Pass>
  330. static void maybeRunAnalysis(const Analysis &Analyzer, const std::string &Name,
  331. const std::string &OutputFilename) {
  332. if (OutputFilename.empty())
  333. return;
  334. if (OutputFilename != "-") {
  335. errs() << "Printing " << Name << " results to file '" << OutputFilename
  336. << "'\n";
  337. }
  338. std::error_code ErrorCode;
  339. raw_fd_ostream ClustersOS(OutputFilename, ErrorCode,
  340. sys::fs::FA_Read | sys::fs::FA_Write);
  341. if (ErrorCode)
  342. ExitOnFileError(OutputFilename, errorCodeToError(ErrorCode));
  343. if (auto Err = Analyzer.run<Pass>(ClustersOS))
  344. ExitOnFileError(OutputFilename, std::move(Err));
  345. }
  346. static void analysisMain() {
  347. ExitOnErr.setBanner("llvm-exegesis: ");
  348. if (BenchmarkFile.empty())
  349. ExitWithError("--benchmarks-file must be set");
  350. if (AnalysisClustersOutputFile.empty() &&
  351. AnalysisInconsistenciesOutputFile.empty()) {
  352. ExitWithError(
  353. "for --mode=analysis: At least one of --analysis-clusters-output-file "
  354. "and --analysis-inconsistencies-output-file must be specified");
  355. }
  356. InitializeNativeTarget();
  357. InitializeNativeTargetAsmPrinter();
  358. InitializeNativeTargetDisassembler();
  359. // Read benchmarks.
  360. const LLVMState State("");
  361. const std::vector<InstructionBenchmark> Points = ExitOnFileError(
  362. BenchmarkFile, InstructionBenchmark::readYamls(State, BenchmarkFile));
  363. outs() << "Parsed " << Points.size() << " benchmark points\n";
  364. if (Points.empty()) {
  365. errs() << "no benchmarks to analyze\n";
  366. return;
  367. }
  368. // FIXME: Check that all points have the same triple/cpu.
  369. // FIXME: Merge points from several runs (latency and uops).
  370. std::string Error;
  371. const auto *TheTarget =
  372. TargetRegistry::lookupTarget(Points[0].LLVMTriple, Error);
  373. if (!TheTarget) {
  374. errs() << "unknown target '" << Points[0].LLVMTriple << "'\n";
  375. return;
  376. }
  377. std::unique_ptr<MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
  378. assert(InstrInfo && "Unable to create instruction info!");
  379. const auto Clustering = ExitOnErr(InstructionBenchmarkClustering::create(
  380. Points, AnalysisClusteringAlgorithm, AnalysisDbscanNumPoints,
  381. AnalysisClusteringEpsilon, InstrInfo->getNumOpcodes()));
  382. const Analysis Analyzer(*TheTarget, std::move(InstrInfo), Clustering,
  383. AnalysisInconsistencyEpsilon,
  384. AnalysisDisplayUnstableOpcodes, CpuName);
  385. maybeRunAnalysis<Analysis::PrintClusters>(Analyzer, "analysis clusters",
  386. AnalysisClustersOutputFile);
  387. maybeRunAnalysis<Analysis::PrintSchedClassInconsistencies>(
  388. Analyzer, "sched class consistency analysis",
  389. AnalysisInconsistenciesOutputFile);
  390. }
  391. } // namespace exegesis
  392. } // namespace llvm
  393. int main(int Argc, char **Argv) {
  394. using namespace llvm;
  395. cl::ParseCommandLineOptions(Argc, Argv, "");
  396. exegesis::ExitOnErr.setExitCodeMapper([](const Error &Err) {
  397. if (Err.isA<exegesis::ClusteringError>())
  398. return EXIT_SUCCESS;
  399. return EXIT_FAILURE;
  400. });
  401. if (exegesis::BenchmarkMode == exegesis::InstructionBenchmark::Unknown) {
  402. exegesis::analysisMain();
  403. } else {
  404. exegesis::benchmarkMain();
  405. }
  406. return EXIT_SUCCESS;
  407. }