tokenized_buffer_benchmark.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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. void BM_ValidKeywordsAsRawIdentifiers(benchmark::State& state) {
  385. absl::BitGen gen;
  386. std::array<llvm::StringRef, NumTokens> tokens;
  387. for (int i : llvm::seq(NumTokens)) {
  388. tokens[i] = TokenKind::KeywordTokens[i % TokenKind::KeywordTokens.size()]
  389. .fixed_spelling();
  390. }
  391. std::shuffle(tokens.begin(), tokens.end(), gen);
  392. std::string source("r#");
  393. source.append(llvm::join(tokens, " r#"));
  394. LexerBenchHelper helper(source);
  395. for (auto _ : state) {
  396. TokenizedBuffer buffer = helper.Lex();
  397. CARBON_CHECK(!buffer.has_errors());
  398. }
  399. state.SetBytesProcessed(state.iterations() * source.size());
  400. state.counters["tokens_per_second"] = benchmark::Counter(
  401. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  402. }
  403. BENCHMARK(BM_ValidKeywordsAsRawIdentifiers);
  404. // This benchmark does a 50-50 split of r-prefixed and r#-prefixed identifiers
  405. // to directly compare raw and non-raw performance.
  406. void BM_RawIdentifierFocus(benchmark::State& state) {
  407. const std::array<std::string, NumTokens>& ids = GetRandomIdentifiers();
  408. llvm::SmallVector<std::string> modified_ids;
  409. // As we resize, start with the in-use prefix. Note that `r#` uses the first
  410. // character of the original identifier.
  411. modified_ids.resize(NumTokens / 2, "r#");
  412. modified_ids.resize(NumTokens, "r");
  413. for (int i : llvm::seq(NumTokens / 2)) {
  414. // Use the same identifier both ways.
  415. modified_ids[i].append(ids[i]);
  416. modified_ids[i + NumTokens / 2].append(
  417. llvm::StringRef(ids[i]).drop_front());
  418. }
  419. absl::BitGen gen;
  420. std::array<llvm::StringRef, NumTokens> tokens;
  421. for (int i : llvm::seq(NumTokens)) {
  422. tokens[i] = modified_ids[i];
  423. }
  424. std::shuffle(tokens.begin(), tokens.end(), gen);
  425. std::string source = llvm::join(tokens, " ");
  426. LexerBenchHelper helper(source);
  427. for (auto _ : state) {
  428. TokenizedBuffer buffer = helper.Lex();
  429. CARBON_CHECK(!buffer.has_errors());
  430. }
  431. state.SetBytesProcessed(state.iterations() * source.size());
  432. state.counters["tokens_per_second"] = benchmark::Counter(
  433. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  434. }
  435. BENCHMARK(BM_RawIdentifierFocus);
  436. template <int MinLength, int MaxLength, bool Uniform>
  437. void BM_ValidIdentifiers(benchmark::State& state) {
  438. std::string source = RandomIdentifierSeq<MinLength, MaxLength, Uniform>();
  439. LexerBenchHelper helper(source);
  440. for (auto _ : state) {
  441. TokenizedBuffer buffer = helper.Lex();
  442. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  443. }
  444. state.SetBytesProcessed(state.iterations() * source.size());
  445. state.counters["tokens_per_second"] = benchmark::Counter(
  446. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  447. }
  448. // Benchmark the non-uniform distribution we observe in C++ code.
  449. BENCHMARK(BM_ValidIdentifiers<1, 64, /*Uniform=*/false>);
  450. // Also benchmark a few uniform distribution ranges of identifier widths to
  451. // cover different patterns that emerge with small, medium, and longer
  452. // identifiers.
  453. BENCHMARK(BM_ValidIdentifiers<1, 1, /*Uniform=*/true>);
  454. BENCHMARK(BM_ValidIdentifiers<3, 5, /*Uniform=*/true>);
  455. BENCHMARK(BM_ValidIdentifiers<3, 16, /*Uniform=*/true>);
  456. BENCHMARK(BM_ValidIdentifiers<12, 64, /*Uniform=*/true>);
  457. BENCHMARK(BM_ValidIdentifiers<16, 16, /*Uniform=*/true>);
  458. BENCHMARK(BM_ValidIdentifiers<24, 24, /*Uniform=*/true>);
  459. BENCHMARK(BM_ValidIdentifiers<32, 32, /*Uniform=*/true>);
  460. BENCHMARK(BM_ValidIdentifiers<48, 48, /*Uniform=*/true>);
  461. BENCHMARK(BM_ValidIdentifiers<64, 64, /*Uniform=*/true>);
  462. BENCHMARK(BM_ValidIdentifiers<80, 80, /*Uniform=*/true>);
  463. // Benchmark to stress the lexing of horizontal whitespace. This sets up what is
  464. // nearly a worst-case scenario of short-but-expensive-to-lex tokens with runs
  465. // of horizontal whitespace between them.
  466. void BM_HorizontalWhitespace(benchmark::State& state) {
  467. int num_spaces = state.range(0);
  468. std::string separator(num_spaces, ' ');
  469. std::string source = RandomIdentifierSeq<3, 5, /*Uniform=*/true>(separator);
  470. LexerBenchHelper helper(source);
  471. for (auto _ : state) {
  472. TokenizedBuffer buffer = helper.Lex();
  473. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  474. // hit errors that would skew the benchmark results.
  475. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  476. }
  477. state.SetBytesProcessed(state.iterations() * source.size());
  478. state.counters["tokens_per_second"] = benchmark::Counter(
  479. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  480. }
  481. BENCHMARK(BM_HorizontalWhitespace)->RangeMultiplier(4)->Range(1, 128);
  482. void BM_RandomSource(benchmark::State& state) {
  483. std::string source = RandomSource(DefaultSourceDist);
  484. LexerBenchHelper helper(source);
  485. for (auto _ : state) {
  486. TokenizedBuffer buffer = helper.Lex();
  487. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  488. // hit errors that would skew the benchmark results.
  489. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  490. }
  491. state.SetBytesProcessed(state.iterations() * source.size());
  492. state.counters["tokens_per_second"] = benchmark::Counter(
  493. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  494. state.counters["lines_per_second"] =
  495. benchmark::Counter(llvm::StringRef(source).count('\n'),
  496. benchmark::Counter::kIsIterationInvariantRate);
  497. }
  498. // The distributions between symbols, keywords, and identifiers here are
  499. // guesses. Eventually, we should collect more data to help tune these, but
  500. // hopefully the performance isn't too sensitive and we can just cover a wide
  501. // range here.
  502. BENCHMARK(BM_RandomSource);
  503. // Benchmark to stress opening and closing grouped symbols.
  504. void BM_GroupingSymbols(benchmark::State& state) {
  505. int curly_brace_depth = state.range(0);
  506. int paren_depth = state.range(1);
  507. int square_bracket_depth = state.range(2);
  508. // TODO: It might be interesting to have some random pattern of nesting, but
  509. // the obvious ways to do that result it really unstable total size of input
  510. // or unbalanced groups. For now, just use a simple strict nesting approach.
  511. // It should still let us look for specific pain points. We do include some
  512. // whitespace and keywords to make sure *some* other parts of the benchmark
  513. // are also active and have some reasonable icache pressure.
  514. const std::array<std::string, NumTokens>& ids = GetRandomIdentifiers();
  515. std::string source;
  516. llvm::raw_string_ostream os(source);
  517. int num_tokens_per_nest =
  518. curly_brace_depth * 2 + paren_depth * 2 + square_bracket_depth * 2 + 2;
  519. int num_nests = NumTokens / num_tokens_per_nest;
  520. for (int i : llvm::seq(num_nests)) {
  521. for (int j : llvm::seq(curly_brace_depth)) {
  522. os.indent(j * 2) << "{\n";
  523. }
  524. os.indent(curly_brace_depth * 2);
  525. for ([[gnu::unused]] int j : llvm::seq(paren_depth)) {
  526. os << "(";
  527. }
  528. for ([[gnu::unused]] int j : llvm::seq(square_bracket_depth)) {
  529. os << "[";
  530. }
  531. os << ids[(i * 2) % NumTokens];
  532. for ([[gnu::unused]] int j : llvm::seq(square_bracket_depth)) {
  533. os << "]";
  534. }
  535. for ([[gnu::unused]] int j : llvm::seq(paren_depth)) {
  536. os << ")";
  537. }
  538. for (int j : llvm::reverse(llvm::seq(curly_brace_depth))) {
  539. os << "\n";
  540. os.indent(j * 2) << "}";
  541. }
  542. os << ids[(i * 2 + 1) % NumTokens] << "\n";
  543. }
  544. LexerBenchHelper helper(os.str());
  545. for (auto _ : state) {
  546. TokenizedBuffer buffer = helper.Lex();
  547. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  548. // hit errors that would skew the benchmark results.
  549. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  550. }
  551. state.SetBytesProcessed(state.iterations() * source.size());
  552. state.counters["tokens_per_second"] = benchmark::Counter(
  553. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  554. state.counters["lines_per_second"] =
  555. benchmark::Counter(llvm::StringRef(source).count('\n'),
  556. benchmark::Counter::kIsIterationInvariantRate);
  557. }
  558. BENCHMARK(BM_GroupingSymbols)
  559. ->ArgsProduct({
  560. {1, 2, 3, 4, 8, 16, 32},
  561. {0},
  562. {0},
  563. })
  564. ->ArgsProduct({
  565. {0},
  566. {1, 2, 3, 4, 8, 16, 32},
  567. {0},
  568. })
  569. ->ArgsProduct({
  570. {0},
  571. {0},
  572. {1, 2, 3, 4, 8, 16, 32},
  573. })
  574. ->ArgsProduct({
  575. {32},
  576. {1, 2, 3, 4, 8, 16, 32},
  577. {0},
  578. })
  579. ->ArgsProduct({
  580. {32},
  581. {32},
  582. {1, 2, 3, 4, 8, 16, 32},
  583. });
  584. // Benchmark to stress the lexing of blank lines. This uses a simple, easy to
  585. // lex token, but separates each one by varying numbers of blank lines.
  586. void BM_BlankLines(benchmark::State& state) {
  587. int num_blank_lines = state.range(0);
  588. std::string separator(num_blank_lines, '\n');
  589. std::string source = RandomIdentifierSeq<3, 5, /*Uniform=*/true>(separator);
  590. LexerBenchHelper helper(source);
  591. for (auto _ : state) {
  592. TokenizedBuffer buffer = helper.Lex();
  593. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  594. // hit errors that would skew the benchmark results.
  595. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  596. }
  597. state.SetBytesProcessed(state.iterations() * source.size());
  598. state.counters["tokens_per_second"] = benchmark::Counter(
  599. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  600. state.counters["lines_per_second"] =
  601. benchmark::Counter(llvm::StringRef(source).count('\n'),
  602. benchmark::Counter::kIsIterationInvariantRate);
  603. }
  604. BENCHMARK(BM_BlankLines)->RangeMultiplier(4)->Range(1, 128);
  605. // Benchmark to stress the lexing of comment lines. This uses a simple, easy to
  606. // lex token, but separates each one by varying numbers of comment lines, with
  607. // varying comment line length and indentation.
  608. void BM_CommentLines(benchmark::State& state) {
  609. int num_comment_lines = state.range(0);
  610. int comment_length = state.range(1);
  611. int comment_indent = state.range(2);
  612. std::string separator;
  613. llvm::raw_string_ostream os(separator);
  614. os << "\n";
  615. for (int i : llvm::seq(num_comment_lines)) {
  616. static_cast<void>(i);
  617. os << std::string(comment_indent, ' ') << "//"
  618. << std::string(comment_length, ' ') << "\n";
  619. }
  620. std::string source = RandomIdentifierSeq<3, 5, /*Uniform=*/true>(separator);
  621. LexerBenchHelper helper(source);
  622. for (auto _ : state) {
  623. TokenizedBuffer buffer = helper.Lex();
  624. // Ensure that lexing actually occurs for benchmarking and that it doesn't
  625. // hit errors that would skew the benchmark results.
  626. CARBON_CHECK(!buffer.has_errors()) << helper.DiagnoseErrors();
  627. }
  628. state.SetBytesProcessed(state.iterations() * source.size());
  629. state.counters["tokens_per_second"] = benchmark::Counter(
  630. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  631. state.counters["lines_per_second"] =
  632. benchmark::Counter(llvm::StringRef(source).count('\n'),
  633. benchmark::Counter::kIsIterationInvariantRate);
  634. }
  635. BENCHMARK(BM_CommentLines)
  636. ->ArgsProduct({
  637. // How many lines of comment. Focused on a couple of small and checking
  638. // how it scales up to large blocks.
  639. {1, 4, 128},
  640. // Comment lengths: the two extremes and a middling length.
  641. {0, 30, 70},
  642. // Comment indentations.
  643. {0, 2, 8},
  644. });
  645. // This is a speed-of-light benchmark that should reflect memory bandwidth
  646. // (ideally) of simply reading all the source code. For speed-of-light we use
  647. // `strcpy` -- this both examines ever byte of the input looking for a null to
  648. // end the copy, and also writes to a data structure of roughly the same size as
  649. // the input. This routine is one we expect to be *very* well optimized and give
  650. // a good approximation of the fastest possible lexer given the physical
  651. // constraints of the machine. Note that which particular source we use as input
  652. // here isn't especially interesting, so we just pick one and should update it
  653. // to reflect whatever distribution is most realistic long-term. The
  654. // bytes/second throughput is the important output of this routine.
  655. auto BM_SpeedOfLightStrCpy(benchmark::State& state) -> void {
  656. std::string source = RandomSource(DefaultSourceDist);
  657. // A buffer to write the null-terminated contents of `source` into.
  658. llvm::OwningArrayRef<char> buffer(source.size() + 1);
  659. for (auto _ : state) {
  660. const char* text = source.data();
  661. benchmark::DoNotOptimize(text);
  662. strcpy(buffer.data(), text);
  663. benchmark::DoNotOptimize(buffer.data());
  664. }
  665. state.SetBytesProcessed(state.iterations() * source.size());
  666. state.counters["tokens_per_second"] = benchmark::Counter(
  667. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  668. state.counters["lines_per_second"] =
  669. benchmark::Counter(llvm::StringRef(source).count('\n'),
  670. benchmark::Counter::kIsIterationInvariantRate);
  671. }
  672. BENCHMARK(BM_SpeedOfLightStrCpy);
  673. // This is a speed-of-light benchmark that builds up a best-case byte-wise table
  674. // dispatch using guaranteed tail recursion. The goal is both to ensure the
  675. // general technique can reasonably hit the level of performance we need and to
  676. // establish how far from this speed of light the actual lexer currently sits.
  677. //
  678. // A major impact on the observed performance of this technique is how many
  679. // different functions are reached in this dispatch loop. This benchmark
  680. // infrastructure tries to bracket the range of performance this technique
  681. // affords with different numbers of dispatch target functions.
  682. using DispatchPtrT = auto (*)(ssize_t& index, const char* text, char* buffer)
  683. -> void;
  684. using DispatchTableT = std::array<DispatchPtrT, 256>;
  685. template <const DispatchTableT& Table>
  686. auto BasicDispatch(ssize_t& index, const char* text, char* buffer) -> void {
  687. *buffer = text[index];
  688. ++index;
  689. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  690. index, text, buffer);
  691. }
  692. template <const DispatchTableT& Table, char C>
  693. auto SpecializedDispatch(ssize_t& index, const char* text, char* buffer)
  694. -> void {
  695. CARBON_CHECK(C == text[index]);
  696. *buffer = C;
  697. ++index;
  698. [[clang::musttail]] return Table[static_cast<unsigned char>(text[index])](
  699. index, text, buffer);
  700. }
  701. // A sample of the symbol characters used in Carbon code. Doesn't need to be
  702. // perfect, as we just need to have a reasonably large # of distinct dispatch
  703. // functions.
  704. constexpr char DispatchSpecializableSymbols[] = {
  705. '!', '%', '(', ')', '*', '+', ',', '-', '.', ':',
  706. ';', '<', '=', '>', '?', '[', ']', '{', '}', '~',
  707. };
  708. // Create an array of all the characters we can specialize dispatch over --
  709. // [0-9A-Za-z] and the symbols above. Similar to the above symbols, doesn't need
  710. // to be exhaustive.
  711. constexpr std::array<char, 26 * 2 + 10 + sizeof(DispatchSpecializableSymbols)>
  712. DispatchSpecializableChars = []() {
  713. constexpr int Size = sizeof(DispatchSpecializableChars);
  714. std::array<char, Size> chars = {};
  715. int i = 0;
  716. for (char c = '0'; c <= '9'; ++c) {
  717. chars[i] = c;
  718. ++i;
  719. }
  720. for (char c = 'A'; c <= 'Z'; ++c) {
  721. chars[i] = c;
  722. ++i;
  723. }
  724. for (char c = 'a'; c <= 'z'; ++c) {
  725. chars[i] = c;
  726. ++i;
  727. }
  728. for (char c : DispatchSpecializableSymbols) {
  729. chars[i] = c;
  730. ++i;
  731. }
  732. CARBON_CHECK(i == Size);
  733. return chars;
  734. }();
  735. // Instantiate a number of specialized dispatch functions for characters in the
  736. // array above, and assign those function addresses to the character's entry in
  737. // the provided table. The provided `tmp_table` is a temporary that will
  738. // eventually initialize the provided `Table` constant, so the constant is what
  739. // we propagate to the instantiated function and the temporary is the one we
  740. // initialize.
  741. template <const DispatchTableT& Table, size_t... Indices>
  742. constexpr auto SpecializeDispatchTable(
  743. DispatchTableT& tmp_table, std::index_sequence<Indices...> /*indices*/)
  744. -> void {
  745. static_assert(sizeof...(Indices) <= sizeof(DispatchSpecializableChars));
  746. ((tmp_table[static_cast<unsigned char>(DispatchSpecializableChars[Indices])] =
  747. &SpecializedDispatch<Table, DispatchSpecializableChars[Indices]>),
  748. ...);
  749. }
  750. // The maximum number of dispatch targets is the size of the array + 1 (for the
  751. // base case target).
  752. constexpr int MaxDispatchTargets = sizeof(DispatchSpecializableChars) + 1;
  753. // Dispatch tables with a provided number of distinct dispatch targets. There
  754. // will always be one additional target for the null byte to end the loop.
  755. template <int NumDispatchTargets>
  756. constexpr DispatchTableT DispatchTable = []() {
  757. static_assert(NumDispatchTargets > 0, "Need at least one dispatch target.");
  758. static_assert(NumDispatchTargets <= MaxDispatchTargets,
  759. "Limited number of dispatch targets available.");
  760. DispatchTableT tmp_table = {};
  761. // Start with the basic dispatch target.
  762. for (int i = 0; i < 256; ++i) {
  763. tmp_table[i] = &BasicDispatch<DispatchTable<NumDispatchTargets>>;
  764. }
  765. if constexpr (NumDispatchTargets > 1) {
  766. // Add additional dispatch targets from our specializable array.
  767. SpecializeDispatchTable<DispatchTable<NumDispatchTargets>>(
  768. tmp_table, std::make_index_sequence<NumDispatchTargets - 1>());
  769. }
  770. // Special case the null byte index to end the tail-dispatch.
  771. tmp_table[0] =
  772. +[](ssize_t& index, const char* text, char* /*buffer*/) -> void {
  773. CARBON_CHECK(text[index] == '\0');
  774. return;
  775. };
  776. return tmp_table;
  777. }();
  778. template <int NumDispatchTargets>
  779. auto BM_SpeedOfLightDispatch(benchmark::State& state) -> void {
  780. std::string source = RandomSource(DefaultSourceDist);
  781. // A buffer to write to, simulating some minimal write traffic.
  782. llvm::OwningArrayRef<char> buffer(source.size());
  783. for (auto _ : state) {
  784. const char* text = source.data();
  785. benchmark::DoNotOptimize(text);
  786. // Use `ssize_t` to minimize indexing overhead.
  787. ssize_t i = 0;
  788. // The dispatch table tail-recurses through the entire string.
  789. DispatchTable<NumDispatchTargets>[static_cast<unsigned char>(text[i])](
  790. i, text, buffer.data());
  791. CARBON_CHECK(i == static_cast<ssize_t>(source.size()));
  792. benchmark::DoNotOptimize(buffer.data());
  793. }
  794. state.SetBytesProcessed(state.iterations() * source.size());
  795. state.counters["tokens_per_second"] = benchmark::Counter(
  796. NumTokens, benchmark::Counter::kIsIterationInvariantRate);
  797. state.counters["lines_per_second"] =
  798. benchmark::Counter(llvm::StringRef(source).count('\n'),
  799. benchmark::Counter::kIsIterationInvariantRate);
  800. }
  801. BENCHMARK(BM_SpeedOfLightDispatch<1>);
  802. BENCHMARK(BM_SpeedOfLightDispatch<2>);
  803. BENCHMARK(BM_SpeedOfLightDispatch<4>);
  804. BENCHMARK(BM_SpeedOfLightDispatch<8>);
  805. BENCHMARK(BM_SpeedOfLightDispatch<16>);
  806. BENCHMARK(BM_SpeedOfLightDispatch<32>);
  807. BENCHMARK(BM_SpeedOfLightDispatch<MaxDispatchTargets>);
  808. } // namespace
  809. } // namespace Carbon::Lex