blob: 201b953b24dbc39d172afcc9d7cf2c3251c9a1b6 [file] [log] [blame] [edit]
<!DOCTYPE HTML>
<html lang="en" class="light sidebar-visible" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Constraint propagation - 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/borrow_check/region_inference/constraint_propagation.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="constraint-propagation"><a class="header" href="#constraint-propagation">Constraint propagation</a></h1>
<p>The main work of the region inference is <strong>constraint propagation</strong>,
which is done in the <a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.propagate_constraints"><code>propagate_constraints</code></a> function. There are
three sorts of constraints that are used in NLL, and we'll explain how
<code>propagate_constraints</code> works by "layering" those sorts of constraints
on one at a time (each of them is fairly independent from the others):</p>
<ul>
<li>liveness constraints (<code>R live at E</code>), which arise from liveness;</li>
<li>outlives constraints (<code>R1: R2</code>), which arise from subtyping;</li>
<li><a href="./member_constraints.html">member constraints</a> (<code>member R_m of [R_c...]</code>), which arise from impl Trait.</li>
</ul>
<p>In this chapter, we'll explain the "heart" of constraint propagation,
covering both liveness and outlives constraints.</p>
<h2 id="notation-and-high-level-concepts"><a class="header" href="#notation-and-high-level-concepts">Notation and high-level concepts</a></h2>
<p>Conceptually, region inference is a "fixed-point" computation. It is
given some set of constraints <code>{C}</code> and it computes a set of values
<code>Values: R -&gt; {E}</code> that maps each region <code>R</code> to a set of elements
<code>{E}</code> (see <a href="../region_inference.html#region-variables">here</a> for more notes on region elements):</p>
<ul>
<li>Initially, each region is mapped to an empty set, so <code>Values(R) = {}</code> for all regions <code>R</code>.</li>
<li>Next, we process the constraints repeatedly until a fixed-point is reached:
<ul>
<li>For each constraint C:
<ul>
<li>Update <code>Values</code> as needed to satisfy the constraint</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>As a simple example, if we have a liveness constraint <code>R live at E</code>,
then we can apply <code>Values(R) = Values(R) union {E}</code> to make the
constraint be satisfied. Similarly, if we have an outlives constraints
<code>R1: R2</code>, we can apply <code>Values(R1) = Values(R1) union Values(R2)</code>.
(Member constraints are more complex and we discuss them <a href="./member_constraints.html">in this section</a>.)</p>
<p>In practice, however, we are a bit more clever. Instead of applying
the constraints in a loop, we can analyze the constraints and figure
out the correct order to apply them, so that we only have to apply
each constraint once in order to find the final result.</p>
<p>Similarly, in the implementation, the <code>Values</code> set is stored in the
<code>scc_values</code> field, but they are indexed not by a <em>region</em> but by a
<em>strongly connected component</em> (SCC). SCCs are an optimization that
avoids a lot of redundant storage and computation. They are explained
in the section on outlives constraints.</p>
<h2 id="liveness-constraints"><a class="header" href="#liveness-constraints">Liveness constraints</a></h2>
<p>A <strong>liveness constraint</strong> arises when some variable whose type
includes a region R is live at some <a href="../../appendix/glossary.html#point">point</a> P. This simply means that
the value of R must include the point P. Liveness constraints are
computed by the MIR type checker.</p>
<p>A liveness constraint <code>R live at E</code> is satisfied if <code>E</code> is a member of
<code>Values(R)</code>. So to "apply" such a constraint to <code>Values</code>, we just have
to compute <code>Values(R) = Values(R) union {E}</code>.</p>
<p>The liveness values are computed in the type-check and passed to the
region inference upon creation in the <code>liveness_constraints</code> argument.
These are not represented as individual constraints like <code>R live at E</code>
though; instead, we store a (sparse) bitset per region variable (of
type <a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/values/struct.LivenessValues.html"><code>LivenessValues</code></a>). This way we only need a single bit for each
liveness constraint.</p>
<p>One thing that is worth mentioning: All lifetime parameters are always
considered to be live over the entire function body. This is because
they correspond to some portion of the <em>caller's</em> execution, and that
execution clearly includes the time spent in this function, since the
caller is waiting for us to return.</p>
<h2 id="outlives-constraints"><a class="header" href="#outlives-constraints">Outlives constraints</a></h2>
<p>An outlives constraint <code>'a: 'b</code> indicates that the value of <code>'a</code> must
be a <strong>superset</strong> of the value of <code>'b</code>. That is, an outlives
constraint <code>R1: R2</code> is satisfied if <code>Values(R1)</code> is a superset of
<code>Values(R2)</code>. So to "apply" such a constraint to <code>Values</code>, we just
have to compute <code>Values(R1) = Values(R1) union Values(R2)</code>.</p>
<p>One observation that follows from this is that if you have <code>R1: R2</code>
and <code>R2: R1</code>, then <code>R1 = R2</code> must be true. Similarly, if you have:</p>
<pre><code class="language-txt">R1: R2
R2: R3
R3: R4
R4: R1
</code></pre>
<p>then <code>R1 = R2 = R3 = R4</code> follows. We take advantage of this to make things
much faster, as described shortly.</p>
<p>In the code, the set of outlives constraints is given to the region
inference context on creation in a parameter of type
<a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/constraints/struct.OutlivesConstraintSet.html"><code>OutlivesConstraintSet</code></a>. The constraint set is basically just a list of <code>'a: 'b</code> constraints.</p>
<h3 id="the-outlives-constraint-graph-and-sccs"><a class="header" href="#the-outlives-constraint-graph-and-sccs">The outlives constraint graph and SCCs</a></h3>
<p>In order to work more efficiently with outlives constraints, they are
<a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/constraints/struct.OutlivesConstraintSet.html#method.graph">converted into the form of a graph</a>, where the nodes of the
graph are region variables (<code>'a</code>, <code>'b</code>) and each constraint <code>'a: 'b</code>
induces an edge <code>'a -&gt; 'b</code>. This conversion happens in the
<a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.new"><code>RegionInferenceContext::new</code></a> function that creates the inference
context.</p>
<p>When using a graph representation, we can detect regions that must be equal
by looking for cycles. That is, if you have a constraint like</p>
<pre><code class="language-txt">'a: 'b
'b: 'c
'c: 'd
'd: 'a
</code></pre>
<p>then this will correspond to a cycle in the graph containing the
elements <code>'a...'d</code>.</p>
<p>Therefore, one of the first things that we do in propagating region
values is to compute the <strong>strongly connected components</strong> (SCCs) in
the constraint graph. The result is stored in the <a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#structfield.constraint_sccs"><code>constraint_sccs</code></a>
field. You can then easily find the SCC that a region <code>r</code> is a part of
by invoking <code>constraint_sccs.scc(r)</code>.</p>
<p>Working in terms of SCCs allows us to be more efficient: if we have a
set of regions <code>'a...'d</code> that are part of a single SCC, we don't have
to compute/store their values separately. We can just store one value
<strong>for the SCC</strong>, since they must all be equal.</p>
<p>If you look over the region inference code, you will see that a number
of fields are defined in terms of SCCs. For example, the
<a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#structfield.scc_values"><code>scc_values</code></a> field stores the values of each SCC. To get the value
of a specific region <code>'a</code> then, we first figure out the SCC that the
region is a part of, and then find the value of that SCC.</p>
<p>When we compute SCCs, we not only figure out which regions are a
member of each SCC, we also figure out the edges between them. So for example
consider this set of outlives constraints:</p>
<pre><code class="language-txt">'a: 'b
'b: 'a
'a: 'c
'c: 'd
'd: 'c
</code></pre>
<p>Here we have two SCCs: S0 contains <code>'a</code> and <code>'b</code>, and S1 contains <code>'c</code>
and <code>'d</code>. But these SCCs are not independent: because <code>'a: 'c</code>, that
means that <code>S0: S1</code> as well. That is -- the value of <code>S0</code> must be a
superset of the value of <code>S1</code>. One crucial thing is that this graph of
SCCs is always a DAG -- that is, it never has cycles. This is because
all the cycles have been removed to form the SCCs themselves.</p>
<h3 id="applying-liveness-constraints-to-sccs"><a class="header" href="#applying-liveness-constraints-to-sccs">Applying liveness constraints to SCCs</a></h3>
<p>The liveness constraints that come in from the type-checker are
expressed in terms of regions -- that is, we have a map like
<code>Liveness: R -&gt; {E}</code>. But we want our final result to be expressed
in terms of SCCs -- we can integrate these liveness constraints very
easily just by taking the union:</p>
<pre><code class="language-txt">for each region R:
let S be the SCC that contains R
Values(S) = Values(S) union Liveness(R)
</code></pre>
<p>In the region inferencer, this step is done in <a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.new"><code>RegionInferenceContext::new</code></a>.</p>
<h3 id="applying-outlives-constraints"><a class="header" href="#applying-outlives-constraints">Applying outlives constraints</a></h3>
<p>Once we have computed the DAG of SCCs, we use that to structure out
entire computation. If we have an edge <code>S1 -&gt; S2</code> between two SCCs,
that means that <code>Values(S1) &gt;= Values(S2)</code> must hold. So, to compute
the value of <code>S1</code>, we first compute the values of each successor <code>S2</code>.
Then we simply union all of those values together. To use a
quasi-iterator-like notation:</p>
<pre><code class="language-txt">Values(S1) =
s1.successors()
.map(|s2| Values(s2))
.union()
</code></pre>
<p>In the code, this work starts in the <a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.propagate_constraints"><code>propagate_constraints</code></a>
function, which iterates over all the SCCs. For each SCC <code>S1</code>, we
compute its value by first computing the value of its
successors. Since SCCs form a DAG, we don't have to be concerned about
cycles, though we do need to keep a set around to track whether we
have already processed a given SCC or not. For each successor <code>S2</code>, once
we have computed <code>S2</code>'s value, we can union those elements into the
value for <code>S1</code>. (Although we have to be careful in this process to
properly handle <a href="./placeholders_and_universes.html">higher-ranked
placeholders</a>. Note that the value
for <code>S1</code> already contains the liveness constraints, since they were
added in <a href="https://doc.rust-lang.org/nightly/nightly-rustc/rustc_borrowck/region_infer/struct.RegionInferenceContext.html#method.new"><code>RegionInferenceContext::new</code></a>.</p>
<p>Once that process is done, we now have the "minimal value" for <code>S1</code>,
taking into account all of the liveness and outlives
constraints. However, in order to complete the process, we must also
consider <a href="./member_constraints.html">member constraints</a>, which are described in <a href="./member_constraints.html">a later
section</a>.</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../../borrow_check/region_inference.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="../../borrow_check/region_inference/lifetime_parameters.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="../../borrow_check/region_inference.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="../../borrow_check/region_inference/lifetime_parameters.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>