| <!DOCTYPE HTML> |
| <html lang="en" class="light sidebar-visible" dir="ltr"> |
| <head> |
| <!-- Book generated using mdBook --> |
| <meta charset="UTF-8"> |
| <title>The Query Evaluation Model in detail - Rust Compiler Development Guide</title> |
| |
| |
| <!-- Custom HTML head --> |
| |
| <meta name="description" content="A guide to developing the Rust compiler (rustc)"> |
| <meta name="viewport" content="width=device-width, initial-scale=1"> |
| <meta name="theme-color" content="#ffffff"> |
| |
| <link rel="icon" href="../favicon.svg"> |
| <link rel="shortcut icon" href="../favicon.png"> |
| <link rel="stylesheet" href="../css/variables.css"> |
| <link rel="stylesheet" href="../css/general.css"> |
| <link rel="stylesheet" href="../css/chrome.css"> |
| <link rel="stylesheet" href="../css/print.css" media="print"> |
| |
| <!-- Fonts --> |
| <link rel="stylesheet" href="../FontAwesome/css/font-awesome.css"> |
| <link rel="stylesheet" href="../fonts/fonts.css"> |
| |
| <!-- Highlight.js Stylesheets --> |
| <link rel="stylesheet" id="highlight-css" href="../highlight.css"> |
| <link rel="stylesheet" id="tomorrow-night-css" href="../tomorrow-night.css"> |
| <link rel="stylesheet" id="ayu-highlight-css" href="../ayu-highlight.css"> |
| |
| <!-- Custom theme stylesheets --> |
| <link rel="stylesheet" href="../pagetoc.css"> |
| |
| |
| <!-- Provide site root and default themes to javascript --> |
| <script> |
| const path_to_root = "../"; |
| const default_light_theme = "light"; |
| const default_dark_theme = "navy"; |
| window.path_to_searchindex_js = "../searchindex.js"; |
| </script> |
| <!-- Start loading toc.js asap --> |
| <script src="../toc.js"></script> |
| </head> |
| <body> |
| <div id="mdbook-help-container"> |
| <div id="mdbook-help-popup"> |
| <h2 class="mdbook-help-title">Keyboard shortcuts</h2> |
| <div> |
| <p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p> |
| <p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p> |
| <p>Press <kbd>?</kbd> to show this help</p> |
| <p>Press <kbd>Esc</kbd> to hide this help</p> |
| </div> |
| </div> |
| </div> |
| <div id="body-container"> |
| <!-- Work around some values being stored in localStorage wrapped in quotes --> |
| <script> |
| try { |
| let theme = localStorage.getItem('mdbook-theme'); |
| let sidebar = localStorage.getItem('mdbook-sidebar'); |
| |
| if (theme.startsWith('"') && theme.endsWith('"')) { |
| localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1)); |
| } |
| |
| if (sidebar.startsWith('"') && sidebar.endsWith('"')) { |
| localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1)); |
| } |
| } catch (e) { } |
| </script> |
| |
| <!-- Set the theme before any content is loaded, prevents flash --> |
| <script> |
| const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme; |
| let theme; |
| try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } |
| if (theme === null || theme === undefined) { theme = default_theme; } |
| const html = document.documentElement; |
| html.classList.remove('light') |
| html.classList.add(theme); |
| html.classList.add("js"); |
| </script> |
| |
| <input type="checkbox" id="sidebar-toggle-anchor" class="hidden"> |
| |
| <!-- Hide / unhide sidebar before it is displayed --> |
| <script> |
| let sidebar = null; |
| const sidebar_toggle = document.getElementById("sidebar-toggle-anchor"); |
| if (document.body.clientWidth >= 1080) { |
| try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } |
| sidebar = sidebar || 'visible'; |
| } else { |
| sidebar = 'hidden'; |
| sidebar_toggle.checked = false; |
| } |
| if (sidebar === 'visible') { |
| sidebar_toggle.checked = true; |
| } else { |
| html.classList.remove('sidebar-visible'); |
| } |
| </script> |
| |
| <nav id="sidebar" class="sidebar" aria-label="Table of contents"> |
| <!-- populated by js --> |
| <mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox> |
| <noscript> |
| <iframe class="sidebar-iframe-outer" src="../toc.html"></iframe> |
| </noscript> |
| <div id="sidebar-resize-handle" class="sidebar-resize-handle"> |
| <div class="sidebar-resize-indicator"></div> |
| </div> |
| </nav> |
| |
| <div id="page-wrapper" class="page-wrapper"> |
| |
| <div class="page"> |
| <div id="menu-bar-hover-placeholder"></div> |
| <div id="menu-bar" class="menu-bar sticky"> |
| <div class="left-buttons"> |
| <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar"> |
| <i class="fa fa-bars"></i> |
| </label> |
| <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list"> |
| <i class="fa fa-paint-brush"></i> |
| </button> |
| <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu"> |
| <li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li> |
| <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li> |
| </ul> |
| <button id="search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="searchbar"> |
| <i class="fa fa-search"></i> |
| </button> |
| </div> |
| |
| <h1 class="menu-title">Rust Compiler Development Guide</h1> |
| |
| <div class="right-buttons"> |
| <a href="../print.html" title="Print this book" aria-label="Print this book"> |
| <i id="print-button" class="fa fa-print"></i> |
| </a> |
| <a href="https://github.com/rust-lang/rustc-dev-guide" title="Git repository" aria-label="Git repository"> |
| <i id="git-repository-button" class="fa fa-github"></i> |
| </a> |
| <a href="https://github.com/rust-lang/rustc-dev-guide/edit/main/src/queries/query-evaluation-model-in-detail.md" title="Suggest an edit" aria-label="Suggest an edit" rel="edit"> |
| <i id="git-edit-button" class="fa fa-edit"></i> |
| </a> |
| |
| </div> |
| </div> |
| |
| <div id="search-wrapper" class="hidden"> |
| <form id="searchbar-outer" class="searchbar-outer"> |
| <div class="search-wrapper"> |
| <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header"> |
| <div class="spinner-wrapper"> |
| <i class="fa fa-spinner fa-spin"></i> |
| </div> |
| </div> |
| </form> |
| <div id="searchresults-outer" class="searchresults-outer hidden"> |
| <div id="searchresults-header" class="searchresults-header"></div> |
| <ul id="searchresults"> |
| </ul> |
| </div> |
| </div> |
| |
| <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM --> |
| <script> |
| document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible'); |
| document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible'); |
| Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) { |
| link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1); |
| }); |
| </script> |
| |
| <div id="content" class="content"> |
| <main> |
| <h1 id="the-query-evaluation-model-in-detail"><a class="header" href="#the-query-evaluation-model-in-detail">The Query Evaluation Model in detail</a></h1> |
| <p>This chapter provides a deeper dive into the abstract model queries are built on. |
| It does not go into implementation details but tries to explain |
| the underlying logic. The examples here, therefore, have been stripped down and |
| simplified and don't directly reflect the compilers internal APIs.</p> |
| <h2 id="what-is-a-query"><a class="header" href="#what-is-a-query">What is a query?</a></h2> |
| <p>Abstractly we view the compiler's knowledge about a given crate as a "database" |
| and queries are the way of asking the compiler questions about it, i.e. |
| we "query" the compiler's "database" for facts.</p> |
| <p>However, there's something special to this compiler database: It starts out empty |
| and is filled on-demand when queries are executed. Consequently, a query must |
| know how to compute its result if the database does not contain it yet. For |
| doing so, it can access other queries and certain input values that the database |
| is pre-filled with on creation.</p> |
| <p>A query thus consists of the following things:</p> |
| <ul> |
| <li>A name that identifies the query</li> |
| <li>A "key" that specifies what we want to look up</li> |
| <li>A result type that specifies what kind of result it yields</li> |
| <li>A "provider" which is a function that specifies how the result is to be |
| computed if it isn't already present in the database.</li> |
| </ul> |
| <p>As an example, the name of the <code>type_of</code> query is <code>type_of</code>, its query key is a |
| <code>DefId</code> identifying the item we want to know the type of, the result type is |
| <code>Ty<'tcx></code>, and the provider is a function that, given the query key and access |
| to the rest of the database, can compute the type of the item identified by the |
| key.</p> |
| <p>So in some sense a query is just a function that maps the query key to the |
| corresponding result. However, we have to apply some restrictions in order for |
| this to be sound:</p> |
| <ul> |
| <li>The key and result must be immutable values.</li> |
| <li>The provider function must be a pure function in the sense that for the same |
| key it must always yield the same result.</li> |
| <li>The only parameters a provider function takes are the key and a reference to |
| the "query context" (which provides access to the rest of the "database").</li> |
| </ul> |
| <p>The database is built up lazily by invoking queries. The query providers will |
| invoke other queries, for which the result is either already cached or computed |
| by calling another query provider. These query provider invocations |
| conceptually form a directed acyclic graph (DAG) at the leaves of which are |
| input values that are already known when the query context is created.</p> |
| <h2 id="cachingmemoization"><a class="header" href="#cachingmemoization">Caching/Memoization</a></h2> |
| <p>Results of query invocations are "memoized" which means that the query context |
| will cache the result in an internal table and, when the query is invoked with |
| the same query key again, will return the result from the cache instead of |
| running the provider again.</p> |
| <p>This caching is crucial for making the query engine efficient. Without |
| memoization the system would still be sound (that is, it would yield the same |
| results) but the same computations would be done over and over again.</p> |
| <p>Memoization is one of the main reasons why query providers have to be pure |
| functions. If calling a provider function could yield different results for |
| each invocation (because it accesses some global mutable state) then we could |
| not memoize the result.</p> |
| <h2 id="input-data"><a class="header" href="#input-data">Input data</a></h2> |
| <p>When the query context is created, it is still empty: No queries have been |
| executed, no results are cached. But the context already provides access to |
| "input" data, i.e. pieces of immutable data that were computed before the |
| context was created and that queries can access to do their computations.</p> |
| <p>As of <!-- date-check --> January 2021, this input data consists mainly of |
| the HIR map, upstream crate metadata, and the command-line options the compiler |
| was invoked with; but in the future inputs will just consist of command-line |
| options and a list of source files -- the HIR map will itself be provided by a |
| query which processes these source files.</p> |
| <p>Without inputs, queries would live in a void without anything to compute their |
| result from (remember, query providers only have access to other queries and |
| the context but not any other outside state or information).</p> |
| <p>For a query provider, input data and results of other queries look exactly the |
| same: It just tells the context "give me the value of X". Because input data |
| is immutable, the provider can rely on it being the same across |
| different query invocations, just as is the case for query results.</p> |
| <h2 id="an-example-execution-trace-of-some-queries"><a class="header" href="#an-example-execution-trace-of-some-queries">An example execution trace of some queries</a></h2> |
| <p>How does this DAG of query invocations come into existence? At some point |
| the compiler driver will create the, as yet empty, query context. It will then, |
| from outside of the query system, invoke the queries it needs to perform its |
| task. This looks something like the following:</p> |
| <pre><code class="language-rust ignore">fn compile_crate() { |
| let cli_options = ...; |
| let hir_map = ...; |
| |
| // Create the query context `tcx` |
| let tcx = TyCtxt::new(cli_options, hir_map); |
| |
| // Do type checking by invoking the type check query |
| tcx.type_check_crate(); |
| }</code></pre> |
| <p>The <code>type_check_crate</code> query provider would look something like the following:</p> |
| <pre><code class="language-rust ignore">fn type_check_crate_provider(tcx, _key: ()) { |
| let list_of_hir_items = tcx.hir_map.list_of_items(); |
| |
| for item_def_id in list_of_hir_items { |
| tcx.type_check_item(item_def_id); |
| } |
| }</code></pre> |
| <p>We see that the <code>type_check_crate</code> query accesses input data |
| (<code>tcx.hir_map.list_of_items()</code>) and invokes other queries |
| (<code>type_check_item</code>). The <code>type_check_item</code> |
| invocations will themselves access input data and/or invoke other queries, |
| so that in the end the DAG of query invocations will be built up backwards |
| from the node that was initially executed:</p> |
| <pre><code class="language-ignore"> (2) (1) |
| list_of_all_hir_items <----------------------------- type_check_crate() |
| | |
| (5) (4) (3) | |
| Hir(foo) <--- type_of(foo) <--- type_check_item(foo) <-------+ |
| | | |
| +-----------------+ | |
| | | |
| (7) v (6) (8) | |
| Hir(bar) <--- type_of(bar) <--- type_check_item(bar) <-------+ |
| |
| // (x) denotes invocation order |
| </code></pre> |
| <p>We also see that often a query result can be read from the cache: |
| <code>type_of(bar)</code> was computed for <code>type_check_item(foo)</code> so when |
| <code>type_check_item(bar)</code> needs it, it is already in the cache.</p> |
| <p>Query results stay cached in the query context as long as the context lives. |
| So if the compiler driver invoked another query later on, the above graph |
| would still exist and already executed queries would not have to be re-done.</p> |
| <h2 id="cycles"><a class="header" href="#cycles">Cycles</a></h2> |
| <p>Earlier we stated that query invocations form a DAG. However, it would be easy |
| to form a cyclic graph by, for example, having a query provider like the |
| following:</p> |
| <pre><code class="language-rust ignore">fn cyclic_query_provider(tcx, key) -> u32 { |
| // Invoke the same query with the same key again |
| tcx.cyclic_query(key) |
| }</code></pre> |
| <p>Since query providers are regular functions, this would behave much as expected: |
| Evaluation would get stuck in an infinite recursion. A query like this would not |
| be very useful either. However, sometimes certain kinds of invalid user input |
| can result in queries being called in a cyclic way. The query engine includes |
| a check for cyclic invocations of queries with the same input arguments. |
| And, because cycles are an irrecoverable error, will abort execution with a |
| "cycle error" message that tries to be human readable.</p> |
| <p>At some point the compiler had a notion of "cycle recovery", that is, one could |
| "try" to execute a query and if it ended up causing a cycle, proceed in some |
| other fashion. However, this was later removed because it is not entirely |
| clear what the theoretical consequences of this are, especially regarding |
| incremental compilation.</p> |
| <h2 id="steal-queries"><a class="header" href="#steal-queries">"Steal" Queries</a></h2> |
| <p>Some queries have their result wrapped in a <code>Steal<T></code> struct. These queries |
| behave exactly the same as regular with one exception: Their result is expected |
| to be "stolen" out of the cache at some point, meaning some other part of the |
| program is taking ownership of it and the result cannot be accessed anymore.</p> |
| <p>This stealing mechanism exists purely as a performance optimization because some |
| result values are too costly to clone (e.g. the MIR of a function). It seems |
| like result stealing would violate the condition that query results must be |
| immutable (after all we are moving the result value out of the cache) but it is |
| OK as long as the mutation is not observable. This is achieved by two things:</p> |
| <ul> |
| <li>Before a result is stolen, we make sure to eagerly run all queries that |
| might ever need to read that result. This has to be done manually by calling |
| those queries.</li> |
| <li>Whenever a query tries to access a stolen result, we make an ICE |
| (Internal Compiler Error) so that such a condition cannot go unnoticed.</li> |
| </ul> |
| <p>This is not an ideal setup because of the manual intervention needed, so it |
| should be used sparingly and only when it is well known which queries might |
| access a given result. In practice, however, stealing has not turned out to be |
| much of a maintenance burden.</p> |
| <p>To summarize: "Steal queries" break some of the rules in a controlled way. |
| There are checks in place that make sure that nothing can go silently wrong.</p> |
| |
| </main> |
| |
| <nav class="nav-wrapper" aria-label="Page navigation"> |
| <!-- Mobile navigation buttons --> |
| <a rel="prev" href="../query.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> |
| <i class="fa fa-angle-left"></i> |
| </a> |
| |
| <a rel="next prefetch" href="../queries/incremental-compilation.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> |
| <i class="fa fa-angle-right"></i> |
| </a> |
| |
| <div style="clear: both"></div> |
| </nav> |
| </div> |
| </div> |
| |
| <nav class="nav-wide-wrapper" aria-label="Page navigation"> |
| <a rel="prev" href="../query.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> |
| <i class="fa fa-angle-left"></i> |
| </a> |
| |
| <a rel="next prefetch" href="../queries/incremental-compilation.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> |
| <i class="fa fa-angle-right"></i> |
| </a> |
| </nav> |
| |
| </div> |
| |
| |
| |
| |
| <script> |
| window.playground_copyable = true; |
| </script> |
| |
| |
| <script src="../elasticlunr.min.js"></script> |
| <script src="../mark.min.js"></script> |
| <script src="../searcher.js"></script> |
| |
| <script src="../clipboard.min.js"></script> |
| <script src="../highlight.js"></script> |
| <script src="../book.js"></script> |
| |
| <!-- Custom JS scripts --> |
| <script src="../mermaid.min.js"></script> |
| <script src="../mermaid-init.js"></script> |
| <script src="../pagetoc.js"></script> |
| |
| |
| |
| </div> |
| </body> |
| </html> |