<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Itplamen on Medium]]></title>
        <description><![CDATA[Stories by Itplamen on Medium]]></description>
        <link>https://medium.com/@itplamen?source=rss-01d871927e48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1ZaFSBJm297_vCg4sRfjkQ.jpeg</url>
            <title>Stories by Itplamen on Medium</title>
            <link>https://medium.com/@itplamen?source=rss-01d871927e48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:09:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itplamen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[JIT Compiler Lowering Explained: What Happens at Runtime (Part 2)]]></title>
            <link>https://levelup.gitconnected.com/lowering-what-happens-at-runtime-part-2-211e39d19c9d?source=rss-01d871927e48------2</link>
            <guid isPermaLink="false">https://medium.com/p/211e39d19c9d</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Itplamen]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 20:03:52 GMT</pubDate>
            <atom:updated>2026-06-10T13:35:08.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8GTl4JDDXs5PCsA7KVfoA.png" /></figure><h3>The Anatomy of Compiler Lowering Series’ Articles</h3><p><a href="https://levelup.gitconnected.com/lowering-what-happens-at-build-time-part-1-285494759a01">C# Compiler Lowering Explained: What Happens at Build Time (Part 1)</a></p><p><em>This series is based on official sources, compiler code exploration, runtime experimentation with decompiler tools, and real-world experience.</em></p><h3>Table of Contents</h3><ul><li><a href="#e535">From IL to Machine Code</a></li><li><a href="#7a18">What is a Just-In-Time Compiler</a></li><li><a href="#5d40">A Brief History of Just-In-Time</a><br>– <a href="#5e98">1952 — A-0 Compiler</a><br>– <a href="#c3db">1960 — LISP</a><br>– <a href="#d93c">1970 — FORTRAN</a><br>– <a href="#7037">1980 — Smalltalk</a><br>– <a href="#6b85">1990 — Java</a></li><li><a href="#9961">JIT Compiler Architecture</a><br>– <a href="#dc0b">Bytecode</a><br>– <a href="#b86a">IL Translation</a><br>– <a href="#a7d4">Static Single Assignment (SSA) Construction</a><br>– <a href="#8765">Data Flow Analysis</a><br>– <a href="#5d14">Optimizations</a><br>– <a href="#ea6e">Lowering</a><br>– <a href="#c41d">Code Generation</a></li><li><a href="#6a50">Conclusion: Why JIT Lowering Matters</a></li><li><a href="#08b0">References and Further Reading</a></li></ul><h3>From IL to Machine Code</h3><p>In <a href="https://levelup.gitconnected.com/lowering-what-happens-at-build-time-part-1-285494759a01?postPublishedType=repub">C# Compiler Lowering Explained: What Happens at Build Time (Part 1)</a>, we explored how high-level constructs are lowered into lower-level equivalents and compiled into Intermediate Language (IL). However, IL is still not what the CPU executes.</p><p>Before execution, IL must undergo additional transformations — this time at runtime. One such transformation is <strong>JIT lowering phase</strong>.</p><p>In Part 2, we will explore how runtime lowering differs fundamentally from its compile-time counterpart. But before diving in, it is important to understand what a JIT compiler is and how its internal architecture works.</p><h3>What is a Just-In-Time Compiler</h3><p>Just-In-Time (JIT) compilation is a runtime technique that translates platform-independent bytecode (such as .NET IL or Java bytecode) into native machine code just before execution.</p><p>Unlike ahead-of-time (AOT) compilation, JIT has access to runtime information, allowing it to generate code that is tailored to the current execution environment — including the specific CPU architecture and runtime behavior.</p><p>As <a href="https://cspages.ucalgary.ca/~aycock/">John Aycock from the University of Calgary</a> notes in his work <strong>A Brief History of Just-In-Time</strong>:</p><blockquote><em>Software systems have been using “just-in-time” compilation (JIT) techniques since the 1960s. Broadly, JIT compilation includes any translation performed dynamically, after a program has started execution.</em></blockquote><h3>A Brief History of Just-In-Time</h3><h4>1952 — A-0 Compiler</h4><p>Compilers have evolved significantly over time. One of the earliest examples is the <a href="https://www.computinghistory.org.uk/det/5487/Grace-Hopper-completes-the-A-0-Compiler/"><strong>A-0 compiler</strong></a> developed by Grace Hopper in 1952, often considered the first compiler. As she described:</p><blockquote><em>All I had to do was to write down a set of call numbers, let the computer find them on the tape, bring them over and do the additions. This was the first compiler.</em></blockquote><h4>1960 — LISP</h4><p>Later, in 1960, John McCarthy introduced LISP in his paper <a href="https://www.cs.tufts.edu/~nr/cs257/archive/john-mccarthy/recursive.pdf"><strong>Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I</strong></a>. While not describing JIT compilation directly, it introduced concepts around dynamic evaluation and runtime execution that influenced later runtime system design.</p><h4>1970 — FORTRAN</h4><p>In the 1970s, Hansen’s work on FORTRAN introduced the idea of identifying frequently executed code paths (hot spots) and optimizing them dynamically at runtime. Although primitive compared to modern JIT compilers, these early systems established a fundamental principle that still holds today: runtime information can enable more effective optimizations than static analysis alone.</p><h4>1980 — Smalltalk</h4><p>The Smalltalk systems of the 1980s introduced one of the first practical uses of JIT compilation. Deutsch and Schiffman developed a system that translated virtual machine code into native machine code at runtime, compiling methods lazily. This approach significantly improved performance and introduced key JIT concepts still used today, such as lazy compilation and code caching.</p><h4>1990 — Java</h4><p>In the late 1990s, JIT compilation was largely driven by the rise of Java. Early Java Virtual Machines (JVMs) relied heavily on interpretation, which resulted in poor performance. JIT compilation emerged as the key solution, translating bytecode into native machine code at runtime. However, it quickly became clear that simple translation was not enough — effective runtime optimization was essential for achieving good performance. This led to significant advancements in JIT design, including improved intermediate representations and optimization strategies.</p><h3>JIT Compiler Architecture</h3><p>A general structure of a JIT compiler is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4997PAfgAO8L9Uix9KJLQ.png" /><figcaption>JIT Compiler Architecture</figcaption></figure><p>At a high level, a JIT compiler takes platform-independent bytecode, produced by a front-end compiler (such as .NET Roslyn or javac), and translates it into native machine code at runtime.</p><h4>Bytecode</h4><p>Before this translation happens, the input bytecode must be parsed into a structured representation that the JIT compiler can reason about. Bytecode is easier to analyze than source code and is composed of low-level instructions that typically include opcodes and operands.</p><ul><li><strong>Opcodes (Operation Codes)</strong> — virtual instructions that specify operations, such as adding data, moving information, or jumping to a new memory location. For example: add (addition), ldloc (load local variable), stloc (store local variable).</li><li><strong>Operands </strong>— the values or registers that an opcode operates on, such as: constants 10, variables x, y, z and memory address 0xA1.</li></ul><p>When bytecode is inspected using disassembler tools, instructions are shown using <strong>mnemonics</strong>, which are human-readable representations of opcodes. For example, MUL (multiplication), and MOV (move data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qSpZ8JjfiyRV9GWuqr5iA.png" /><figcaption>From Source Code to Native Code</figcaption></figure><h4>IL Translation</h4><p>Also called the <strong>Importer</strong>, this phase is responsible for translating bytecode into an intermediate representation (IR) that is easier to analyze and optimize. During this phase, the JIT converts bytecode instructions into internal data structures such as:</p><ul><li><strong>IR Trees (IR GenTrees)</strong> — tree-based representations of expressions and operations used for analysis and optimization.</li><li><strong>Control Flow Graph (CFG)</strong> — a representation of all possible execution paths through a program. Instead of viewing code as a linear sequence of instructions, the JIT organizes it into a graph structure that captures branching and control flow. A CFG consists of:<br><strong>— Basic Blocks</strong> — sequence of instructions with a single entry and exit point and no internal control flow (jumps) in the middle (no if, goto or return)<br>— <strong>Control Edges</strong> — directed connections between basic blocks that represent possible execution paths.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nChLvlFGbEYIcmUw9cQJg.png" /><figcaption><strong>IR Trees (IR GenTrees) vs Control Flow Graph (CFG)</strong></figcaption></figure><h4>Static Single Assignment (SSA) Construction</h4><p>SSA is an intermediate representation used by most modern compilers, including RyuJIT, OpenJ9 JIT, GCC, LLVM, V8, HotSpot and the Go compiler. Introduced in the late 1980s, SSA is a fundamental technique in compiler design in which each variable is assigned <strong>exactly once</strong>, and every use of a variable refers to a single definition. This makes many optimizations simpler and efficient.</p><ul><li><strong>Variable renaming (single assignment)</strong></li></ul><p>Consider the following code:</p><pre>x = 10;<br>x = x - 5;<br>x = x * 3;<br>x = x + 9;<br>y = x</pre><p>The variable x is assigned multiple times. When the compiler reads y = x, it must trace back through previous assignments to determine the correct value.</p><p>In SSA form, each assignment creates a new version of the variable:</p><pre>x1 = 10;<br>x2 = x1 - 5;<br>x3 = x2 * 3;<br>x4 = x3 + 9;<br>y = x4</pre><p>Now each variable is defined <strong>exactly once</strong> and when the compiler reads y = x4, there is no ambiguity - it can directly reference the definition.</p><ul><li><strong>Insert φ (phi) nodes at merge points — </strong>SSA introduces additional complexity when dealing with branching code. Consider an if/else statement where each branch assigns a different value to the same variable:</li></ul><pre>int x;<br>if condition {<br>    x = 10;<br>} else {<br>    x = 20;<br>}<br><br>y = x;</pre><p>Here, x may have different values depending on execution path. When execution reaches y = x, the compiler must account for both possibilities.</p><p>In SSA form, this is handled using <strong>φ (phi) nodes</strong>, which merge values from different control flow paths:</p><pre>int x1, x2;<br>if condition {<br>    x1 = 10;<br>} else {<br>    x2 = 20;<br>}<br><br>int x3 = φ(x1, x2);<br>y = x3;</pre><p>The <strong>φ (phi)</strong> function selects a value based on the control flow path taken at runtime:</p><blockquote>If the “if” branch is taken, “x3” gets the value of “x1” <br>If the “else” branch is taken, “x3” gets the value of “x2”</blockquote><p><strong>Φ nodes</strong> are a conceptual construct used by the compiler to represent value merging.</p><h4>Data Flow Analysis</h4><p>Once SSA is constructed, the data-flow analysis phases executes in which the JIT analyzes how data moves through the program using the Control Flow Graph (CFG). The results of this analysis are later used by various optimization passes, such as removing redundant computations and reusing previous calculations. Data-flow analysis consists of several analyses:</p><ul><li><strong>Reaching Definitions Analysis</strong> — determines which assignments (definitions) of a variable can reach a given point in the program without being overwritten. It answers the question: <em>“Where did this variable’s value come from?”</em> The algorithm for computing reaching definitions is outlined below:<br> — <strong>Generate blocks</strong> — assign a unique label to each definition and group the code into basic blocks <strong><em>(B)</em></strong>.<br> — <strong>Identify <em>GEN(B)</em> and <em>KILL(B)</em> sets</strong> — for each basic block <strong><em>(B)</em></strong>, compute the <strong><em>GEN(B)</em></strong> set of definitions generated within block <strong><em>(B)</em></strong> that reach the end of <strong><em>(B)</em></strong> and are not overwritten within the block, and <strong><em>KILL(B)</em></strong> set of definitions from outside the block that are invalidated (overwritten) by the code inside the block <strong><em>(B)</em></strong>.<br> — <strong>Apply data-flow equations</strong> — using the computed <strong><em>GEN(B)</em></strong> and <strong><em>KILL(B)</em></strong> sets, determine the <strong><em>IN(B)</em></strong> and <strong><em>OUT(B)</em></strong> sets for each basic block, representing definitions that reach the <strong><em>entry/exit of (B)</em></strong>, respectively. JIT compilers use the following equations to calculate what information exits a block based on what entered it…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ButiByJECrtAHtUfEjO5dw.png" /><figcaption><strong>Data-flow equations</strong></figcaption></figure><ul><li>… The first equation computes the <strong>input state</strong> of a block by merging the <strong>OUT(B)</strong> sets of its predecessor blocks using the <strong>(⋃)</strong> union operator. This represents all definitions that may reach block <strong>(B)</strong> from any incoming control-flow path. The second equation computes the <strong>output state</strong> by taking the incoming definitions <strong>IN(B)</strong>, removing those that are overwritten <strong>KILL(B)</strong>, and adding newly generated definitions <strong>GEN(B)</strong>.<br><strong>— Annotate the Control Flow Graph (CFG)</strong> — once the data-flow equations reach a fixed point, the computed <strong><em>GEN(B)</em></strong>, <strong><em>KILL(B)</em></strong>, <strong><em>IN(B)</em></strong>, and <strong><em>OUT(B)</em></strong> sets are associated with each basic block in the CFG. These annotations describe how definitions propagate through the program and are used by subsequent optimization passes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko_25IknmTXuewBe7KaJ1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QbO0iplnhqZeWDuH8AmCg.png" /></figure><ul><li><strong>Live Variable Analysis</strong> — unlike <em>Reaching Definitions</em>, which focuses on assignments, <em>Live Variable Analysis</em> focuses on variable usage. It determines which variables may be used in the future at a given point in the program. This is a <strong>backward data-flow analysis</strong>, meaning it works from the end of the program toward the beginning. A variable is considered <strong>live</strong> at a program point if its current value may be used along some future execution path. If a variable is never used again, it is considered <strong>dead</strong> at that point. There are two kinds of variable liveness:<br> — <strong>Syntactic Liveness</strong> — a variable is considered live if there exists a path in the control-flow graph where it is used later in the program.<br> — <strong>Semantic Liveness</strong> — a variable is truly live if its value actually affects the program’s behavior.</li></ul><p><strong>x is both syntactically and semantically LIVE</strong></p><pre>int x = y * z;<br>return x;</pre><p><strong>x is DEAD</strong></p><pre>int x = 10;<br>return 0;</pre><p><strong>x is LIVE (conditionally)</strong></p><pre>int x = y * z;<br><br>if (flag)<br>    return x;<br><br>return 0;</pre><ul><li><strong>Available Expressions Analysis (AVAIL)</strong> — is a <strong>forward data-flow analysis</strong> that determines which expressions have already been computed and remain valid at different points in the program. In other words, an expression is considered available if the compiler can safely reuse its previously computed value instead of recalculating it. It is closely related to <strong>Common Subexpression Elimination (CSE)</strong> analysis in RyuJIT.</li></ul><p><strong>Available Expressions</strong></p><pre>int x = y * z;<br>return y * z</pre><p>After computing y * z in the first statement, and since neither y nor z has been modified, the expression remains valid at the next program point. Therefore, the available expression set includes avail(n) = {y * z}, allowing the JIT compiler to reuse the previously computed result instead of recalculating the expression.</p><p><strong>Unavailable Expressions</strong></p><pre>int a = 2;<br>int b = 3;<br><br>int c = a + b; <br>int x = c * 10;<br><br>a = 5;<br><br>int d = a + b;</pre><p>After computing a + b, the expression is initially available avail(n) = {a + b}. However, the assignment a = 5; modifies the value of a, which invalidates any previous computations. As a result, when the compiler reaches d = a + b; the expression a + b is no longer available and must be recomputed.</p><h4>Optimizations</h4><p>JIT compilers apply a wide range of optimizations to transform the intermediate representation into more efficient code. Examples include:</p><ul><li><strong>Local Optimization</strong> — focuses on improving a small region of code, typically within a single basic block. Common techniques include:<br> — <strong>Removing Redundant Instructions</strong> — redundant computations are identified and removed by reusing previously calculated results.<br> — <strong>Constant Folding</strong> — expressions are calculated at compile time and replaced with computed values by the JIT compiler. For example, instead of calculating the expression, the compiler can assign x = 10;</li></ul><pre>// High-level code<br>int x = 2 * 3 + 4;<br><br>// Before optimization IR<br>t1 = MUL(2, 3)<br>t2 = ADD(t1, 4)<br>x = t2<br><br>// After optimization IR<br>(MOV, 10, -, x) </pre><ul><li><strong>— Strength Reduction</strong> — expensive operations are replaced with equivalent but less expensive ones.</li></ul><pre>// High-level code -&gt; Before optimization<br>int y = pow(x, 2);  <br>int z = x * 32;<br><br>// Intermediate Representation (IR) -&gt; Before optimization<br>(CALL, pow, x, 2, y)<br>(MUL, x, 32, z)<br><br>// High-level code -&gt; After optimization<br>int y = x * x;<br>int z = x &lt;&lt; 5;<br><br>// Intermediate Representation (IR) -&gt; After optimization<br>(MUL, x, x, y)<br>(SHL, x, 5, z) -&gt; shifting (SHL) is faster than multiplication</pre><ul><li><strong>Global Optimization</strong> — operates across multiple basic blocks or the entire function (method). While more computationally expensive, these optimizations provide a better increase in performance. Common techniques include:<br> — <strong>Dead Code Elimination (DCE)</strong> — removes unreachable or unused code.</li></ul><p><em>Example: Unused Variable</em></p><pre>// High-level code<br>int a = 5;<br>int b = 10;<br>int c = a + b; // Never used<br>return a;<br><br>// Before optimization IR<br>(MOV, 5, -, a)<br>(MOV, 10, -, b)<br>(ADD, a, b, c)<br>(RET, a, -, -)<br><br>// After optimization IR<br>(MOV, 5, -, a)<br>(RET, a, -, -)</pre><p><em>Example: Unreached Code</em></p><pre>// High-level code<br>int x = 10;<br>if (false) {<br>    x = 20; // Never used<br>}<br>return x;<br><br>// Before optimization IR<br>(MOV, 10, -, x)<br>(JMP_FALSE, false, L1, -)<br>(MOV, 20, -, x)<br>L1:<br>(RET, x, -, -)<br><br>// After optimization IR<br>(MOV, 10, -, x)<br>(RET, x, -, -)</pre><ul><li><strong>Control Flow Optimization</strong> — focuses on improving how execution flows through a function. Instead of optimizing individual expressions, it operates on the program’s control structure. The goal is to reduce unnecessary branching, simplify execution paths, and improve overall execution efficiency.</li></ul><h4>Lowering</h4><p>Unlike front-end compilers (e.g. .NET Roslyn), where lowering is a hidden transformation phase between Semantic Analysis and Intermediate Code Generation, in JIT compilers such as <strong>RyuJIT (CLR)</strong>, lowering is a major architectural phase. At this stage, the compiler transforms the optimized high-level intermediate representation (IR) into a machine-oriented, low-level IR (LIR) that is much closer to actual CPU instructions.</p><p>Example:</p><pre>// High-level code<br>int y = (x * 3) + 10;<br><br>// Intermediate Representation (IR)<br>(ADD, (MUL, x, 3), 10, y)<br><br>// Lowering to x86 / x64<br>(LEA, x + x * 2 + 10, y)<br><br>// Lowering to ARM64<br>(MUL, x, 3, t1)<br>(ADD, t1, 10, y)</pre><p><strong>Lowering is architecture-aware</strong>. Although both versions compute the same result, the generated IR differs because lowering adapts the program to the target architecture.</p><p>On x86/x64, the architecture provides <strong>LEA (Load Effective Address)</strong> instruction, which can compute expressions like base + index * scale + offset. This allows the JIT compiler to replace x * 3 with x + x * 2, which can reduce instruction count and improve efficiency.</p><p>On the other hand, the ARM64 architecture follows a <strong>RISC (Reduced Instruction Set Computer)</strong> design, which means that there are no LEA-style complex instructions, thus arithmetic operations must be explicit using small, highly-optimized set of simple instructions.</p><h4>Code Generation</h4><p>This is the final phase of the JIT compilation pipeline, where the compiler transforms the intermediate representation into machine instructions that the CPU can execute. At this stage the IR has already been lowered into a machine-friendly form (LIR), and registers have been assigned. The JIT compiler performs several critical tasks:</p><ul><li><strong>Instruction Selection</strong> — the process of mapping low-level intermediate representation (LIR) operations to actual machine instructions supported by the target CPU.</li><li><strong>Register Allocation</strong> — this is the process of assigning program values to a limited set of physical CPU registers. It determines where each value lives at runtime — either in a register or, if necessary, in memory. Modern CPUs operate fastest on registers, but the number of available registers is limited …</li></ul><p><em>x64 has 16 registers<br>ARM64 has 31 registers (X0–X30)</em></p><p>… Programs often have far more “live” values than available registers, so the compiler must decide which values remain in registers and which are temporarily stored in memory (a process known as <strong>r<em>egister spilling</em></strong>).</p><pre>// High-level code<br>int x = 10;<br>int y = x + 1;<br>int z = x + 2;<br><br>// Before optimization IR -&gt; &quot;x&quot; is loaded twice from memory<br>(STORE, 10, -, x)<br>(LOAD, x, -, t1)<br>(ADD, t1, 1, y)<br>(LOAD, x, -, t2)<br>(ADD, t2, 2, z)<br><br>// After optimization IR -&gt; &quot;R1&quot; holds the value 10 and reused<br>(MOV, 10, -, R1)      <br>(ADD, R1, 1, y)<br>(ADD, R1, 2, z)</pre><p><strong>Spilling (When Registers Are Not Enough)</strong> — if there are more “live” values than available registers, some values must be stored in memory temporarily:</p><pre>(MOV, 10, -, R1)<br>(STORE, R1, -, [mem])   // spill to memory<br>...<br>(LOAD, [mem], -, R2)    // reload later</pre><p>This introduces overhead, which is why efficient register allocation is critical for performance.</p><ul><li><strong>Instruction Encoding</strong> — is the final task where selected machine instructions are translated into binary form (opcodes) that the CPU can execute.</li></ul><h3>Conclusion: Why JIT Lowering Matters</h3><p>If <a href="https://levelup.gitconnected.com/lowering-what-happens-at-build-time-part-1-285494759a01?postPublishedType=repub">C# Compiler Lowering Explained: What Happens at Build Time (Part 1)</a> of the series showed how compilers reshape our code at build time, Part 2 reveals what happens when that same process continues at runtime. This is where lowering becomes interesting.</p><p>Understanding JIT lowering changes how we think about runtime execution. Code is no longer static once compiled to IL — it is continuously analyzed, transformed, and optimized as it moves closer to the hardware. At the center of this process is the <strong>JIT lowering</strong> phase — the moment where the compiler stops reasoning in terms of expressions and semantics alone, and starts reasoning in terms of the machine itself.</p><p>Just-In-Time lowering is where abstraction meets reality, and where abstract program structure is reshaped by the constraints of a specific architecture.</p><h3>References and Further Reading</h3><ul><li><a href="https://jurakovic.github.io/runtime/">The Book of the Runtime</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/standard/managed-execution-process">Managed execution process, Microsoft Official Docs</a></li><li><a href="https://www.ibm.com/docs/en/sdk-java-technology/8?topic=reference-jit-compiler">The JIT compiler, IBM SDK, Java Technology Edition</a></li><li><a href="https://www.cs.tufts.edu/comp/150IPL/papers/aycock03jit.pdf">A Brief History of Just-In-Time, John Aycock, University of Calgary</a></li><li><a href="https://www.computinghistory.org.uk/">Centre for Computing History</a></li></ul><p><em>Originally published at </em><a href="https://dev.to/itplamen/lowering-what-happens-at-runtime-part-2-1m2h"><em>https://dev.to</em></a><em> on June 5, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=211e39d19c9d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/lowering-what-happens-at-runtime-part-2-211e39d19c9d">JIT Compiler Lowering Explained: What Happens at Runtime (Part 2)</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Compiler Lowering Explained: What Happens at Build Time (Part 1)]]></title>
            <link>https://levelup.gitconnected.com/lowering-what-happens-at-build-time-part-1-285494759a01?source=rss-01d871927e48------2</link>
            <guid isPermaLink="false">https://medium.com/p/285494759a01</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Itplamen]]></dc:creator>
            <pubDate>Fri, 05 Jun 2026 19:35:33 GMT</pubDate>
            <atom:updated>2026-06-26T19:13:01.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieq0gsGkfHrNi5b7e2-KeA.png" /></figure><h3>The Anatomy of Compiler Lowering Series’ Articles</h3><p><a href="https://levelup.gitconnected.com/lowering-what-happens-at-runtime-part-2-211e39d19c9d">JIT Compiler Lowering Explained: What Happens at Runtime (Part 2)</a></p><p><em>This series is based on official sources, compiler code exploration, runtime experimentation with decompiler tools, and real-world experience.</em></p><h3>Table of Contents</h3><ul><li><a href="#a97b">Lowering — The Hidden Layer of the Compiler</a></li><li><a href="#7677">Where Lowering Fits in the Compiler Pipeline</a></li><li><a href="#16bf">Lowering in the Roslyn Compiler Pipeline</a></li><li><a href="#b498">Lowering in Practice</a><br>– <a href="#94ee">Loop Lowering</a><br>– <a href="#9e20">Lambda Lowering</a><br>– <a href="#bd2a">Async State Machine</a><br>– <a href="#e03f">Code Review Concern</a></li><li><a href="#e183">Conclusion: Why Lowering Matters</a></li><li><a href="#f43c">References and Further Reading</a></li></ul><p>Have you ever heard that a for loop is faster than foreach, or that yield return has an architectural overhead because it hides a &quot;state machine&quot; underneath? In modern C#, these differences are often negligible. But over a decade ago, I remember a specific question from my first interview for a Junior Software Engineer - <em>&quot;Is string interpolation </em><em>$&quot;Hello, {name}&quot;; slower than string concatenation </em><em>&quot;Hello, &quot; + name;?</em></p><p>At the time, my honest answer was a confident <em>“I don’t know”</em> — but that question stuck with me. It was only later that I truly understood the answer.</p><h3>Lowering — The Hidden Layer of the Compiler</h3><p>Eric Lippert, who was a Principal Developer on the C# compiler team at Microsoft, explains this concept perfectly in his blog post <a href="https://ericlippert.com/2014/04/28/lowering-in-language-design-part-one/">Lowering in language design</a>:</p><blockquote><em>A common technique … is to have the compiler “lower” from high-level language features to low-level language features in the same language.</em></blockquote><p>I also really like this perspective from the 1998 classic book “ <a href="https://www.amazon.com/Building-Optimizing-Compiler-Bob-Morgan-ebook/dp/B008COCE9G">Building an Optimizing Compiler</a>”, by Robert Morgan:</p><blockquote><em>The instructions are lowered so that each operation in the flow graph represents a single instruction in the target machine. Complex instructions, such as subscripted array references, are replaced by the equivalent sequence of elementary machine instructions. Alternatively, multiple instructions may be folded into a single instruction when constants, rather than temporaries holding the constant value, can occur in instructions.</em></blockquote><p>In other words, instead of understanding every high-level language feature, the compiler takes these constructs — such as iterators (yield return), scoping blocks (using), or abstractions (LINQ and async/await) - and lowers them into an equivalent set of simpler, more fundamental instructions.</p><p>This allows different constructs to often perform similarly to their lower-level equivalents — although this ultimately depends on the specific scenario and how the code is transformed. In some cases, the compiler can also simplify or combine operations when values are known in advance, further reducing the amount of work needed at runtime.</p><p><strong>So, what should have been the answer to the question from my interview?</strong><br><em>Yes, at the time, string interpolation could be slower than string concatenation, because it often lowered to </em><em>String.Format, which introduced additional overhead.</em></p><h3>Where Lowering Fits in the Compiler Pipeline</h3><p>In the classic compiler structure described in <a href="https://www.amazon.com/Compilers-Principles-Techniques-Tools-2nd/dp/0321486811">Compilers: Principles, Techniques, and Tools</a>, known as “<strong><em>The Dragon Book</em></strong>”, you won’t see “lowering” as a separate phase. In fact, it is not mentioned at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3ZWXFs5weCP7ix2koFxHA.png" /><figcaption>Where Lowering Fits in the Compiler Pipeline</figcaption></figure><h4><strong>Lexical Analysis</strong></h4><p>Also called <strong>Tokenization </strong>or <strong>Scanning</strong> — is the first phase in compilation. The compiler reads the stream of characters (source code) and groups them into meaningful sequences called <strong>lexemes</strong>, which are then converted into <strong>tokens</strong> (such as keywords, identifiers, literals, and operators). Unnecessary whitespace and comments are typically ignored or removed.</p><p>Example of generated tokens after a lexical analysis:</p><p>int number = 5;</p><ul><li>int - keyword</li><li>number - identifier</li><li>= - operator</li><li>5 - literal</li><li>; - separator</li></ul><h4><strong>Syntax Analysis</strong></h4><p>Also called <strong>Parsing</strong>, is the compiler’s second phase. It ensures that the generated tokens follow the grammatical rules of the programming language.</p><p>&lt;declaration&gt; -&gt; &lt;datatype&gt; &lt;identifier&gt; = &lt;literal&gt;;</p><p>During this phase, the compiler builds a tree-like representation of the code — parse tree or syntax tree. If the structure is invalid, the parser generates errors such as “Unexpected token” or “Missing semicolon”.</p><ul><li><strong>Parse Tree</strong> — shows exactly how the code matches the grammar rules of the programming language. It represents the full syntactic structure including every detail, even those that are not essential for understanding the program.</li><li><strong>Syntax Tree </strong>— is a simplified representation of the code. It removes unnecessary syntactic details and focuses on the meaning of the program — the operations, relationships, and structure of the code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5gfjw7XDtWrrCXFMJs9Lg.png" /><figcaption>Parse Tree vs. Syntax Tree</figcaption></figure><h4><strong>Semantic Analysis</strong></h4><p>Ensures the statements are meaningful and do not violate semantic rules. Even syntactically correct code can be semantically invalid. The following checks are performed:</p><ul><li><strong>Type Checking</strong> — ensures variables and operations are used correctly. For example, assigning a string to an integer variable would result in an error.</li><li><strong>Variable Scope and Declaration</strong> — ensures variables are declared before use and accessed only within valid scopes.</li><li><strong>Function Check</strong> — ensures function calls match their definitions in terms of number and type of arguments.</li></ul><h4><strong>Intermediate Code Generation</strong></h4><p>Is the fourth phase, the source code is translated into an intermediate representation (IR), a lower-level, machine-like form that is not yet machine code but is easier to optimize and translate into different target architectures. This phase translates high-level language constructs into a lower-level intermediate representation that is closer to machine instructions, making it easier to optimize. In many compiler designs, the syntax tree can be considered a high-level form of intermediate representation.</p><h4><strong>Code Optimization</strong></h4><p>Once the IR is generated, the compiler enters the optimization phase where the code is transformed to improve performance and reduce resource usage. This is achieved through techniques such as instruction reordering, elimination of redundant calculations, and removal of “dead code” (code that is never executed).</p><h4><strong>Code Generation</strong></h4><p>The final phase of the compilation process, where the IR, which has already been lowered and optimized from high-level language constructs, is translated into machine code for the target architecture.</p><h4><strong>Symbol Table</strong></h4><p>Is a data structure used by the compiler to store information about code constructs. Each entry in the symbol table contains details about an identifier, such as its name (lexeme), type, memory location, and other relevant attributes. This structure allows the compiler to efficiently store, look up, and retrieve information about identifiers.</p><p>Did you notice the dashed box labeled “Lowering” in the diagram? There it is. It represents a conceptual transformation stage between Semantic Analysis and Intermediate Code Generation, where high-level language features are translated into simpler constructs. In compiler designs, lowering is not a strictly defined pipeline stage. Instead, it is a concept that can happen in multiple places: during transformations on the syntax tree, during intermediate representation (IR) generation, or across several compiler passes as part of a broader lowering and optimization pipeline.</p><h3>Lowering in the Roslyn Compiler Pipeline</h3><p>In the Roslyn compiler pipeline, lowering is a sequence of transformations applied after Binding and before IL Emission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsqhE87_sx8UcHLb3YzGmw.png" /><figcaption>Lowering in the Roslyn Compiler Pipeline</figcaption></figure><h4><strong>Parsing</strong></h4><p>The first phase consists of <em>tokenization</em> and <em>parsing</em>, where the source code is converted into a syntax tree.</p><h4><strong>Declaration</strong></h4><p>Similar to semantic analysis in a classical compiler structure, this phase analyzes source code and referenced metadata to identify all declared symbols, such as types, methods, variables, and builds a hierarchical symbol table.</p><h4><strong>Binding</strong></h4><p>The process of matching syntax (the code you wrote) to symbols (the identities discovered during the Declaration phase). The identifiers are assigned to symbols, effectively exposing the result of the compiler’s semantic analysis.</p><h4><strong>IL Emission</strong></h4><p>The final phase emits an assembly with all the information produced in the previous phases. This stage is exposed through the Emit API and generates Intermediate Language (IL) byte code.</p><p>In his book, Robert Morgan explains a fundamental truth about the process of rewriting high-level constructs such as yield return, using, and foreach into lower-level forms:</p><blockquote><em>During code lowering, where high-level operations are replaced by lower-level instructions, the compiler will generate expressions. The most common example is the lowering of subscript operations from a subscripted load/store operation to the computation of the address followed by an indirect load/store. The compiler generated the expressions, so the compiler must simplify them: The programmer cannot do it.</em></blockquote><p>Understanding this idea helps explain why this simple C# code:</p><pre>var i = 0;<br>var numbers = new [] {1, 2, 3};<br>var n = numbers[i];</pre><p>can be lowered into a more explicit, lower-level form:</p><pre>int num = 0;<br>int[] array = new int[3];<br>RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle));<br>int[] array2 = array;<br>int num2 = array2[num];</pre><p>In this transformation, the compiler introduced RuntimeHelpers.InitializeArray and an extra reference array2. The programmer did not write this, the compiler did.</p><p>One of the most surprising discoveries when exploring the Roslyn codebase is just how extensive lowering really is. Take a look at the compiler source code under <a href="https://github.com/dotnet/roslyn/tree/main/src/Compilers/CSharp/Portable/Lowering">/src/Compilers/CSharp/Portable/Lowering</a>, you’ll find dedicated rewriters for major language features:</p><ul><li><a href="https://github.com/dotnet/roslyn/tree/main/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter">AsyncRewriter</a></li><li><a href="https://github.com/dotnet/roslyn/tree/main/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter">IteratorRewriter</a></li><li><a href="https://github.com/dotnet/roslyn/tree/main/src/Compilers/CSharp/Portable/Lowering/LocalRewriter">LocalRewriter</a></li><li><a href="https://github.com/dotnet/roslyn/tree/main/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter">StateMachineRewriter</a></li></ul><p>At first glance, this aligns with what we expect — complex, high-level constructs like async/await, iterators, and lambdas require significant transformation. <strong>But the real insight comes one level deeper.</strong> Digging further into the LocalRewriter reveals something much more interesting. Lowering is not reserved for &quot;complex&quot; features - it is applied to many language constructs, including:</p><ul><li><a href="https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ForEachStatement.cs">foreach</a> loops</li><li><a href="https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_LockStatement.cs">lock</a> statements</li><li><a href="https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.cs">using</a> statements</li><li><a href="https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_WhileStatement.cs">while</a> loops</li><li><a href="https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TryStatement.cs">try-catch</a> statements</li><li>and many more.</li></ul><p><strong>What does this really mean?</strong><br><em>Lowering is not a special-case transformation — it is a </em><strong><em>core mechanism of the compiler.</em></strong></p><h3>Lowering in Practice</h3><p>Having already discussed compiler architecture and different phases, let’s take a look at some more interesting examples.</p><h4>Loop Lowering</h4><pre>var numbers = new [] {1, 2, 3};<br><br>foreach (var n in numbers)<br>{   <br>}<br><br>for (int i = 0; i &lt; numbers.Length; i++)<br>{   <br>}</pre><p>Both constructs are transformed into simpler while constructs:</p><pre>int[] array = new int[3];<br>RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle));<br>int[] array2 = array;<br>int[] array3 = array2;<br>int num = 0;<br>while (num &lt; array3.Length)<br>{<br>    int num2 = array3[num];<br>    num++;<br>}<br><br>int num3 = 0;<br>while (num3 &lt; array2.Length)<br>{<br>     num3++;<br>}</pre><p>However, for non-array collections, foreach is transformed into an enumerator-based pattern using GetEnumerator() and MoveNext():</p><pre>var list = new List&lt;int&gt; { 1, 2, 3 };<br><br>foreach (var item in list)<br>{<br>    Console.WriteLine(item);<br>}</pre><p>Is lowered to:</p><pre>List&lt;int&gt; list = new List&lt;int&gt;();<br>list.Add(1);<br>list.Add(2);<br>list.Add(3);<br>List&lt;int&gt; list2 = list;<br>List&lt;int&gt;.Enumerator enumerator = list2.GetEnumerator();<br>try<br>{<br>    while (enumerator.MoveNext())<br>    {<br>        int current = enumerator.Current;<br>        Console.WriteLine(current);<br>    }<br>}<br>finally<br>{<br>    ((IDisposable)enumerator).Dispose();<br>}</pre><h4>Lambda Lowering</h4><p>Consider the following code:</p><pre>var evens = numbers.Where(n =&gt; n % 2 == 0);</pre><p>The lambda expression is lowered into a compiler-generated class:</p><pre>[CompilerGenerated]<br>private sealed class &lt;&gt;c<br>{<br>     public static readonly &lt;&gt;c &lt;&gt;9 = new &lt;&gt;c();<br>     public static Func&lt;int, bool&gt; &lt;&gt;9__0_0;<br><br>     internal bool &lt;M&gt;b__0_0(int n)<br>     {<br>         return n % 2 == 0;<br>     }<br>}<br><br>public void Main()<br>{<br>    int[] source = array;<br>    IEnumerable&lt;int&gt; enumerable = Enumerable.Where(source, &lt;&gt;c.&lt;&gt;9__0_0 ?? (&lt;&gt;c.&lt;&gt;9__0_0 = new Func&lt;int, bool&gt;(&lt;&gt;c.&lt;&gt;9.&lt;M&gt;b__0_0)));<br>}</pre><h4>Iterator State Machine</h4><p>As mentioned earlier, yield return is lowered by the compiler into a state machine. But why? Because yield return does not execute like a normal method. It produces a value, pauses, and later resumes from the same point. To enable this, the compiler must preserve execution state across calls - resulting in a compiler-generated state machine.</p><p>So, this code:</p><pre>public IEnumerable&lt;int&gt; GetNumbers()<br>{<br>    yield return 1;<br>    yield return 2;<br>}</pre><p>is lowered into a much more complex compiler-generated structure:</p><pre>[CompilerGenerated]<br>private sealed class &lt;GetNumbers&gt;d__0 : IEnumerable&lt;int&gt;, IEnumerable, IEnumerator&lt;int&gt;, IEnumerator, IDisposable<br>{<br>    private int &lt;&gt;1__state;<br>    private int &lt;&gt;2__current;<br><br>    int IEnumerator&lt;int&gt;.Current<br>    {<br>        [DebuggerHidden]<br>        get<br>        {<br>            return &lt;&gt;2__current;<br>        }<br>    }<br><br>    object IEnumerator.Current<br>    {<br>        [DebuggerHidden]<br>        get<br>        {<br>            return &lt;&gt;2__current;<br>        }<br>    }<br><br>    private bool MoveNext()<br>    {<br>        switch (&lt;&gt;1__state)<br>        {<br>            default:<br>                return false;<br>            case 0:<br>                &lt;&gt;1__state = -1;<br>                &lt;&gt;2__current = 1;<br>                &lt;&gt;1__state = 1;<br>                return true;<br>            case 1:<br>                &lt;&gt;1__state = -1;<br>                &lt;&gt;2__current = 2;<br>                &lt;&gt;1__state = 2;<br>                return true;<br>            case 2:<br>                &lt;&gt;1__state = -1;<br>                return false;<br>        }<br>    }<br>}</pre><h4>Async State Machine</h4><p>A more dramatic example of lowering in modern C# is the async/await pattern. While we see a simple code block, the compiler sees a much more complex structure. As Robert Morgan notes:</p><blockquote><em>… the compiler translates these operations into the simpler arithmetic and memory references implied by the formula. In other words, the level of the flow graph is lowered by replacing higher-level operations by simpler instruction-level operations.</em></blockquote><p>In the case of asynchronous methods, this idea of lowering is taken further. The compiler does not simply produce a sequence of instructions — it transforms the method into a compiler-generated state machine.</p><p>For example, consider the following code:</p><pre>public class Program <br>{<br>    public async Task Main() <br>    {<br>        await DoSomething();<br>    }<br><br>    public Task DoSomething() <br>    {<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>The compiler rewrites it into a state machine that implements IAsyncStateMachine:</p><pre>[CompilerGenerated]<br>private sealed class &lt;Main&gt;d__0 : IAsyncStateMachine<br>{<br>    private TaskAwaiter &lt;&gt;u__1;<br>    public int &lt;&gt;1__state;<br>    public AsyncTaskMethodBuilder &lt;&gt;t__builder;<br><br>    [Nullable(0)]<br>    public Program &lt;&gt;4__this;<br><br>    private void MoveNext()<br>    {<br>        int num = &lt;&gt;1__state;<br><br>        try<br>        {<br>            TaskAwaiter awaiter;<br>            if (num != 0)<br>            {<br>                awaiter = &lt;&gt;4__this.DoSomething().GetAwaiter();<br><br>                if (!awaiter.IsCompleted)<br>                {<br>                    num = (&lt;&gt;1__state = 0);<br>                    &lt;&gt;u__1 = awaiter;<br>                    &lt;Main&gt;d__0 stateMachine = this;<br>                    &lt;&gt;t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);<br><br>                    return;<br>                }<br>            }<br>            else<br>            {<br>                awaiter = &lt;&gt;u__1;<br>                &lt;&gt;u__1 = default(TaskAwaiter);<br>                num = (&lt;&gt;1__state = -1);<br>            }<br><br>            awaiter.GetResult();<br>        }<br>        catch (Exception exception)<br>        {<br>            &lt;&gt;1__state = -2;<br>            &lt;&gt;t__builder.SetException(exception);<br>            return;<br>        }<br><br>        &lt;&gt;1__state = -2;<br>        &lt;&gt;t__builder.SetResult();<br>    }<br>}</pre><h4>Code Review Concern</h4><p>Theory is great, but the true power of understanding the compiler’s lowering becomes clear during a code review. While implementing a TransactionalExecutionWrapper that ensures all commands run within the same scope and exposes the current transaction, a valid concern was raised.</p><p><strong>The Code in Question</strong></p><pre>public class TransactionalExecutionWrapper<br>{<br>    private readonly IDbConnection _connection;<br><br>    public TransactionalExecutionWrapper(IDbConnection connection)<br>    {<br>        _connection = connection;<br>    }<br><br>    public IDbTransaction Transaction { get; private set; }<br><br>    public void Execute(Action  action)<br>    {<br>        using (Transaction = _connection.BeginTransaction())<br>        {<br>            try<br>            {<br>                action();<br>                Transaction.Commit();<br>            }<br>            catch (Exception)<br>            {<br>                Transaction.Rollback();<br>                throw;<br>            }<br>            finally<br>            {<br>                Transaction = null;<br>            }<br>        }   <br>    }<br>}</pre><p><strong>The Debate: To Null or Not to Null?</strong></p><blockquote><em>Concern: The </em><em>using statement is essentially a </em><em>try/finally block and ensures disposal at the end of the scope. If </em><em>Transaction = null, by the time the </em><em>using block reaches the </em><em>finally, it will be trying to call </em><em>null.Dispose(). The object won&#39;t be cleaned up!</em></blockquote><p>At first glance, this looks reasonable. However, this is where compiler lowering changes how we reason about the code.</p><p>When the compiler sees a using statement, it does not just copy-paste your variable into a finally block. It lowers the using statement by creating a hidden, local variable. In other words, the using statement is effectively rewritten into a form similar to:</p><pre>public class TransactionalExecutionWrapper<br>{<br>    private readonly IDbConnection _connection;<br><br>    [CompilerGenerated]<br>    [DebuggerBrowsable(DebuggerBrowsableState.Never)]<br>    private IDbTransaction &lt;Transaction&gt;k__BackingField;<br><br>    public IDbTransaction Transaction<br>    {<br>        [CompilerGenerated]<br>        get<br>        {<br>            return &lt;Transaction&gt;k__BackingField;<br>        }<br>        [CompilerGenerated]<br>        private set<br>        {<br>            &lt;Transaction&gt;k__BackingField = value;<br>        }<br>    }<br><br>    public TransactionalExecutionWrapper(IDbConnection connection)<br>    {<br>        _connection = connection;<br>    }<br><br>    public void Execute(Action action)<br>    {<br>        IDbTransaction dbTransaction2 = (Transaction = _connection.BeginTransaction());<br>        IDbTransaction dbTransaction3 = dbTransaction2;<br>        try<br>        {<br>            try<br>            {<br>                action();<br>                Transaction.Commit();<br>            }<br>            catch (Exception)<br>            {<br>                Transaction.Rollback();<br>                throw;<br>            }<br>            finally<br>            {<br>                Transaction = null;<br>            }<br>        }<br>        finally<br>        {<br>            if (dbTransaction3 != null)<br>            {<br>                dbTransaction3.Dispose();<br>            }<br>        }<br>    }<br>}</pre><p>This transformation demonstrates an important point:</p><ul><li>The compiler captures the initial transaction reference in a compiler-generated temporary local variable dbTransaction3</li><li>That local variable is used for disposal in the generated finally block.</li><li>The Transaction property is independent and can be modified without affecting disposal.</li></ul><p>So when this line executes:</p><pre>Transaction = null;</pre><p>it only affects the property value, not the compiler-generated local reference that will be disposed.</p><p><strong>What about Garbage Collection?<br></strong> It is important to separate <strong>disposal</strong> from <strong>garbage collection</strong>, as they are often confused. Setting Transaction = null; <strong>does not</strong> trigger garbage collection, nor does it free memory, nor does it dispose the object. <strong>It only removes one reference to the transaction object.</strong> After Dispose() executes, the object may become <strong>eligible for garbage collection</strong>, but the <strong>GC</strong> will only collect it later, when a garbage collection cycle occurs.</p><h3>Conclusion: Why Lowering Matters</h3><p>When we write code, we use high-level abstractions like using, await, or foreach to keep our logic clean. But underneath, there is the compiler - the &quot;Architect&quot; - rewrites these abstractions into simpler operations, introducing variables, restructuring control flow, and generating helper code.</p><p>Understanding lowering changes how developers think about code: no longer abstract intentions, but concrete operations that reveal how the code is transformed and executed. This insight turns performance tuning, resource management, and debugging from guesswork into more predictable engineering.</p><p>By understanding what the compiler produces and how the runtime executes it, developers gain a deeper mental model of their systems-writing code with greater confidence, clarity, and control.</p><p>In <a href="https://levelup.gitconnected.com/lowering-what-happens-at-runtime-part-2-211e39d19c9d?postPublishedType=repub">JIT Compiler Lowering Explained: What Happens at Runtime (Part 2)</a>, we will see that lowering is not restricted to build-time. It is a major architectural phase in runtime compilation (JIT compiler), where build-time transformations continue into execution, and the JIT compiler further lowers IL into machine-oriented representation that is ultimately translated into executable machine code.</p><h3>References and Further Reading</h3><ul><li><a href="https://www.amazon.com/Compilers-Principles-Techniques-Tools-2nd/dp/0321486811">Compilers: Principles, Techniques, and Tools</a>, known as “The Dragon Book”</li><li><a href="https://www.amazon.com/Building-Optimizing-Compiler-Bob-Morgan-ebook/dp/B008COCE9G">Building an Optimizing Compiler</a> by Robert Morgan</li><li><a href="https://github.com/dotnet/roslyn/tree/main/src/Compilers/CSharp/Portable/Lowering">Roslyn</a> source code</li><li><a href="https://ericlippert.com/2014/04/28/lowering-in-language-design-part-one/">Eric Lippert’s</a> blog</li><li><a href="https://www.cl.cam.ac.uk/teaching/1718/OptComp/notes.pdf">Optimising Compilers, University of Cambridge</a></li><li><a href="https://www.cs.cornell.edu/courses/cs4120/2021sp/notes.html?id=lowering">CS 4120: Introduction to Compilers (Spring 2021), Cornell University</a></li><li><a href="https://luctielen.com/posts/how-to-lower-an-ir/">How to lower an IR?</a></li></ul><p><em>Originally published at </em><a href="https://dev.to/itplamen/lowering-what-happens-at-build-time-part-1-4l9e"><em>https://dev.to</em></a><em> on June 5, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=285494759a01" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/lowering-what-happens-at-build-time-part-1-285494759a01">C# Compiler Lowering Explained: What Happens at Build Time (Part 1)</a> was originally published in <a href="https://levelup.gitconnected.com">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>