Files
progcode/docs/rebuild-v2/raw/outbound/e93edd28366e266c.txt

1655 lines
34 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">
<title>The New CTFE Engine | The D Blog</title>
<meta name="description" content="The official blog for the D Programming Language.">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/d.min.js"></script>
<meta name="theme-color" content="#b03931">
<link type="application/atom+xml" rel="alternate" href="https://blog.dlang.org/feed.xml" title="The D Blog" />
<link rel="stylesheet" href="/assets/css/style.css">
<link rel="icon" href="/assets/images/favicon-192.png" sizes="192x192" />
<link rel="apple-touch-icon" href="/assets/images/apple-touch-icon.png" />
<link rel="icon" href="/assets/images/favicon-32.png" sizes="32x32" />
<meta name="msapplication-TileImage" content="/assets/images/favicon-270.png" />
<link rel="manifest" href="/manifest.json">
</head>
<body>
<div class="blog-container">
<header class="dlf-header">
<h1>The D Blog</h1>
<p style="color: #666; font-size: 1.1em; margin: 5px 0 0 0; border-bottom: none !important; padding-bottom: 0 !important;">
The official blog for the D Programming Language.
</p>
<nav class="nav-bar">
<ul>
<li><a href="https://dlang.org">D HOME</a></li>
<li><a href="https://forum.dlang.org/">D FORUMS</a></li>
<li><a href="https://dlang.org/donate.html">DONATE</a></li>
<li><a href="https://store.dlang.org/">SHOP</a></li>
</ul>
</nav>
</header>
<div class="main-grid">
<main class="article-col" style="">
<article class="post">
<header>
<h2 style="font-size: 2.6em; font-weight: bold; margin-bottom: 15px;">
The New CTFE Engine
</h2>
<p>
Apr 10, 2017 • StefanKoch
•
<a href="/search?q=Compilers+%26amp%3B+Tools" class="tag-link">#Compilers &amp; Tools</a>,
<a href="/search?q=Core+Team" class="tag-link">#Core Team</a>,
<a href="/search?q=Guest+Posts" class="tag-link">#Guest Posts</a>
</p>
</header>
<div class="post-content" style="line-height: 1.6; font-size: 1.1em; color: #222;">
<p><em>Stefan Koch is the maintainer of <a href="https://github.com/UplinkCoder/sqlite-d">sqlite-d</a>, a native D <a href="https://www.sqlite.org">sqlite</a> reader, and has contributed to projects like <a href="https://github.com/SDC-Developers/SDC">SDC</a> (the Stupid D Compiler) and <a href="http://vibed.org">vibe.d</a>. He was also responsible for a 10% performance improvement in D’s current CTFE implementation and is currently writing a new CTFE engine, the subject of this post.</em></p>
<hr />
<p>For the past nine months, I’ve been working on a project called NewCTFE, a reimplementation of the <a href="https://dlang.org/spec/function.html#interpretation">Compile-Time Function Evaluation (CTFE)</a> feature of the D compiler front-end. CTFE is considered one of the game-changing features of D.</p>
<p>As the name implies, CTFE allows certain functions to be evaluated by the compiler while it is compiling the source code in which the functions are implemented. As long as all arguments to a function are available at compile time and the function is pure (has no side effects), then the function qualifies for CTFE. The compiler will replace the function call with the result.</p>
<p>Since this is an integral part of the language, pure functions can be evaluated anywhere a compile-time constant may go. A simple example can be found in the <a href="https://dlang.org/phobos/index.html">standard library</a> module, <a href="https://dlang.org/phobos/std_uri.html"><code>std.uri</code></a>, where CTFE is used to compute a lookup table. It <a href="https://github.com/dlang/Phobos/blob/master/std/uri.d">looks like</a> this:</p>
<pre><code class="language-d">private immutable ubyte[128] uri_flags = // indexed by character
({
ubyte[128] uflags;
// Compile time initialize
uflags['#'] |= URI_Hash;
foreach (c; 'A' .. 'Z' + 1)
{
uflags[c] |= URI_Alpha;
uflags[c + 0x20] |= URI_Alpha; // lowercase letters
}
foreach (c; '0' .. '9' + 1) uflags[c] |= URI_Digit;
foreach (c; ";/?:@&amp;=+$,") uflags[c] |= URI_Reserved;
foreach (c; "-_.!~*'()") uflags[c] |= URI_Mark;
return uflags;
})();
</code></pre>
<p>Instead of populating the table with magic values, a simple expressive <a href="https://dlang.org/spec/expression.html#FunctionLiteral">function literal</a> is used. This is much easier to understand and debug than some opaque static array. The <code>({</code> starts a function-literal, the <code>})</code> closes it. The <code>()</code> at the end tells the compiler to immediately evoke that literal such that <code>uri_flags</code> becomes the result of the literal.</p>
<p>Functions are only evaluated at compile time if they need to be. <code>uri_flags</code> in the snippet above is declared in module scope. When a module-scope variable is initialized in this manner, the initializer must be available at compile time. In this case, since the initializer is a function literal, an attempt will be made to perform CTFE. This particular literal has no arguments and is pure, so the attempt succeeds.</p>
<p>For a more in-depth discussion of CTFE, see <a href="https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time">this article</a> by H. S. Teoh at the D Wiki.</p>
<p>Of course, the same technique can be applied to more complicated problems as well; <code>std.regex</code>, for example, can build a specialized automaton for a regex at compile time using CTFE. However, as soon as <a href="https://dlang.org/phobos/std_regex.html"><code>std.regex</code></a> is used with CTFE for non-trivial patterns, compile times can become extremely high (in D everything that takes longer than a second to compile is bloat-ware :)). Eventually, as patterns get more complex, the compiler will run out of memory and probably take the whole system down with it.</p>
<p>The blame for this can be laid at the feet of the current CTFE interpreter’s architecture. It’s an AST interpreter, which means that it interprets the AST while traversing it. To represent the result of interpreted expressions, it uses DMD’s AST node classes. This means that every expression encountered will allocate one or more AST nodes. Within a tight loop, the interpreter can easily generate over <code>100_000_000</code> nodes and eat a few gigabytes of RAM. That can exhaust memory quite quickly.</p>
<p><a href="https://issues.dlang.org/show_bug.cgi?id=12844">Issue 12844</a> complains about <code>std.regex</code> taking more than 16GB of RAM. For one pattern. Then there’s <a href="https://issues.dlang.org/show_bug.cgi?id=6498">issue 6498</a>, which executes a simple <code>0</code> to <code>10_000_000</code> while loop via CTFE and runs out of memory.</p>
<p>Simply freeing nodes doesn’t fix the problem; we don’t know which nodes to free and enabling the garbage collector makes the whole compiler brutally slow. Luckily there is another approach which doesn’t allocate for every expression encountered. It involves compiling the function to a virtual ISA (Instruction Set Architecture). This virtual ISA, also known as bytecode, is then given to a dedicated interpreter for that ISA (in the case in which a virtual ISA happens to be the same as the ISA of the host, we call it a JIT (Just in Time) interpreter).</p>
<p>The NewCTFE project concerns itself with implementing such a bytecode interpreter. Writing the actual interpreter (a CPU emulator for a virtual CPU/ISA) is reasonably simple. However, compiling code to a virtual ISA is exactly as much work as compiling it to a real ISA (though, a virtual ISA has the added benefit that it can be extended for customized needs, but that makes it harder to do JIT later). That’s why it took a month just to get the first simple examples running on the new CTFE engine, and why slightly more complicated ones still aren’t running even after 9 months of development. At the end of the post, you’ll find an approximate timeline of the work done so far.</p>
<p>I’ll be giving <a href="http://dconf.org/2017/talks/koch.html">a presentation</a> at <a href="http://dconf.org/2017/index.html">DConf 2017</a>, where I’ll discuss my experience implementing the engine and explain some of the technical details, particularly regarding the trade-offs and design choices I’ve made. The current estimation is that the 1.0 goals will not be met by then, but I’ll keep coding away until it’s done.</p>
<p>Those interested in keeping up with my progress can follow my status updates <a href="http://forum.dlang.org/thread/btqjnieachntljobzrho@forum.dlang.org">in the D forums</a>. At some point in the future, I will write another article on some of the technical details of the implementation. In the meantime, I hope the following listing does shed some light on how much work it is to implement NewCTFE :)</p>
<ul>
<li>
<p><strong>May 9th 2016</strong>
Announcement of the plan to improve CTFE.</p>
</li>
<li>
<p><strong>May 27th 2016</strong>
Announcement that work on the new engine has begun.</p>
</li>
<li>
<p><strong>May 28th 2016</strong>
Simple memory management change failed.</p>
</li>
<li>
<p><strong>June 3rd 2016</strong>
Decision to implement a bytecode interpreter.</p>
</li>
<li>
<p><strong>June 30th 2016</strong>
First code (taken from <a href="https://issues.dlang.org/show_bug.cgi?id=6498">issue 6498</a>) consisting of simple integer arithmetic runs.</p>
</li>
<li>
<p><strong>July 14th 2016</strong>
ASCII string indexing works.</p>
</li>
<li>
<p><strong>July 15th 2016</strong>
Initial <code>struct</code> support</p>
</li>
<li>
<p><strong>Sometime between July and August</strong>
First switches work.</p>
</li>
<li>
<p><strong>August 17th 2016</strong>
Support for the special cases <code>if(__ctfe)</code> and <code>if(!__ctfe)</code></p>
</li>
<li>
<p><strong>Sometime between August and September</strong>
Ternary expressions are supported</p>
</li>
<li>
<p><strong>September 08th 2016</strong>
First Phobos unit tests pass.</p>
</li>
<li>
<p><strong>September 25th 2016</strong>
Support for returning strings and ternary expressions.</p>
</li>
<li>
<p><strong>October 16th 2016</strong>
First (almost working) version of the LLVM backend.</p>
</li>
<li>
<p><strong>October 30th 2016</strong>
First failed attempts to support function calls.</p>
</li>
<li>
<p><strong>November 01st</strong>
DRuntime unit tests pass for the first time.</p>
</li>
<li>
<p><strong>November 10th 2016</strong>
Failed attempt to implement string concatenation.</p>
</li>
<li>
<p><strong>November 14th 2016</strong>
Array expansion, e.g. assignment to the <code>length</code> property, is supported.</p>
</li>
<li>
<p><strong>November 14th 2016</strong>
Assignment of array indexes is supported.</p>
</li>
<li>
<p><strong>November 18th 2016</strong>
Support for arrays as function parameters.</p>
</li>
<li>
<p><strong>November 19th 2016</strong>
Performance fixes.</p>
</li>
<li>
<p><strong>November 20th 2016</strong>
Fixing the broken <code>while(true) / for (;;)</code> loops; they can now be broken out of :)</p>
</li>
<li>
<p><strong>November 25th 2016</strong>
Fixes to <code>goto</code> and switch handling.</p>
</li>
<li>
<p><strong>November 29th 2016</strong>
Fixes to <code>continue</code> and <code>break</code> handling.</p>
</li>
<li>
<p><strong>November 30th 2016</strong>
Initial support for <code>assert</code></p>
</li>
<li>
<p><strong>December 02nd 2016</strong>
Bailout on <code>void</code>-initialized values (since they can lead to undefined behavior).</p>
</li>
<li>
<p><strong>December 03rd 2016</strong>
Initial support for returning <code>struct</code> literals.</p>
</li>
<li>
<p><strong>December 05th 2016</strong>
Performance fix to the bytecode generator.</p>
</li>
<li>
<p><strong>December 07th 2016</strong>
Fixes to <code>continue</code> and <code>break</code> in <code>for</code> statements (<code>continue</code> <em>must not skip</em> the increment step)</p>
</li>
<li>
<p><strong>December 08th 2016</strong>
Array literals with variables inside are now supported: <code>[1, n, 3]</code></p>
</li>
<li>
<p><strong>December 08th 2016</strong>
Fixed a bug in <code>switch</code> statements.</p>
</li>
<li>
<p><strong>December 10th 2016</strong>
Fixed a nasty evaluation order bug.</p>
</li>
<li>
<p><strong>December 13th 2016</strong>
Some progress on function calls.</p>
</li>
<li>
<p><strong>December 14th 2016</strong>
Initial support for strings in switches.</p>
</li>
<li>
<p><strong>December 15th 2016</strong>
Assignment of static arrays is now supported.</p>
</li>
<li>
<p><strong>December 17th 2016</strong>
Fixing <code>goto</code> statements (we were ignoring the last <code>goto</code> to any label :)).</p>
</li>
<li>
<p><strong>December 17th 2016</strong>
De-macrofied string-equals.</p>
</li>
<li>
<p><strong>December 20th 2016</strong>
Implement check to guard against dereferencing null pointers (yes… that one was oh so fun).</p>
</li>
<li>
<p><strong>December 22ed 2016</strong>
Initial support for pointers.</p>
</li>
<li>
<p><strong>December 25th 2016</strong>
<code>static immutable</code> variables can now be accessed (yes the result is recomputed … who cares).</p>
</li>
<li>
<p><strong>January 02nd 2017</strong>
First Function calls are supported !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p>
</li>
<li>
<p><strong>January 17th 2017</strong>
Recursive function calls work now :)</p>
</li>
<li>
<p><strong>January 23rd 2017</strong>
The <strong>interpret3.d</strong> unit-test passes.</p>
</li>
<li>
<p><strong>January 24th 2017</strong>
We are green on 64bit!</p>
</li>
<li>
<p><strong>January 25th 2017</strong>
Green on all platforms !!!!! (with blacklisting though)</p>
</li>
<li>
<p><strong>January 26th 2017</strong>
Fixed special case <code>cast(void*) size_t.max</code> (this one cannot go through the normal pointer support, which assumes that you have something valid to dereference).</p>
</li>
<li>
<p><strong>January 26th 2017</strong>
Member function calls are supported!</p>
</li>
<li>
<p><strong>January 31st 2017</strong>
Fixed a bug in <code>switch</code> handling.</p>
</li>
<li>
<p><strong>February 03rd 2017</strong>
Initial function pointer support.</p>
</li>
<li>
<p><strong>Rest of Feburary 2017</strong>
Wild goose chase for <a href="https://issues.dlang.org/show_bug.cgi?id=17220">issue #17220</a></p>
</li>
<li>
<p><strong>March 11th 2017</strong>
Initial support for slices.</p>
</li>
<li>
<p><strong>March 15th 2017</strong>
String slicing works.</p>
</li>
<li>
<p><strong>March 18th 2017</strong>
<code>$</code> in slice expressions is now supported.</p>
</li>
<li>
<p><strong>March 19th 2017</strong>
The concatenation operator (<code>c = a ~ b</code>) works.</p>
</li>
<li>
<p><strong>March 22ed 2017</strong>
Fixed a <code>switch</code> fallthrough bug.</p>
</li>
</ul>
</div>
<div class="related-posts" style="margin-top: 60px; padding-top: 30px; border-top: 2px solid #eee;">
<h3 style="font-size: 1.3em; margin-bottom: 20px;">Related Articles</h3>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
<div style="background: #fdfdfd; padding: 15px; border: 1px solid #eee; border-radius: 4px;">
<h4 style="margin: 0 0 10px 0; font-size: 1rem;">
<a href="/2026/08/10/language-plasticity-is-more-important-than-ever/" style="color: #b03931; text-decoration: none;">Language Plasticity is More Important Than Ever</a>
</h4>
<small style="color: #888;">Aug 10, 2026</small>
</div>
<div style="background: #fdfdfd; padding: 15px; border: 1px solid #eee; border-radius: 4px;">
<h4 style="margin: 0 0 10px 0; font-size: 1rem;">
<a href="/2026/07/19/abusing-overload-sets-to-create-ad-hoc-template-apis/" style="color: #b03931; text-decoration: none;">(Ab)using Overload Sets to Create Ad-Hoc Template APIs</a>
</h4>
<small style="color: #888;">Jul 19, 2026</small>
</div>
<div style="background: #fdfdfd; padding: 15px; border: 1px solid #eee; border-radius: 4px;">
<h4 style="margin: 0 0 10px 0; font-size: 1rem;">
<a href="/2026/06/07/teaching-an-ai-to-know-itself-building-a-local-llm-agent-in-d/" style="color: #b03931; text-decoration: none;">Teaching an AI to Know Itself: Building a Local LLM Agent in D</a>
</h4>
<small style="color: #888;">Jun 07, 2026</small>
</div>
</div>
</div>
</article>
</main>
<aside class="sidebar-col">
<div class="sidebar-section" style="margin-bottom: 30px;">
<form action="/search" method="get" style="display: flex; align-items: stretch; gap: 0; width: 100%; max-width: 280px; border: 1px solid #ccc; border-radius: 3px; overflow: hidden; margin-bottom: 15px;">
<input type="text" name="q" placeholder="Search..."
style="flex: 1; padding: 8px 10px; border: none; font-size: 0.95em; outline: none; color: #333;">
<button type="submit" style="padding: 0 12px; cursor: pointer; background: #f4f4f4; border: none; border-left: 1px solid #ccc; display: flex; align-items: center; justify-content: center;">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
</svg>
</button>
</form>
<div style="display: flex; flex-direction: column; gap: 12px; padding-left: 2px;">
<a href="/feed.xml" style="text-decoration: none; color: #b03931; font-weight: bold; font-size: 0.9em; display: flex; align-items: center; gap: 8px;">
<span style="background: #b03931; color: white; padding: 2px 6px; border-radius: 3px; font-size: 0.7em;">RSS</span> RSS FEED
</a>
<a href="https://x.com/d_programming" target="_blank" style="text-decoration: none; color: #666; font-size: 0.9em; display: inline-flex; align-items: center; gap: 8px;">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
Follow @D_Programming
</a>
</div>
</div>
<div class="sidebar-section" style="margin-bottom: 35px;">
<h4 style="font-size: 0.85em; letter-spacing: 1px; color: #888; border-bottom: 1px solid #eee; padding-bottom: 8px; margin-bottom: 15px; text-transform: uppercase;">Recent Articles</h4>
<ul style="list-style: none; padding: 0; margin: 0;">
<li style="margin-bottom: 14px;">
<a href="/2026/08/10/language-plasticity-is-more-important-than-ever/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
Language Plasticity is More Important Than Ever
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/2026/07/19/abusing-overload-sets-to-create-ad-hoc-template-apis/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
(Ab)using Overload Sets to Create Ad-Hoc Template APIs
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/2026/07/01/symmetry-autumn-of-code-report-importc-enhancements/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
Symmetry Autumn of Code Report: ImportC Enhancements
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/2026/06/07/teaching-an-ai-to-know-itself-building-a-local-llm-agent-in-d/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
Teaching an AI to Know Itself: Building a Local LLM Agent in D
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/2026/05/29/i-stopped-fighting-my-tools-and-built-a-game-engine-in-d/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
I Stopped Fighting My Tools and Built a Game Engine in D
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/2026/05/05/the-amazing-compile-time-state-machine/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
The Amazing Compile-Time Metaprogramming State Machine
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/2026/04/12/dip-1053-a-tale-of-tuples/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
DIP 1053 - A Tale of Tuples
</a>
</li>
<li style="margin-bottom: 14px;">
<a href="/archive/2024/02/22/dmd-compiler-as-a-library-a-call-to-arms/" style="color: #b03931; text-decoration: none; font-weight: 500; font-size: 0.95em; line-height: 1.3; display: block;">
DMD Compiler as a Library: A Call to Arms
</a>
</li>
</ul>
</div>
<div class="sidebar-section">
<div style="background: white; padding: 5px; border: 1px solid #eee; border-radius: 4px;" class="banner-shadow">
<a href="https://dlang.org/shop.html" style="display: block;">
<img src="/assets/images/do-it-in-d-banner.png" alt="Do it in D" style="width: 100%; display: block; border-radius: 2px;">
</a>
</div>
<p style="font-size: 0.85em; color: #666; margin: 15px 0 25px; line-height: 1.4;">
Support the D Language Foundation at the <a href="https://store.dlang.org/" style="color: #b03931; font-weight: bold; text-decoration: none;">DO IT IN D shop!</a>
</p>
<div style="text-align: center; border-top: 1px dashed #ddd; padding-top: 20px;">
<a href="https://dlang.org/donate.html">
<img src="/assets/images/donatenew.png" alt="Donate" style="max-width: 140px;">
</a>
<p style="font-size: 0.85em; color: #666; margin-top: 10px;">
Or make a <a href="https://dlang.org/donate.html" style="color: #b03931; font-weight: bold; text-decoration: none;">direct donation</a>.
</p>
</div>
</div>
</aside>
</div>
</div>
<script>
hljs.configure({ languages: ['d', 'cpp', 'python', 'bash', 'rust', 'julia', 'chapel', 'haskell'] });
hljs.highlightAll();
</script>
</body>
</html>