ClangIR and the Cost of MLIR
ClangIR (CIR) is an MLIR dialect between the AST and LLVM IR, and in October 2026 the clang area team accepted building it by default.
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
ClangIR (CIR) is an MLIR dialect between the AST and LLVM IR, and in October 2026 the clang area team accepted building it by default. CIR is built on MLIR because each step along the way was locally reasonable, and together the steps locked MLIR in. The costs (build time, binary size, MLIR API churn) land largely on Clang contributors who neither chose MLIR nor use CIR.
This post traces how CIR came to depend on MLIR, compares CIR with the IRs it cites as models, Rust's MIR and Swift's SIL, collects what the MLIR dependency costs, and uses an MLIR-free CIR as a thought experiment to separate the costs inherent to MLIR from those that can be reduced.
This post relies heavily on an LLM agent (Claude Code). It read the Discourse threads, GitHub PRs, slides, and the llvm-project, rustc, and Swift source trees, computed the build-closure and contributor numbers, and drafted the text, which I then edited. My part was steering, and some of what I added to its context:
Treat the numbers as checked but not peer-reviewed.
Classic Clang lowers the AST to LLVM IR in clang/lib/CodeGen. With -fclangir, clang/lib/CIR/CodeGen (CIRGen) emits CIR instead, a set of CIR passes runs, CIR is converted to MLIR's llvm dialect, and MLIR translates that to LLVM IR.
The in-tree roadmap, clang/docs/CIR/CodeDuplication.md, is about CodeGen. It plans to raise CIR to a higher level, move ABI details into later lowering passes, and "replace relevant parts of the existing implementation, piece by piece" with implementations shared by both code generators. Calling conventions are the first case (LLVMABI, plus an MLIR adapter that FIR can also use). The roadmap lists the next candidates: constant expression evaluation, complex multiplication and division, builtins, exception handling and C++ cleanups, inline assembly, and C++ ABI handling (vtables, virtual calls, constructor and destructor arguments, dynamic casts, base class addresses, type descriptors, array new and delete). Linkage, alignment, debug info, TBAA, sanitizers, and lifetime markers are spread through CodeGen and listed as harder to share. It also aims to run all classic CodeGen tests through the CIR path.
The area team's decision says "ClangIR is likely to reach the point where it becomes the replacement for the current CodeGen and CFG analysis." The same post promises that -DCLANG_ENABLE_CIR=Off "will still be a supported configuration for the forseeable future", and -fclangir stays off by default. On main, clang/CMakeLists.txt tests CLANG_ENABLE_CIR but declares no option() for it, so the flip is still pending.
A separate RFC, Add CIR testing to clang and MLIR CI (#227834), would build and test CIR in premerge for clang/ and mlir/ changes. nikic is weakly -1: if contributors have to fix CIR failures, "they also need to build and test CIR locally", so premerge testing and build-by-default "should go hand in hand". rengolin calls asking non-CIR developers to stub out CIR breakage "an unreasonable request" and suggests a different CI setup.
As for the compiler itself, the ClangIR progress report for September 2026 measures -fclangir against classic CodeGen: 1.32x the wall time on a typical file, 1.57x across the tree, 1.17x the memory, and 3% more code.
ClangIR started at Meta in October 2021. Bruno Cardoso Lopes and Nathan Lanza proposed it in RFC: An MLIR based Clang IR (CIR) in June 2022, and it moved to an LLVM incubator in August 2022 (timeline from the 2025 keynote). The primary goal was "improved diagnostics for modern C++"; the design had "grown out of implementing a lifetime analysis/checker pass"; optimization and lowering were "a secondary goal for now". Clang lacked a suitable IR: the AST is awkward for dataflow, LLVM IR is too low level, and the Clang CFG is discarded after analysis. The RFC's entire "Why MLIR?" section reads:
MLIR provides a solid and tested framework to build custom IR and run passes. Among several other capabilities, it's also in already in tree and used by Flang to build FIR.
Nobody in the thread argued for a bespoke IR; the closest was John McCall's aside that if MLIR needed in-tree dialects to be useful, "it would be better to just not use MLIR" and write the IR "from scratch on top of llvm::ilist". efriedma wrote "using MLIR to build it seems like the right approach" and objected to structured control flow instead. Gábor Horváth argued that the CFG suffices for lifetime analysis, and John McCall wanted a two-stage lowering like Swift's. Reid Kleckner asked for an agreed compile-time ceiling, "like +15-25%, before making this part of the default pipeline". -fclangir is still opt-in, and 1.32x/1.57x is already past that ceiling.
Lopes's later talks do not revisit the choice. The 2023 Developers' Meeting talk (video) describes CIR as "Implemented as an MLIR dialect for C/C++". Its pipeline diagram goes from CIRGen through CIR passes, including the lifetime checker, to LLVM lowering, with a dashed side path through SCF and Affine. The lifetime checker was real: the talk reports integration with clangd, clang-tidy, and an internal IDE, and "Successful detection of lifetime bug that caused a major internal outage". The same talk lists "Compile & execution time, binary size, memory usage" among the challenges. The project site gives today's rationale: MLIR enables "the development of passes and IR, rapid design iteration, and reuse of community-provided analyses and transformations". Apart from a few OpenMP passes, clang's CIR pipeline runs only CIR's own passes.
The lifetime checker never reached upstream CIR. Clang's lifetime-safety analysis (#142313, July 2025) is built on the CFG, and Horváth is among its authors.
In October 2023 Erich Keane (NVIDIA) posted RFC: Implementation of OpenACC 3.3 for offload in Clang. Flang lowers OpenACC through MLIR's acc dialect: "It is our intention to use that as well, so NVIDIA is beginning to participate in the CIR/MLIR effort". Clang shares more than the dialect with Flang. CIR and FIR implement the same acc type interfaces (CIROpenACCTypeInterfaces.cpp, FIROpenACCTypeInterfaces.cpp), and acc-to-GPU passes are landing in mlir/lib/Dialect/OpenACC/Transforms. Classic CodeGen has no OpenACC lowering (CodeGenFunction.h: "TODO OpenACC: Implement this"), so CIR plus acc is Clang's only OpenACC implementation.
Strictly, the requirement was MLIR's acc dialect, not CIR. Keane's fallback was "LLVM-IR based metadata to enable the translation to the OpenACC MLIR dialect", and the second fallback, "lowering as OMP does", gives up sharing with Flang. OpenMP has the same sharing benefit without the necessity: CIR emits omp ops, but classic CodeGen already lowers OpenMP.
By 2026 the motive had widened. Keane wrote that the goal is to "enable further advancement for our compiler stack … the way to allow those to integrate with C/C++/Clang is to have a dialect for it".
Lopes proposed upstreaming in January 2024, Lanza landed the scaffolding in April 2024, and NVIDIA's first upstream CIR commit (David Olsen) followed in November 2024. Today CIR is 120K lines (lib + include) on ODS, MLIR interfaces, and MLIR rewrite drivers, with ~230 ops and 1,269 test files, 868 of which check -emit-cir output in MLIR's textual format.
Readers might ask whether NVIDIA led the upstreaming. I counted commits touching clang/lib/CIR, both upstream and in the archived llvm/clangir incubator (excluding incubator commits that also exist upstream). Affiliation comes from email domains, GitHub profiles, and LinkedIn; a GitHub profile shows the current employer, not the employer at commit time.
Meta wrote the incubator: its share was 100% in 2021, 97% in 2022, about half in 2023–2024, and 11% in 2025. NVIDIA wrote 45–49% of upstream commits each year, so by volume NVIDIA led the upstreaming; by authorship of the RFC and the scaffolding, Meta did. Of the 260 upstream commits titled "upstream …", the explicit ports from the incubator, Amr Hesham wrote 37%, NVIDIA 31%, and unknown authors 31%. Most NVIDIA commits are new code written upstream. The maintainers are Andy Kaylor (NVIDIA), Bruno Cardoso Lopes (Meta), and Henrich Lauko (NVIDIA since August 2026, previously Trail of Bits and NextSilicon).
The stated long-term value is mixing dialects. From Lopes's SC24 talk (November 2024) on, the slides describe CIR as a way to "Move Clang onto the MLIR substrate" and "Use MLIR from C, C++ and extensions", and to "Mix CIR with downstream and custom dialects". The 2025 keynote with Andy Kaylor lists "Lower to other MLIR dialects" among CIR's uses, next to the lifetime checker, and has a slide titled "CIR Won't Always Go To LLVM IR", where CIR is consumed by MLIR to "Offload to GPU or other targets". clang/docs/CIR/CodeDuplication.md: "even now we generate the ACC (OpenACCC) [sic] dialect in combination with CIR, and when support for OpenMP and CUDA are added, similar mixing will occur". The area team's acceptance ratifies this direction. Every year of upstreaming raised the cost of switching, and the main funder's motive now depends on MLIR itself, not just on the original team's choice of framework.
CIR's case has been made in RFCs and talks since 2022. Here is what was promised and where it stands upstream in October 2026.
The functional milestones have been met, some on schedule. The MultiSource test suite passes, and the stage-2 self-build Keane predicted "within another month" in September works: all 4,744 translation units compile, and Lopes reports check-clang passing on the self-built clang. Shared AST queries moved to clang/lib/CodeGenUtils (#221001), ABI lowering has a shared library, and unimplemented features produce errorNYI diagnostics, as the 2024 RFC planned. What has not arrived is the reason the project was started, better diagnostics, and the optimizations that later took its place, along with the promises about the cost to everyone else.
The 2022 RFC named Rust's MIR and Swift's SIL as models. Both sit where CIR sits, between a type-checked AST and LLVM IR, so they show what such an IR is for. I read rustc at feaadeeaca7 and swiftlang/swift at 79e04dab01e.
Neither project kept two code generators for long. Swift's IRGen walked the AST until April 2013; SIL-based IRGen became the default on April 16 and the old path was removed the next day, more than a year before Swift 1.0. Rust ran MIR-based codegen beside the old AST-based translation for nine months; it became the default on 2016-08-01, and the old translation (12,585 lines) was deleted three weeks later. Borrow checking moved to MIR with the 2018 edition, and the AST borrow checker was deleted in September 2019. CIR has been upstream beside classic CodeGen since April 2024, and no document schedules removing either.
Parity is harder for C++ than it looks. Most of what MIR and SIL enforce has no required C++ counterpart: C++ has no borrow checker, reading an uninitialized variable is not a compile error, and there is no Sendable. The C++ analyses that do exist already live on the CFG, and lifetime safety went there in 2025. Templates are instantiated in Sema, so CIR never sees generic code, and the MIR and SIL win of optimizing generics before specialization does not exist. constexpr is evaluated in Sema before any IR exists; Rust can evaluate on MIR only because it builds MIR on demand during type checking. Clang issues its CFG-based warnings from Sema (Sema::PopFunctionScopeInfo calls AnalysisBasedWarnings::IssueWarnings), so they appear under -fsyntax-only, in clangd, and in clang-tidy. Swift shows the cost of the alternative: swiftc -typecheck builds no SIL, so definite-initialization and exclusivity errors appear only when compiling, and SourceKit runs the SIL diagnostic passes to show them in the editor. Moving Clang's warnings onto CIR would mean running CIRGen in every one of those tools.
MIR and SIL are worth their cost because they replace work: Swift and Rust have no other path from the type checker to a backend,
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。