tokenized_buffer_benchmark.cpp 35 KB

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