tokenized_buffer_benchmark.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include <benchmark/benchmark.h>
  5. #include <algorithm>
  6. #include <utility>
  7. #include "absl/random/random.h"
  8. #include "common/check.h"
  9. #include "llvm/ADT/Sequence.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "toolchain/base/value_store.h"
  12. #include "toolchain/diagnostics/diagnostic_emitter.h"
  13. #include "toolchain/diagnostics/null_diagnostics.h"
  14. #include "toolchain/lex/token_kind.h"
  15. #include "toolchain/lex/tokenized_buffer.h"
  16. namespace Carbon::Lex {
  17. namespace {
  18. // A large value for measurement stability without making benchmarking too slow.
  19. // Needs to be a multiple of 100 so we can easily divide it up into percentages,
  20. // and 1% itself needs to not be too tiny. This makes 100,000 a great balance.
  21. constexpr int NumTokens = 100'000;
  22. auto IdentifierStartChars() -> llvm::ArrayRef<char> {
  23. static llvm::SmallVector<char> chars = [] {
  24. llvm::SmallVector<char> chars;
  25. chars.push_back('_');
  26. for (char c : llvm::seq_inclusive('A', 'Z')) {
  27. chars.push_back(c);
  28. }
  29. for (char c : llvm::seq_inclusive('a', 'z')) {
  30. chars.push_back(c);
  31. }
  32. return chars;
  33. }();
  34. return chars;
  35. }
  36. auto IdentifierChars() -> llvm::ArrayRef<char> {
  37. static llvm::SmallVector<char> chars = [] {
  38. llvm::ArrayRef<char> start_chars = IdentifierStartChars();
  39. llvm::SmallVector<char> chars(start_chars.begin(), start_chars.end());
  40. for (char c : llvm::seq_inclusive('0', '9')) {
  41. chars.push_back(c);
  42. }
  43. return chars;
  44. }();
  45. return chars;
  46. }
  47. // Generates a random identifier string of the specified length using the
  48. // provided RNG BitGen.
  49. auto GenerateRandomIdentifier(absl::BitGen& gen, int length) -> std::string {
  50. llvm::ArrayRef<char> start_chars = IdentifierStartChars();
  51. llvm::ArrayRef<char> chars = IdentifierChars();
  52. std::string id_result;
  53. llvm::raw_string_ostream os(id_result);
  54. llvm::StringRef id;
  55. do {
  56. // Erase any prior attempts to find an identifier.
  57. id_result.clear();
  58. os << start_chars[absl::Uniform<int>(gen, 0, start_chars.size())];
  59. for (int j : llvm::seq(0, length)) {
  60. static_cast<void>(j);
  61. os << chars[absl::Uniform<int>(gen, 0, chars.size())];
  62. }
  63. // Check if we ended up forming an integer type literal or a keyword, and
  64. // try again.
  65. id = llvm::StringRef(id_result);
  66. } while (
  67. llvm::any_of(TokenKind::KeywordTokens,
  68. [id](auto token) { return id == token.fixed_spelling(); }) ||
  69. ((id.consume_front("i") || id.consume_front("u") ||
  70. id.consume_front("f")) &&
  71. llvm::all_of(id, [](const char c) { return llvm::isDigit(c); })));
  72. return id_result;
  73. }
  74. // Get a static pool of random identifiers with the desired distribution.
  75. template <int MinLength = 1, int MaxLength = 64, bool Uniform = false>
  76. auto GetRandomIdentifiers() -> const std::array<std::string, NumTokens>& {
  77. static_assert(MinLength <= MaxLength);
  78. static_assert(
  79. Uniform || MaxLength <= 64,
  80. "Cannot produce a meaningful non-uniform distribution of lengths longer "
  81. "than 64 as those are exceedingly rare in our observed data sets.");
  82. static const std::array<std::string, NumTokens> id_storage = [] {
  83. std::array<int, 64> id_length_counts;
  84. // For non-uniform distribution, we simulate a distribution roughly based on
  85. // the observed histogram of identifier lengths, but smoothed a bit and
  86. // reduced to small counts so that we cycle through all the lengths
  87. // reasonably quickly. We want sampling of even 10% of NumTokens from this
  88. // in a round-robin form to not be skewed overly much. This still inherently
  89. // compresses the long tail as we'd rather have coverage even though it
  90. // distorts the distribution a bit.
  91. //
  92. // The distribution here comes from a script that analyzes source code run
  93. // over a few directories of LLVM. The script renders a visual ascii-art
  94. // histogram along with the data for each bucket, and that output is
  95. // included in comments above each bucket size below to help visualize the
  96. // rough shape we're aiming for.
  97. //
  98. // 1 characters [3976] ███████████████████████████████▊
  99. id_length_counts[0] = 40;
  100. // 2 characters [3724] █████████████████████████████▊
  101. id_length_counts[1] = 40;
  102. // 3 characters [4173] █████████████████████████████████▍
  103. id_length_counts[2] = 40;
  104. // 4 characters [5000] ████████████████████████████████████████
  105. id_length_counts[3] = 50;
  106. // 5 characters [1568] ████████████▌
  107. id_length_counts[4] = 20;
  108. // 6 characters [2226] █████████████████▊
  109. id_length_counts[5] = 20;
  110. // 7 characters [2380] ███████████████████
  111. id_length_counts[6] = 20;
  112. // 8 characters [1786] ██████████████▎
  113. id_length_counts[7] = 18;
  114. // 9 characters [1397] ███████████▏
  115. id_length_counts[8] = 12;
  116. // 10 characters [ 739] █████▉
  117. id_length_counts[9] = 12;
  118. // 11 characters [ 779] ██████▎
  119. id_length_counts[10] = 12;
  120. // 12 characters [1344] ██████████▊
  121. id_length_counts[11] = 12;
  122. // 13 characters [ 498] ████
  123. id_length_counts[12] = 5;
  124. // 14 characters [ 284] ██▎
  125. id_length_counts[13] = 3;
  126. // 15 characters [ 172] █▍
  127. // 16 characters [ 278] ██▎
  128. // 17 characters [ 191] █▌
  129. // 18 characters [ 207] █▋
  130. for (int i : llvm::seq(14, 18)) {
  131. id_length_counts[i] = 2;
  132. }
  133. // 19 - 63 characters are all <100 but non-zero, and we map them to 1 for
  134. // coverage despite slightly over weighting the tail.
  135. for (int i : llvm::seq(18, 64)) {
  136. id_length_counts[i] = 1;
  137. }
  138. // Used to track the different count buckets when in a non-uniform
  139. // distribution.
  140. int length_bucket_index = 0;
  141. int length_count = 0;
  142. std::array<std::string, NumTokens> ids;
  143. absl::BitGen gen;
  144. for (auto [i, id] : llvm::enumerate(ids)) {
  145. if (Uniform) {
  146. // Rather than using randomness, for a uniform distribution rotate
  147. // lengths in round-robin to get a deterministic and exact size on every
  148. // run. We will then shuffle them at the end to produce a random
  149. // ordering.
  150. int length = MinLength + i % (1 + MaxLength - MinLength);
  151. id = GenerateRandomIdentifier(gen, length);
  152. continue;
  153. }
  154. // For non-uniform distribution, walk through each each length bucket
  155. // until our count matches the desired distribution, and then move to the
  156. // next.
  157. id = GenerateRandomIdentifier(gen, length_bucket_index + 1);
  158. if (length_count < id_length_counts[length_bucket_index]) {
  159. ++length_count;
  160. } else {
  161. length_bucket_index =
  162. (length_bucket_index + 1) % id_length_counts.size();
  163. length_count = 0;
  164. }
  165. }
  166. return ids;
  167. }();
  168. return id_storage;
  169. }
  170. // Compute a random sequence of just identifiers.
  171. template <int MinLength = 1, int MaxLength = 64, bool Uniform = false>
  172. auto RandomIdentifierSeq(llvm::StringRef separator = " ") -> std::string {
  173. // Get a static pool of identifiers with the desired distribution.
  174. const std::array<std::string, NumTokens>& ids =
  175. GetRandomIdentifiers<MinLength, MaxLength, Uniform>();
  176. // Shuffle tokens so we get exactly one of each identifier but in a random
  177. // order.
  178. std::array<llvm::StringRef, NumTokens> tokens;
  179. for (int i : llvm::seq(NumTokens)) {
  180. tokens[i] = ids[i];
  181. }
  182. std::shuffle(tokens.begin(), tokens.end(), absl::BitGen());
  183. return llvm::join(tokens, separator);
  184. }
  185. auto GetSymbolTokenTable() -> llvm::ArrayRef<TokenKind> {
  186. // Build our own table of symbols so we can use repetitions to skew the
  187. // distribution.
  188. static auto symbol_token_table_storage = [] {
  189. llvm::SmallVector<TokenKind> table;
  190. #define CARBON_SYMBOL_TOKEN(TokenName, Spelling) \
  191. table.push_back(TokenKind::TokenName);
  192. #define CARBON_OPENING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, ClosingName)
  193. #define CARBON_CLOSING_GROUP_SYMBOL_TOKEN(TokenName, Spelling, OpeningName)
  194. #include "toolchain/lex/token_kind.def"
  195. table.insert(table.end(), 32, TokenKind::Semi);
  196. table.insert(table.end(), 16, TokenKind::Comma);
  197. table.insert(table.end(), 12, TokenKind::Period);
  198. table.insert(table.end(), 8, TokenKind::Colon);
  199. table.insert(table.end(), 8, TokenKind::Equal);
  200. table.insert(table.end(), 4, TokenKind::Amp);
  201. table.insert(table.end(), 4, TokenKind::ColonExclaim);
  202. table.insert(table.end(), 4, TokenKind::EqualEqual);
  203. table.insert(table.end(), 4, TokenKind::ExclaimEqual);
  204. table.insert(table.end(), 4, TokenKind::MinusGreater);
  205. table.insert(table.end(), 4, TokenKind::Star);
  206. return table;
  207. }();
  208. return symbol_token_table_storage;
  209. }
  210. struct RandomSourceOptions {
  211. int symbol_percent = 0;
  212. int keyword_percent = 0;
  213. int numeric_literal_percent = 0;
  214. int string_literal_percent = 0;
  215. int tokens_per_line = NumTokens;
  216. int comment_line_percent = 0;
  217. int blank_line_percent = 0;
  218. void Validate() {
  219. auto is_percentage = [](int n) { return 0 <= n && n <= 100; };
  220. CARBON_CHECK(is_percentage(symbol_percent));
  221. CARBON_CHECK(is_percentage(keyword_percent));
  222. CARBON_CHECK(is_percentage(numeric_literal_percent));
  223. CARBON_CHECK(is_percentage(string_literal_percent));
  224. CARBON_CHECK(is_percentage(symbol_percent + keyword_percent +
  225. numeric_literal_percent +
  226. string_literal_percent));
  227. CARBON_CHECK(tokens_per_line <= NumTokens);
  228. CARBON_CHECK(NumTokens % tokens_per_line == 0)
  229. << "Tokens per line of " << tokens_per_line
  230. << " does not divide the number of tokens " << NumTokens;
  231. CARBON_CHECK(is_percentage(comment_line_percent));
  232. CARBON_CHECK(is_percentage(blank_line_percent));
  233. // Ensure that comment and blank lines are less than 100% so we eventually
  234. // produce a token line.
  235. CARBON_CHECK(comment_line_percent + blank_line_percent < 100);
  236. }
  237. };
  238. // Based on measurements of LLVM's source code, a rough approximation of the
  239. // distribution of these kinds of tokens.
  240. constexpr RandomSourceOptions DefaultSourceDist = {
  241. .symbol_percent = 50,
  242. .keyword_percent = 7,
  243. .numeric_literal_percent = 17,
  244. .string_literal_percent = 1,
  245. // The median for LLVM is roughly 5.
  246. .tokens_per_line = 5,
  247. // Observed percentage of lines in LLVM.
  248. .comment_line_percent = 22,
  249. .blank_line_percent = 15,
  250. };
  251. // Compute random source code with a mixture of tokens and whitespace according
  252. // to the options. The source isn't designed to be valid, or directly
  253. // representative of real-world Carbon code. However, it tries to provide
  254. // reasonable coverage of the different aspects of Carbon's lexer, such that for
  255. // real world source code with distributions similar to the options provided the
  256. // lexer performance will be roughly representative.
  257. //
  258. // TODO: Does not yet support generating numeric or string literals.
  259. //
  260. // TODO: The shape of lines is handled very arbitrarily and should vary more to
  261. // avoid over-fitting to a specific shape (number of tokens, length of comment).
  262. auto RandomSource(RandomSourceOptions options) -> std::string {
  263. options.Validate();
  264. static_assert((NumTokens % 100) == 0,
  265. "The number of tokens must be divisible by 100 so that we can "
  266. "easily scale integer percentages up to it.");
  267. // Get static pools of symbols, keywords, and identifiers.
  268. llvm::ArrayRef<TokenKind> symbols = GetSymbolTokenTable();
  269. llvm::ArrayRef<TokenKind> keywords = TokenKind::KeywordTokens;
  270. const std::array<std::string, NumTokens>& ids = GetRandomIdentifiers();
  271. // Build a list of StringRefs from the different types with the desired
  272. // distribution, then shuffle that list.
  273. llvm::OwningArrayRef<llvm::StringRef> tokens(NumTokens);
  274. int num_symbols = (NumTokens / 100) * options.symbol_percent;
  275. int num_keywords = (NumTokens / 100) * options.keyword_percent;
  276. int num_identifiers = NumTokens - num_symbols - num_keywords;
  277. CARBON_CHECK(num_identifiers == 0 || num_identifiers > 500)
  278. << "We require at least 500 identifiers as we need to collect a "
  279. "reasonable number of samples to end up with a reasonable "
  280. "distribution of lengths.";
  281. for (int i : llvm::seq(num_symbols)) {
  282. tokens[i] = symbols[i % symbols.size()].fixed_spelling();
  283. }
  284. for (int i : llvm::seq(num_keywords)) {
  285. tokens[num_symbols + i] = keywords[i % keywords.size()].fixed_spelling();
  286. }
  287. for (int i : llvm::seq(num_identifiers)) {
  288. // We always have enough identifiers, so no need to mod here.
  289. tokens[num_symbols + num_keywords + i] = ids[i];
  290. }
  291. std::shuffle(tokens.begin(), tokens.end(), absl::BitGen());
  292. // Distribute the tokens across lines as well as horizontal whitespace. The
  293. // goal isn't to make any one line representative of anything, but to make the
  294. // rough density of different kinds of whitespace roughly representative.
  295. //
  296. // TODO: This is a really coarse approach that just picks a fixed number of
  297. // tokens per line rather than using some distribution with this as the median
  298. // or mean.
  299. llvm::SmallVector<std::string> lines;
  300. // First place tokens onto each line.
  301. for (auto i : llvm::seq(NumTokens / options.tokens_per_line)) {
  302. lines.push_back("");
  303. llvm::raw_string_ostream os(lines.back());
  304. // Arbitrarily indent each line by two spaces.
  305. os << " ";
  306. llvm::ListSeparator sep(" ");
  307. for (int j : llvm::seq(options.tokens_per_line)) {
  308. os << sep << tokens[i * options.tokens_per_line + j];
  309. }
  310. }
  311. // Next, synthesize blank and comment lines with the correct distribution.
  312. int token_line_percent =
  313. 100 - options.blank_line_percent - options.comment_line_percent;
  314. CARBON_CHECK(token_line_percent > 0);
  315. int num_token_lines = lines.size();
  316. int num_lines = num_token_lines * 100 / token_line_percent;
  317. int num_blank_lines = num_lines * options.blank_line_percent / 100;
  318. int num_comment_lines = num_lines - num_blank_lines - num_token_lines;
  319. CARBON_CHECK(num_comment_lines >= 0);
  320. lines.resize(num_lines);
  321. for (auto& line :
  322. llvm::MutableArrayRef(lines).slice(num_lines - num_comment_lines)) {
  323. // TODO: We should vary the content and length, especially as the
  324. // distribution is weirdly shaped with just over half the comment lines
  325. // being blank and the median length of non-black comment lines being 64!
  326. // This is a *very* coarse approximation of the mean at 30 characters long.
  327. line = " // abcdefghijklmnopqrstuvwxyz";
  328. }
  329. // Now shuffle the lines.
  330. std::shuffle(lines.begin(), lines.end(), absl::BitGen());
  331. // And join them into the source string.
  332. return llvm::join(lines, "\n");
  333. }
  334. class LexerBenchHelper {
  335. public:
  336. explicit LexerBenchHelper(llvm::StringRef text)
  337. : source_(MakeSourceBuffer(text)) {}
  338. auto Lex() -> TokenizedBuffer {
  339. DiagnosticConsumer& consumer = NullDiagnosticConsumer();
  340. return TokenizedBuffer::Lex(value_stores_, source_, consumer);
  341. }
  342. auto DiagnoseErrors() -> std::string {
  343. std::string result;
  344. llvm::raw_string_ostream out(result);
  345. StreamDiagnosticConsumer consumer(out);
  346. auto buffer = TokenizedBuffer::Lex(value_stores_, source_, consumer);
  347. consumer.Flush();
  348. CARBON_CHECK(buffer.has_errors())
  349. << "Asked to diagnose errors but none found!";
  350. return result;
  351. }
  352. auto source_text() -> llvm::StringRef { return source_.text(); }
  353. private:
  354. auto MakeSourceBuffer(llvm::StringRef text) -> SourceBuffer {
  355. CARBON_CHECK(fs_.addFile(filename_, /*ModificationTime=*/0,
  356. llvm::MemoryBuffer::getMemBuffer(text)));
  357. return std::move(*SourceBuffer::CreateFromFile(
  358. fs_, filename_, ConsoleDiagnosticConsumer()));
  359. }
  360. SharedValueStores value_stores_;
  361. llvm::vfs::InMemoryFileSystem fs_;
  362. std::string filename_ = "test.carbon";
  363. SourceBuffer source_;
  364. };
  365. void BM_ValidKeywords(benchmark::State& state) {
  366. absl::BitGen gen;
  367. std::array<llvm::StringRef, NumTokens> tokens;
  368. for (int i : llvm::seq(NumTokens)) {
  369. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  370. .fixed_spelling();
  371. }
  372. std::shuffle(tokens.begin(), tokens.end(), gen);
  373. std::string source = llvm::join(tokens, " ");
  374. LexerBenchHelper helper(source);
  375. for (auto _ : state) {
  376. TokenizedBuffer buffer = helper.Lex();
  377. CARBON_CHECK(!buffer.has_errors());
  378. }
  379. state.SetBytesProcessed(state.iterations() * source.size());
  380. state.counters["tokens_per_second"] = benchmark::Counter(
  381. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  382. }
  383. BENCHMARK(BM_ValidKeywords);
  384. template <int MinLength, int MaxLength, bool Uniform>
  385. void BM_ValidIdentifiers(benchmark::State& state) {
  386. std::string source = RandomIdentifierSeq<MinLength, MaxLength, Uniform>();
  387. LexerBenchHelper helper(source);
  388. for (auto _ : state) {
  389. TokenizedBuffer buffer = helper.Lex();
  390. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  391. }
  392. state.SetBytesProcessed(state.iterations() * source.size());
  393. state.counters["tokens_per_second"] = benchmark::Counter(
  394. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  395. }
  396. // Benchmark the non-uniform distribution we observe in C++ code.
  397. BENCHMARK(BM_ValidIdentifiers<1, 64, /*Uniform=*/false>);
  398. // Also benchmark a few uniform distribution ranges of identifier widths to
  399. // cover different patterns that emerge with small, medium, and longer
  400. // identifiers.
  401. BENCHMARK(BM_ValidIdentifiers<1, 1, /*Uniform=*/true>);
  402. BENCHMARK(BM_ValidIdentifiers<3, 5, /*Uniform=*/true>);
  403. BENCHMARK(BM_ValidIdentifiers<3, 16, /*Uniform=*/true>);
  404. BENCHMARK(BM_ValidIdentifiers<12, 64, /*Uniform=*/true>);
  405. BENCHMARK(BM_ValidIdentifiers<16, 16, /*Uniform=*/true>);
  406. BENCHMARK(BM_ValidIdentifiers<24, 24, /*Uniform=*/true>);
  407. BENCHMARK(BM_ValidIdentifiers<32, 32, /*Uniform=*/true>);
  408. BENCHMARK(BM_ValidIdentifiers<48, 48, /*Uniform=*/true>);
  409. BENCHMARK(BM_ValidIdentifiers<64, 64, /*Uniform=*/true>);
  410. BENCHMARK(BM_ValidIdentifiers<80, 80, /*Uniform=*/true>);
  411. // Benchmark to stress the lexing of horizontal whitespace. This sets up what is
  412. // nearly a worst-case scenario of short-but-expensive-to-lex tokens with runs
  413. // of horizontal whitespace between them.
  414. void BM_HorizontalWhitespace(benchmark::State& state) {
  415. int num_spaces = state.range(0);
  416. std::string separator(num_spaces, ' ');
  417. std::string source = RandomIdentifierSeq<3, 5, /*Uniform=*/true>(separator);
  418. LexerBenchHelper helper(source);
  419. for (auto _ : state) {
  420. TokenizedBuffer buffer = helper.Lex();
  421. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  422. // hit errors that would skew the benchmark results.
  423. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  424. }
  425. state.SetBytesProcessed(state.iterations() * source.size());
  426. state.counters["tokens_per_second"] = benchmark::Counter(
  427. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  428. }
  429. BENCHMARK(BM_HorizontalWhitespace)->RangeMultiplier(4)->Range(1, 128);
  430. void BM_RandomSource(benchmark::State& state) {
  431. std::string source = RandomSource(DefaultSourceDist);
  432. LexerBenchHelper helper(source);
  433. for (auto _ : state) {
  434. TokenizedBuffer buffer = helper.Lex();
  435. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  436. // hit errors that would skew the benchmark results.
  437. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  438. }
  439. state.SetBytesProcessed(state.iterations() * source.size());
  440. state.counters["tokens_per_second"] = benchmark::Counter(
  441. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  442. state.counters["lines_per_second"] =
  443. benchmark::Counter(llvm::StringRef(source).count('\n'),
  444. benchmark::Counter::kIsIterationInvariantRate);
  445. }
  446. // The distributions between symbols, keywords, and identifiers here are
  447. // guesses. Eventually, we should collect more data to help tune these, but
  448. // hopefully the performance isn't too sensitive and we can just cover a wide
  449. // range here.
  450. BENCHMARK(BM_RandomSource);
  451. // Benchmark to stress opening and closing grouped symbols.
  452. void BM_GroupingSymbols(benchmark::State& state) {
  453. int curly_brace_depth = state.range(0);
  454. int paren_depth = state.range(1);
  455. int square_bracket_depth = state.range(2);
  456. // TODO: It might be interesting to have some random pattern of nesting, but
  457. // the obvious ways to do that result it really unstable total size of input
  458. // or unbalanced groups. For now, just use a simple strict nesting approach.
  459. // It should still let us look for specific pain points. We do include some
  460. // whitespace and keywords to make sure *some* other parts of the benchmark
  461. // are also active and have some reasonable icache pressure.
  462. const std::array<std::string, NumTokens>& ids = GetRandomIdentifiers();
  463. std::string source;
  464. llvm::raw_string_ostream os(source);
  465. int num_tokens_per_nest =
  466. curly_brace_depth * 2 + paren_depth * 2 + square_bracket_depth * 2 + 2;
  467. int num_nests = NumTokens / num_tokens_per_nest;
  468. for (int i : llvm::seq(num_nests)) {
  469. for (int j : llvm::seq(curly_brace_depth)) {
  470. os.indent(j * 2) << "{\n";
  471. }
  472. os.indent(curly_brace_depth * 2);
  473. for ([[gnu::unused]] int j : llvm::seq(paren_depth)) {
  474. os << "(";
  475. }
  476. for ([[gnu::unused]] int j : llvm::seq(square_bracket_depth)) {
  477. os << "[";
  478. }
  479. os << ids[(i * 2) % NumTokens];
  480. for ([[gnu::unused]] int j : llvm::seq(square_bracket_depth)) {
  481. os << "]";
  482. }
  483. for ([[gnu::unused]] int j : llvm::seq(paren_depth)) {
  484. os << ")";
  485. }
  486. for (int j : llvm::reverse(llvm::seq(curly_brace_depth))) {
  487. os << "\n";
  488. os.indent(j * 2) << "}";
  489. }
  490. os << ids[(i * 2 + 1) % NumTokens] << "\n";
  491. }
  492. LexerBenchHelper helper(os.str());
  493. for (auto _ : state) {
  494. TokenizedBuffer buffer = helper.Lex();
  495. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  496. // hit errors that would skew the benchmark results.
  497. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  498. }
  499. state.SetBytesProcessed(state.iterations() * source.size());
  500. state.counters["tokens_per_second"] = benchmark::Counter(
  501. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  502. state.counters["lines_per_second"] =
  503. benchmark::Counter(llvm::StringRef(source).count('\n'),
  504. benchmark::Counter::kIsIterationInvariantRate);
  505. }
  506. BENCHMARK(BM_GroupingSymbols)
  507. ->ArgsProduct({
  508. {1, 2, 3, 4, 8, 16, 32},
  509. {0},
  510. {0},
  511. })
  512. ->ArgsProduct({
  513. {0},
  514. {1, 2, 3, 4, 8, 16, 32},
  515. {0},
  516. })
  517. ->ArgsProduct({
  518. {0},
  519. {0},
  520. {1, 2, 3, 4, 8, 16, 32},
  521. })
  522. ->ArgsProduct({
  523. {32},
  524. {1, 2, 3, 4, 8, 16, 32},
  525. {0},
  526. })
  527. ->ArgsProduct({
  528. {32},
  529. {32},
  530. {1, 2, 3, 4, 8, 16, 32},
  531. });
  532. // Benchmark to stress the lexing of blank lines. This uses a simple, easy to
  533. // lex token, but separates each one by varying numbers of blank lines.
  534. void BM_BlankLines(benchmark::State& state) {
  535. int num_blank_lines = state.range(0);
  536. std::string separator(num_blank_lines, '\n');
  537. std::string source = RandomIdentifierSeq<3, 5, /*Uniform=*/true>(separator);
  538. LexerBenchHelper helper(source);
  539. for (auto _ : state) {
  540. TokenizedBuffer buffer = helper.Lex();
  541. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  542. // hit errors that would skew the benchmark results.
  543. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  544. }
  545. state.SetBytesProcessed(state.iterations() * source.size());
  546. state.counters["tokens_per_second"] = benchmark::Counter(
  547. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  548. state.counters["lines_per_second"] =
  549. benchmark::Counter(llvm::StringRef(source).count('\n'),
  550. benchmark::Counter::kIsIterationInvariantRate);
  551. }
  552. BENCHMARK(BM_BlankLines)->RangeMultiplier(4)->Range(1, 128);
  553. // Benchmark to stress the lexing of comment lines. This uses a simple, easy to
  554. // lex token, but separates each one by varying numbers of comment lines, with
  555. // varying comment line length and indentation.
  556. void BM_CommentLines(benchmark::State& state) {
  557. int num_comment_lines = state.range(0);
  558. int comment_length = state.range(1);
  559. int comment_indent = state.range(2);
  560. std::string separator;
  561. llvm::raw_string_ostream os(separator);
  562. os << "\n";
  563. for (int i : llvm::seq(num_comment_lines)) {
  564. static_cast<void>(i);
  565. os << std::string(comment_indent, ' ') << "//"
  566. << std::string(comment_length, ' ') << "\n";
  567. }
  568. std::string source = RandomIdentifierSeq<3, 5, /*Uniform=*/true>(separator);
  569. LexerBenchHelper helper(source);
  570. for (auto _ : state) {
  571. TokenizedBuffer buffer = helper.Lex();
  572. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  573. // hit errors that would skew the benchmark results.
  574. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  575. }
  576. state.SetBytesProcessed(state.iterations() * source.size());
  577. state.counters["tokens_per_second"] = benchmark::Counter(
  578. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  579. state.counters["lines_per_second"] =
  580. benchmark::Counter(llvm::StringRef(source).count('\n'),
  581. benchmark::Counter::kIsIterationInvariantRate);
  582. }
  583. BENCHMARK(BM_CommentLines)
  584. ->ArgsProduct({
  585. // How many lines of comment. Focused on a couple of small and checking
  586. // how it scales up to large blocks.
  587. {1, 4, 128},
  588. // Comment lengths: the two extremes and a middling length.
  589. {0, 30, 70},
  590. // Comment indentations.
  591. {0, 2, 8},
  592. });
  593. // This is a speed-of-light benchmark that should reflect memory bandwidth
  594. // (ideally) of simply reading all the source code. For speed-of-light we use
  595. // `strcpy` -- this both examines ever byte of the input looking for a null to
  596. // end the copy, and also writes to a data structure of roughly the same size as
  597. // the input. This routine is one we expect to be *very* well optimized and give
  598. // a good approximation of the fastest possible lexer given the physical
  599. // constraints of the machine. Note that which particular source we use as input
  600. // here isn't especially interesting, so we just pick one and should update it
  601. // to reflect whatever distribution is most realistic long-term. The
  602. // bytes/second throughput is the important output of this routine.
  603. auto BM_SpeedOfLightStrCpy(benchmark::State& state) -> void {
  604. std::string source = RandomSource(DefaultSourceDist);
  605. // A buffer to write the null-terminated contents of `source` into.
  606. llvm::OwningArrayRef<char> buffer(source.size() + 1);
  607. for (auto _ : state) {
  608. const char* text = source.data();
  609. benchmark::DoNotOptimize(text);
  610. strcpy(buffer.data(), text);
  611. benchmark::DoNotOptimize(buffer.data());
  612. }
  613. state.SetBytesProcessed(state.iterations() * source.size());
  614. state.counters["tokens_per_second"] = benchmark::Counter(
  615. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  616. state.counters["lines_per_second"] =
  617. benchmark::Counter(llvm::StringRef(source).count('\n'),
  618. benchmark::Counter::kIsIterationInvariantRate);
  619. }
  620. BENCHMARK(BM_SpeedOfLightStrCpy);
  621. // This is a speed-of-light benchmark that builds up a best-case byte-wise table
  622. // dispatch using guaranteed tail recursion. The goal is both to ensure the
  623. // general technique can reasonably hit the level of performance we need and to
  624. // establish how far from this speed of light the actual lexer currently sits.
  625. //
  626. // A major impact on the observed performance of this technique is how many
  627. // different functions are reached in this dispatch loop. This benchmark
  628. // infrastructure tries to bracket the range of performance this technique
  629. // affords with different numbers of dispatch target functions.
  630. using DispatchPtrT = auto (*)(ssize_t& index, const char* text, char* buffer)
  631. -> void;
  632. using DispatchTableT = std::array<DispatchPtrT, 256>;
  633. template <const DispatchTableT& Table>
  634. auto BasicDispatch(ssize_t& index, const char* text, char* buffer) -> void {
  635. *buffer = text[index];
  636. ++index;
  637. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  638. index, text, buffer);
  639. }
  640. template <const DispatchTableT& Table, char C>
  641. auto SpecializedDispatch(ssize_t& index, const char* text, char* buffer)
  642. -> void {
  643. CARBON_CHECK(C == text[index]);
  644. *buffer = C;
  645. ++index;
  646. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  647. index, text, buffer);
  648. }
  649. // A sample of the symbol characters used in Carbon code. Doesn't need to be
  650. // perfect, as we just need to have a reasonably large # of distinct dispatch
  651. // functions.
  652. constexpr char DispatchSpecializableSymbols[] = {
  653. '!', '%', '(', ')', '*', '+', ',', '-', '.', ':',
  654. ';', '<', '=', '>', '?', '[', ']', '{', '}', '~',
  655. };
  656. // Create an array of all the characters we can specialize dispatch over --
  657. // [0-9A-Za-z] and the symbols above. Similar to the above symbols, doesn't need
  658. // to be exhaustive.
  659. constexpr std::array<char, 26 * 2 + 10 + sizeof(DispatchSpecializableSymbols)>
  660. DispatchSpecializableChars = []() {
  661. constexpr int Size = sizeof(DispatchSpecializableChars);
  662. std::array<char, Size> chars = {};
  663. int i = 0;
  664. for (char c = '0'; c <= '9'; ++c) {
  665. chars[i] = c;
  666. ++i;
  667. }
  668. for (char c = 'A'; c <= 'Z'; ++c) {
  669. chars[i] = c;
  670. ++i;
  671. }
  672. for (char c = 'a'; c <= 'z'; ++c) {
  673. chars[i] = c;
  674. ++i;
  675. }
  676. for (char c : DispatchSpecializableSymbols) {
  677. chars[i] = c;
  678. ++i;
  679. }
  680. CARBON_CHECK(i == Size);
  681. return chars;
  682. }();
  683. // Instantiate a number of specialized dispatch functions for characters in the
  684. // array above, and assign those function addresses to the character's entry in
  685. // the provided table. The provided `tmp_table` is a temporary that will
  686. // eventually initialize the provided `Table` constant, so the constant is what
  687. // we propagate to the instantiated function and the temporary is the one we
  688. // initialize.
  689. template <const DispatchTableT& Table, size_t... Indices>
  690. constexpr auto SpecializeDispatchTable(
  691. DispatchTableT& tmp_table, std::index_sequence<Indices...> /*indices*/)
  692. -> void {
  693. static_assert(sizeof...(Indices) <= sizeof(DispatchSpecializableChars));
  694. ((tmp_table[static_cast<unsigned char>(DispatchSpecializableChars[Indices])] =
  695. &SpecializedDispatch<Table, DispatchSpecializableChars[Indices]>),
  696. ...);
  697. }
  698. // The maximum number of dispatch targets is the size of the array + 1 (for the
  699. // base case target).
  700. constexpr int MaxDispatchTargets = sizeof(DispatchSpecializableChars) + 1;
  701. // Dispatch tables with a provided number of distinct dispatch targets. There
  702. // will always be one additional target for the null byte to end the loop.
  703. template <int NumDispatchTargets>
  704. constexpr DispatchTableT DispatchTable = []() {
  705. static_assert(NumDispatchTargets > 0, "Need at least one dispatch target.");
  706. static_assert(NumDispatchTargets <= MaxDispatchTargets,
  707. "Limited number of dispatch targets available.");
  708. DispatchTableT tmp_table = {};
  709. // Start with the basic dispatch target.
  710. for (int i = 0; i < 256; ++i) {
  711. tmp_table[i] = &BasicDispatch<DispatchTable<NumDispatchTargets>>;
  712. }
  713. if constexpr (NumDispatchTargets > 1) {
  714. // Add additional dispatch targets from our specializable array.
  715. SpecializeDispatchTable<DispatchTable<NumDispatchTargets>>(
  716. tmp_table, std::make_index_sequence<NumDispatchTargets - 1>());
  717. }
  718. // Special case the null byte index to end the tail-dispatch.
  719. tmp_table[0] =
  720. +[](ssize_t& index, const char* text, char* /*buffer*/) -> void {
  721. CARBON_CHECK(text[index] == '\0');
  722. return;
  723. };
  724. return tmp_table;
  725. }();
  726. template <int NumDispatchTargets>
  727. auto BM_SpeedOfLightDispatch(benchmark::State& state) -> void {
  728. std::string source = RandomSource(DefaultSourceDist);
  729. // A buffer to write to, simulating some minimal write traffic.
  730. llvm::OwningArrayRef<char> buffer(source.size());
  731. for (auto _ : state) {
  732. const char* text = source.data();
  733. benchmark::DoNotOptimize(text);
  734. // Use `ssize_t` to minimize indexing overhead.
  735. ssize_t i = 0;
  736. // The dispatch table tail-recurses through the entire string.
  737. DispatchTable<NumDispatchTargets>[static_cast<unsigned char>(text[i])](
  738. i, text, buffer.data());
  739. CARBON_CHECK(i == static_cast<ssize_t>(source.size()));
  740. benchmark::DoNotOptimize(buffer.data());
  741. }
  742. state.SetBytesProcessed(state.iterations() * source.size());
  743. state.counters["tokens_per_second"] = benchmark::Counter(
  744. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  745. state.counters["lines_per_second"] =
  746. benchmark::Counter(llvm::StringRef(source).count('\n'),
  747. benchmark::Counter::kIsIterationInvariantRate);
  748. }
  749. BENCHMARK(BM_SpeedOfLightDispatch<1>);
  750. BENCHMARK(BM_SpeedOfLightDispatch<2>);
  751. BENCHMARK(BM_SpeedOfLightDispatch<4>);
  752. BENCHMARK(BM_SpeedOfLightDispatch<8>);
  753. BENCHMARK(BM_SpeedOfLightDispatch<16>);
  754. BENCHMARK(BM_SpeedOfLightDispatch<32>);
  755. BENCHMARK(BM_SpeedOfLightDispatch<MaxDispatchTargets>);
  756. } // namespace
  757. } // namespace Carbon::Lex