Repository navigation
LLVM IR backend - #221
Open
SamuelMarks wants to merge 10 commits into
Open
LLVM IR backend#221SamuelMarks wants to merge 10 commits into
SamuelMarks wants to merge 10 commits into
Conversation
… C++ tests Comprehensive implementation across all planned backend phases: - Test suite: Replaced Python test runners with C++ test executables (build config, driver flag, fuzz). - Architecture & Scoping: Implemented scoped local symbol table for alloca tracking, LValue/RValue semantics with implicit loads, and dynamic TargetTriple/DataLayout construction from EDG target macros. - Type System & Layout: Lowered primitives (bool, complex, float variants), empty struct padding, union lowering with bitcast access, bitfield packing/masking, and arrays/VLAs/pointer-to-member types. - Global State & Linkage: Added linkage mappings (weak, linkonce, comdat, TLS), recursive constant evaluation for static initializers, and dynamic initializers registered in llvm.global_ctors/dtors. - Control Flow & Statements: Implemented loops (while, do, for), switches, case/default handling, and jumps (break, continue, goto). - Expressions & Operations: Implemented GEP memory references (arrays, struct fields), function calls (direct, indirect, vararg, sret), full arithmetic/logic/comparisons, casts, ternary operators, and restrict/noalias qualification. - ABI & Attributes: Applied function and parameter attributes (NoReturn, inline hints, ByVal, SExt/ZExt), vtable/RTTI support.
…ted gotos, and test suite Add support for exception handling, GNU inline assembly, computed gotos, and extended constants in the LLVM IR generator, alongside automated tests and CI coverage: - Exception Handling: Added Itanium ABI personality routine setup (__gxx_personality_v0), landing pads, throw/rethrow runtime calls (__cxa_allocate_exception, __cxa_throw, __cxa_rethrow), catch blocks (__cxa_begin_catch, __cxa_end_catch), and invoke instructions for calls. - Inline Assembly: Implemented stmk_asm lowering to llvm::InlineAsm with operand constraint string translation, register clobber handling, and argument forwarding. - Computed Gotos: Implemented stmk_assigned_goto using llvm::IndirectBrInst dispatching to address-taken labels, with BlockAddress evaluation. - Constants: Added fp_to_hex_constant_string evaluation for float/double/long double (including inf/nan), UTF-16/UTF-32 string constant arrays, and label address constants. - Testing & CI: Added CTest configurations for EH, inline assembly, constants, and computed gotos, test coverage script, and GitHub Actions workflow.
… support, and verification Enhance LLVM backend code generation and validation with typeinfo integration, extended inline assembly handling, opaque pointer modernization, and verification: - Target Triple & Lifecycles: Configured target triple derivation across macOS, Windows, and Linux targets; ensured thorough state cleanup in llvm_gen_be_terminate. - Verifier Integration: Added function verification pass via llvm::verifyFunction with source position mapping on diagnostic failure. - Exception Handling & RTTI: Lowered typeinfo references using EDG mangled names (__cxa_throw typeinfo/dtor args) and added catch clause dispatch matching via llvm.eh.typeid.for. - Inline Assembly: Supported multiple outputs via struct returns, indirect memory operand constraints (*), and value extraction to lvalue destinations. - Type System & Opaque Pointers: Streamlined GEP and pointer bitcasts for opaque pointer support; added explicit float/complex kind mappings (bfloat16, fp16, fp80, fp128, etc.). - Testing & Coverage: Added multi-output inline asm test, lit test cases for for-loops and opaque pointers, orchestrator/verifier test targets, and coverage validation scripts.
…t layouts, and refine codegen Decouple LLVM backend configuration from C-generator assumptions, adopt runtime target configuration parameters, and resolve memory paging and terminator handling in the LLVM IR generator: - Target Configuration & Environment: Replaced static compile-time TARG_* macros with dynamic targ_* variables in DataLayout and type generation; decoupled BACK_END_IS_LLVM_GEN_BE from C-backend IL lowering and layout macros in front-end headers and lowering routines (host_envir.h, target.h, il_alloc.c, lower_c99.c, etc.). - Back-end Isolation: Guarded back_end() definition in c_gen_be.c and cp_gen_be.c when BACK_END_IS_LLVM_GEN_BE is active; upgraded C++ standard to C++17 in build configs. - Scope & Memory Management: Added get_scope_for_routine_definition with IL memory region paging (read_memory_region) to ensure routine definitions are available during code generation. - Control Flow & Terminators: Ensured conditional branch conditions are typed as i1; added terminator fallbacks to unreachable/ret void to guarantee block termination prior to module and function verification. - Inline Assembly & Expressions: Refactored assembly constraint string parsing, memory operand indirection, and register clobber lookups; corrected AST expression operator kinds and exception throw dynamic init handling. - Test Suite: Extended assembly, constant, and exception handling tests covering primitive and pointer catches, mixed asm outputs, float variants, and complex types.
Collaborator
|
Thanks, I've opened #245 for a central discussion of the topic of some kind of "native IR" back end for the EDG compiler project. |
…on, and pass pipeline Implement target calling convention ABIs (AAPCS64, SysV x86-64, Win64), DWARF debug metadata emission, machine code/assembly generation, optimization pipelines, and centralized error handling with test coverage: - Target Calling Conventions: Implemented ABI argument and return value classification for SysV x86-64, AAPCS64, and Win64 calling conventions, supporting direct, indirect, sret, coercion, and register attributes. - DWARF Debug Information: Added DIBuilder lifecycle management, compile unit setup, subprogram declarations, lexical block scopes, debug locations on instructions, and type metadata for primitives, pointers, and variables. - Code Generation & Emission: Integrated LLVM TargetMachine code generation to emit object files (.o) and assembly (.s); hooked into cpfe CLI flags (--gen_llvm_file_name, --llvm_opt_level, etc.). - Optimization Pipeline: Integrated LLVM new PassManager supporting optimization levels O0 through O3, Os, Oz, along with loop and SLP vectorization passes. - Error Handling & Modularization: Added centralized error subsystem with structured error contexts (llvm_gen_be_error_t); decoupled internal declarations into dedicated headers (llvm_gen_be_type.h, llvm_gen_be_expr.h, llvm_gen_be_const.h). - Test Infrastructure: Added unit tests for ABIs, DWARF metadata, pass pipelines, fault injection, and codegen, along with lit tests, GCC torture runner, and STL header compilation validation.
…ARF scopes, and update test suite Enforce uniform error propagation via [[nodiscard]] llvm_gen_be_error_t, annotate backend routines with noexcept, wire DWARF debug scopes and variable declarations into function lowering, and update backend tests: - Error Propagation & noexcept: Decorated llvm_gen_be_error_t with [[nodiscard]] at the type definition, eliminating redundant per-function attributes while guaranteeing mandatory error checking; annotated backend APIs with noexcept and migrated routines (get_llvm_type, build_data_layout, get_typeinfo_global, llvm_gen_be, back_end) to return status codes via out-parameters. - Diagnostic Context: Threaded persistent error context via be_state->err_context in code generation and target machine emission instead of localized stack buffers. - DWARF Debug Information: Integrated DI subprograms and lexical block scopes into routine lowering; added llvm.dbg.declare emission for routine parameters and non-static local variables with source position mapping. - Frontend Integration: Guarded back_end() in c_gen_be.h and cp_gen_be.h when BACK_END_IS_LLVM_GEN_BE is active, and hooked llvm_gen_be_cleanup into fe_wrapup.c. - Test Suite & Targets: Added C++17 and LLVM link dependencies to orchestrator and verifier test targets in CMake; updated fault injection and type unit tests to reflect out-parameter signatures; aligned lit test bitfield and datalayout expectations.
SamuelMarks
marked this pull request as ready for review
October 9, 2026 14:50
…ics, and revamp test suite
Modularize the C++ object model (vtables/RTTI), exception handling, inline
assembly, coroutines, and target ABI subsystems, implement atomic operations
and doc-coverage verification, and replace legacy test scripts with an exhaustive
C++ test suite:
- C++ Object Model & RTTI: Factored vtable emission and virtual method dispatch
into dedicated modules (llvm_gen_be_vtable.{h,cpp}) and RTTI descriptor generation
into llvm_gen_be_rtti.{h,cpp}, supporting Itanium and MSVC layouts with thunk generation.
- Exception Handling: Separated landing pads, cleanup unwinding, and personality
routines into llvm_gen_be_eh.{h,cpp} with full Itanium and MSVC funclet support.
- Target ABIs & Assembly: Added RISC-V 64-bit ABI classification (llvm_gen_be_abi_riscv64.{h,cpp}),
refined Win64 parameter passing, and modularized GNU inline assembly handling
into llvm_gen_be_asm.{h,cpp} with constraint parsing and asm-goto support.
- Modern C++ Features & Atomics: Implemented C++20 coroutine intrinsics and pass
lowering (llvm_gen_be_coro.{h,cpp}) and lowered C11/C++20 atomic builtins
(__atomic_thread_fence, __atomic_fetch_*, __atomic_compare_exchange).
- Code Quality & Documentation: Added check_doc_coverage.py and CMake target to
enforce 100% Doxygen coverage on backend types, fields, and functions; instrumented
coverage flags via EDG_LLVM_BE_COVERAGE.
- Test Infrastructure Revamp: Consolidated and replaced fragmented shell and unit tests
under tests/llvm_ir_backend_tests/ with dedicated, self-contained C++ unit test
executables (test_llvm_*) covering types, expressions, control flow, ABIs, EH,
inline asm, atomics, debug info, optimization pipelines, and differential fuzzing.
…MP, PGO/LTO pipelines, and expanded test coverage
Implement multi-target calling convention ABIs across eight additional architectures,
member pointer representation for Itanium and MSVC models, OpenMP lowering, PGO/LTO
compilation pipelines, and extensive test suites:
- Multi-Target Calling Conventions: Added complete ABI lowering implementations for
ARM32, LoongArch64, MIPS, PPC64, SystemZ (s390x), SPARC, WebAssembly, and x86-32
alongside classification improvements for AAPCS64, RISC-V 64, SysV x86-64, and Win64.
- Member Pointers: Implemented lowering for pointers to member functions and data
(llvm_gen_be_ptrmem.{h,cpp}) supporting Itanium dual-field representations and MSVC
single, multiple, and virtual inheritance layouts.
- OpenMP Runtime Lowering: Added OpenMP 5.x construct emission (llvm_gen_be_omp.{h,cpp})
interfacing with libomp/kmpc runtime primitives for parallel regions, worksharing loops,
critical sections, and atomic constructs.
- Driver, PGO, and LTO Pipelines: Modularized backend driver orchestration
(llvm_gen_be_driver.{h,cpp}) with CLI integration for Profile-Guided Optimization
(PGO generation/use), ThinLTO/LTO bitcode emission, and sanitizer instrumentation.
- Expression, Statement, & Model Lowering: Substantially expanded expression evaluation,
statement lowerings (switch jump tables, indirect branches, cleanup blocks), TLS
and static initializers, complex vtable/thunk layouts, and MSVC RTTI structures.
- Test Suite Expansion: Added unit tests for declarations, error handling, LTO,
modules, MSVC inline assembly, OpenMP, and PGO, accompanied by comprehensive lit
integration test suites and documentation coverage verification.
* Implement ABI, builtins, RTTI, EH, and dtor subsystems in GCC backend
Expand the native libgccjit backend (gcc_gen_be) with comprehensive language
feature lowering, runtime support, lexical scoping, and subsystem test coverage:
- ABI, Calling Conventions, and Attributes (src/gcc_gen_be_abi.[ch]):
- Implement gcc_gen_be_apply_function_attributes, gcc_gen_be_apply_struct_attributes,
and gcc_gen_be_apply_variable_attributes for packing, alignment, TLS, and linkage.
- Builtins and Intrinsics (src/gcc_gen_be_builtin.[ch]):
- Add gcc_gen_be_lower_builtin_call using libgccjit builtin function lookup.
- RTTI, VTables, and Thunks (src/gcc_gen_be_rtti.[ch]):
- Add vtable and VTT emission (gcc_gen_be_emit_vtable, gcc_gen_be_emit_vtt).
- Generate virtual method dispatch thunks (gcc_gen_be_emit_thunk).
- Implement dynamic_cast and typeid lowering with type_info descriptor emission.
- Exception Handling and RAII Destructors (src/gcc_gen_be_eh.[ch], src/gcc_gen_be_dtor.[ch]):
- Declare standard EH symbols (__cxa_throw, etc.) and lower throw expressions.
- Implement __cxa_atexit and __cxa_thread_atexit registration for global and TLS destructors.
- Lexical Scopes and Control Flow (src/gcc_gen_be_context.[ch], src/gcc_gen_be_stmt.[ch], src/gcc_gen_be_cache.[ch]):
- Introduce lexical scope push/pop stacks to support variable shadowing.
- Add stack save/restore helpers for VLA allocation.
- Expand cache types for local static guard variables and string constants.
- Dynamic Symbol Loader (src/gcc_gen_be_lib_loader.[ch]):
- Dynamically load modern libgccjit symbols for union constructors, bitcasts,
vector rvalues, builtin retrieval, and link sections.
- CLI and Driver Integration (src/cmd_line.[ch], src/gcc_gen_be_main.c):
- Register --gcc_gen_be and -c command-line options.
- Lower function scopes with lexical scope tracking and default terminator emission.
- Subsystem Unit Tests and Coverage (tests/gcc_be/, dev_tools/):
- Add subsystem test suites for ABI, builtins, debug, dtor, main, RTTI, and statements.
- Update CMake targets and end-to-end backend test fixtures.
- Add scripts for verifying backend test and documentation coverage.
- Remove deprecated dev-init.py.
* Implement subsystem unit tests, dynamic caching, and context stacks in GCC backend
Expand the native libgccjit backend (gcc_gen_be) with dynamic memory management,
subsystem diagnostics, modern libgccjit symbol loading, and a modular unit test suite:
- Context and Control-Flow Stacks (gcc_gen_be_context.[ch]):
- Replace static stack arrays with dynamically resizing stacks for break, continue,
switch exit, nested blocks, and RAII cleanup handlers.
- Introduce gcc_gen_be_push_block() / gcc_gen_be_pop_block() for nested scope tracking.
- Add thread-ownership verification via gcc_gen_be_check_thread_safety().
- Cache Resizing and Metrics (gcc_gen_be_cache.[ch]):
- Convert fixed-size hash buckets in be_cache_map to dynamically resizing tables.
- Track cache lookup metrics (hits, misses) retrievable via cache_get_metrics().
- Add GCC_GEN_BE_CACHE_SWITCH_CASE for jump target deduplication.
- Diagnostic Integration and Extended Errors (gcc_gen_be_error.[ch]):
- Introduce gcc_gen_be_report_diagnostic() bridging backend errors with EDG's
diagnostic counters and f_error.
- Add detailed error codes for EH, unresolved symbols, vtables, RTTI, asm constraints,
and DWARF emissions.
- Declarations and Expressions (gcc_gen_be_decl.[ch], gcc_gen_be_expr.[ch]):
- Separate global vs local variable lowering (gcc_gen_be_lower_global_variable_decl
and gcc_gen_be_lower_local_variable_decl).
- Add gcc_gen_be_lower_constant_rvalue() with aggregate initializer lowering.
- Dynamic Symbol Loader (gcc_gen_be_lib_loader.[ch]):
- Dynamically load optional modern libgccjit symbols (TLS models, vector types,
extended asm goto, function/variable attributes, struct/array constructors).
- Namespaces and Header Structuring:
- Standardize C++ namespaces (BEGIN_EDG_NAMESPACE / END_EDG_NAMESPACE) across
backend headers.
- Modular Unit Test Suite (tests/gcc_be/):
- Add standalone unit test suites for all backend subsystems: test_gcc_be_cache,
test_gcc_be_context, test_gcc_be_decl, test_gcc_be_errors, test_gcc_be_expr,
test_gcc_be_lib_loader, test_gcc_be_stmt, and test_gcc_be_type.
- Update tests/gcc_be/CMakeLists.txt to build and register subsystem tests.
- Tracking and Documentation:
- Add TODO_PLAN.md documenting architecture, test coverage mandates, and roadmap.
* Enforce universal error codes, percolation, and noexcept across GCC backend
Enforce strict error handling invariants, non-discardable return codes,
and noexcept specification across all GCC backend (gcc_gen_be) subsystems:
- Error infrastructure (gcc_gen_be_error.[ch]):
- Attach GCC_GEN_BE_NODISCARD directly to typedef enum gcc_gen_be_error_t
to ensure compiler-enforced return value checks across all backend APIs.
- Introduce GCC_GEN_BE_NOEXCEPT macro and add GCC_GEN_BE_ERROR_COMPILATION_FAILED.
- Refactor gcc_gen_be_error_string() to take an out-parameter and return
gcc_gen_be_error_t.
- Universal error code returns and pointer out-parameters:
- Update context getters/setters (gcc_gen_be_get_state, gcc_gen_be_get_context,
gcc_gen_be_set_context, gcc_gen_be_get_current_block, gcc_gen_be_set_current_block).
- Update helper constructors such as gcc_gen_be_get_global_ctor_block().
- Convert driver entry points gcc_gen_be() and back_end() to return
gcc_gen_be_error_t.
- Strict error propagation:
- Percolate all internal fallible operations (cache lookups/inserts/clears,
type and expression lowering, location queries, memory allocations) via
GCC_GEN_BE_CHECK().
- Eliminate ignored return values, unhandled fallback paths, and silent errors.
- Universal noexcept annotation:
- Decorate all backend function declarations and definitions across
gcc_gen_be_cache, gcc_gen_be_context, gcc_gen_be_decl, gcc_gen_be_error,
gcc_gen_be_expr, gcc_gen_be_lib_loader, gcc_gen_be_location,
gcc_gen_be_main, gcc_gen_be_stmt, and gcc_gen_be_type with GCC_GEN_BE_NOEXCEPT.
* Modularize GCC backend into dedicated subsystems and expand CLI options
Decompose monolithic gcc_gen_be.c and gcc_gen_be.h into modular,
decoupled backend subsystems to improve maintainability, testability,
and separation of concerns:
- gcc_gen_be_cache: hash map memoization for types, variables, functions,
and fields.
- gcc_gen_be_context: context lifecycle, option configuration, and active
basic block tracking.
- gcc_gen_be_decl: declaration lowering for globals, local variables, and
parameters.
- gcc_gen_be_error: centralized backend error handling and diagnostics.
- gcc_gen_be_expr: expression lowering for operators, calls, and accessors.
- gcc_gen_be_lib_loader: cross-platform dynamic loader for libgccjit.
- gcc_gen_be_location: mapping frontend source locations to JIT locations.
- gcc_gen_be_main: driver entry points and compilation invocation.
- gcc_gen_be_stmt: statement and CFG control-flow lowering.
- gcc_gen_be_type: type system lowering across scalar, aggregate, pointer,
and function types.
Additionally:
- Support GCC backend CLI optimization and debug flags in cmd_line.[ch]
(-O0..-O3, -Os, -Ofast, -g, -fPIC, -fPIE, dump flags).
- Update src/CMakeLists.txt for the new modular sources and coverage flags.
- Expand tests/gcc_be/ suite and modernize coverage verification script
to inspect all gcc_gen_be_*.c compilation units.
* GCC [libgccjit] backend (initial pass)
* Update LICENSE.txt for clarity []
…TBAA, and 100% coverage
Expand the LLVM IR backend with target architecture SIMD/system intrinsics,
OpenMP 5.x device offloading and directives, TBAA and fixed-point support,
multi-TU LTO linking, enhanced C++ ABI/EH/debug emission, and 100% test and
documentation coverage:
- Target Architecture Intrinsics (src/llvm_gen_be_intrinsics.{h,cpp}):
- Implement target-specific builtin lowering across x86/x86_64 (MMX, SSE,
AVX, AVX2, AVX-512, AMX, BMI, AES, SHA), ARM/AArch64 (NEON, SVE/SVE2,
CRC32, Crypto, barriers, system registers), RISC-V (RVV, Zbb/Zbc/Zbs),
PowerPC (Altivec/VSX), s390x, LoongArch (LSX/LASX), MIPS, SPARC, and
WebAssembly SIMD128.
- Expressions, Builtins, and Fixed-Point (src/llvm_gen_be_expr.{h,cpp}):
- Add lowering for C++ new/delete (with array cookies), C++17 fold
expressions (enk_fold), sizeof...(pack), ISO/IEC TR 18037 fixed-point
arithmetic intrinsics, builtin operations (bit_cast, offsetof, shuffle,
convertvector, source_location, uuidof), and padding masks for
__builtin_clear_padding.
- Types, TBAA, and Address Spaces (src/llvm_gen_be_type.{h,cpp}):
- Add LLVM TBAA type descriptors, access tags (!tbaa), and aggregate
struct metadata (!tbaa.struct), fixed-point scaling, and symbolic GPU/target
address-space mapping (nvptx64, amdgcn, spirv64).
- OpenMP 5.x Offloading and Directives (src/llvm_gen_be_omp.{h,cpp}):
- Implement map/to/from clause parsing, target data/enter/exit/update
mapper emission, GPU device module compilation (nvptx64/amdgcn), and
constructs for simd, teams distribute, taskloop, taskyield, flush,
ordered, master/masked, atomic, declare simd, and declare reduction.
- Declarations, VTables, RTTI, and EH (src/llvm_gen_be_decl.cpp,
src/llvm_gen_be_vtable.{h,cpp}, src/llvm_gen_be_rtti.{h,cpp},
src/llvm_gen_be_eh.{h,cpp}):
- Add unlowered C++ entity mangling (Itanium and MSVC), C++20 module
initializer guards, construction vtables, virtual/covariant and MSVC
vtordisp thunks, MSVC _TypeDescriptor/_ThrowInfo emission, chained
cleanup landing pads, SEH __leave, and /EHa async exception attributes.
- Inline Assembly, Coroutines, and Debug Info (src/llvm_gen_be_asm.{h,cpp},
src/llvm_gen_be_coro.{h,cpp}, src/llvm_gen_be_debug*.{h,cpp}):
- Add full MSVC __asm block parsing and GCC constraint canonicalization,
coroutine ramp/suspend/destroy lowering, and DWARF 5/CodeView metadata
for macros, imported entities, common blocks, fragments, and inlinedAt.
- Driver, CLI, and Build Integration (src/llvm_gen_be_driver.{h,cpp},
src/cmd_line.{h,cpp}, src/cfe.c, cmake/):
- Add native toolchain discovery, multi-TU ThinLTO/FullLTO linking, target
configuration synchronization, expanded CLI flags (-O0..-Oz, -g,
-gsplit-dwarf, -mcpu/-march/-mattr, -fPIC/-fPIE, -mcmodel, -fopenmp,
-fstack-protector*, -fsanitize=hwaddress/safe-stack/shadow-call-stack),
and CMake presets for debug, release, and coverage builds.
- Verification and Coverage (tests/, dev_tools/):
- Add test_llvm_target_intrinsics and check_llvm_be_coverage.py, and
expand unit, integration, and doc-coverage suites to verify 100%
function, line, region, branch, and Doxygen coverage.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Native LLVM IR & Machine Code Backend (
llvm_gen_be) for the EDG C/C++ Compiler Front EndExecutive Summary
This pull request introduces a complete, production-grade native LLVM IR and machine code generation backend (
llvm_gen_be) for the EDG C/C++ Front End (cpfe), transforming EDG from a pure parser/C-generating front end (c_gen_be/cp_gen_be) into a standalone, multi-target, optimizing C/C++ compiler and linker driver.Across 10 commits (
169 files changed, +62,404 / -506 lines), this branch implements:src/llvm_gen_be*.cpp) and 30 headers (src/llvm_gen_be*.h) totaling 29,036 lines of C++17, cleanly decoupled fromBACK_END_IS_C_GEN_BEandBACK_END_IS_CP_GEN_BE.x86_64), Microsoft Windows x64 (Win64+__vectorcall), ARM64 (AAPCS64, Darwinarm64, WindowsARM64EC), 32-bit x86 (cdecl,stdcall,fastcall,thiscall,regparm), 32-bit ARM (AAPCS/AAPCS-VFP), RISC-V (RV32/RV64lp64d), LoongArch64 (LP64D), MIPS (O32/N64), PowerPC (PPC32/PPC64ELFv1 & ELFv2), SystemZ (s390x), SPARC (V8/V9), and WebAssembly (wasm32/wasm64).VTT), construction vtables (_ZTC),this-adjusting and covariant return thunks, virtual base (vcall/vbase) offsets,vtordispthunks, Itanium RTTI (__fundamental_type_info,__class_type_info,__si_class_type_info,__vmi_class_type_info,__pointer_type_info,__pointer_to_member_type_info), and MSVC RTTI (_TypeDescriptor,_s__RTTICompleteObjectLocator,_s__RTTIClassHierarchyDescriptor,_s__RTTIBaseClassArray,_s__RTTIBaseClassDescriptor,_ThrowInfo,_CatchableTypeArray).__gxx_personality_v0,landingpad,__cxa_allocate_exception,__cxa_throw,__cxa_begin_catch,__cxa_end_catch,__cxa_rethrow,__cxa_call_unexpected,llvm.eh.typeid.for) and Windows Structured Exception Handling (__CxxFrameHandler3,__C_specific_handler,catchswitch,catchpad,catchret,cleanuppad,cleanupret,llvm.localescape,llvm.localrecover, outlined__finally/__exceptfilter funclets,__leave, and/EHaasynchronous exception attributes).MMX,SSE–SSE4.2,AVX,AVX2,AVX-512,AMX,BMI1/2,FMA,AES,SHA), ARM/AArch64 (NEON,SVE/SVE2,CRC32,Crypto, memory barriers,mrs/msrsystem registers), RISC-V (RVV,Zbb/Zbc/Zbs), PowerPC (Altivec/VSX), SystemZ (s390xvector), LoongArch (LSX/LASX), MIPS (MSA), SPARC (VIS), and WebAssembly (SIMD128).__kmpc_fork_call,__kmpc_fork_teams), static/dynamic/guided worksharing loops, reductions, tasks (__kmpc_omp_task_alloc,__kmpc_omp_taskloop), synchronization (critical,barrier,master/masked,ordered,flush,atomic), SIMD loop metadata (!llvm.loop.vectorize.enable), vector function ABI mangling (_ZGV...), andlibomptargetdevice offloading (__tgt_target_kernel,__tgt_target_data_begin_mapper,__tgt_target_data_end_mapper,__tgt_target_data_update_mapper) with embedded device image compilation (nvptx64-nvidia-cuda,amdgcn-amd-amdhsa,spirv64).llvm.coro.id,llvm.coro.size,llvm.coro.begin,llvm.coro.save,llvm.coro.suspend,llvm.coro.end,llvm.coro.free,llvm.coro.resume,llvm.coro.destroy,llvm.coro.promise,llvm.coro.noop) with promise allocation alignment/elision, and C++20 Module metadata (!edg.cpp20.module,!edg.cpp20.imports) with idempotent per-module dynamic initializer guards (__module_init_<name>)..dwo), & CodeView (.pdb) Debug Info: Fullllvm::DIBuilderintegration for compilation units, lexical block scopes, subprograms, local/parameterllvm.dbg.declare/llvm.dbg.value, composite types (classes, base inheritance, vtable holders, unions, bitfields, enums, templates),DIFlagBitField,createFragmentExpression(SROA),inlinedAtchains, DWARF v5 macro information (DIMacroFile,DIMacro), Fortran/C common blocks (DICommonBlock), andusingdeclarations/directives (DIImportedEntity).-O0/-O1/-O2/-O3/-Os/-Ozoptimization pipeline, Loop/SLP vectorization, AddressSanitizer (ASan), ThreadSanitizer (TSan), MemorySanitizer (MSan), HWAddressSanitizer (HWASan), UndefinedBehaviorSanitizer (UBSan),SafeStack,ShadowCallStack, Stack Protector (-fstack-protector*), Instrumentation PGO (-fprofile-generate/-fprofile-use), FullLTO and ThinLTO (ModuleSummaryIndex, combined index generation, and multi-TU in-process IR linking), and automated native toolchain/SDK discovery (ld.lld,ld64.lld,lld-link,clang++, CRT startup objects).typedef enum class [[nodiscard]] llvm_gen_be_error_t : int32_treturn status across all internal and public backend functions.noexceptenforcement and zero unhandled error paths (LLVM_GEN_BE_CHECK/LLVM_GEN_BE_CHECK_NOT_NULL/LLVM_GEN_BE_RETURN_ERROR).src/llvm_gen_be*.{h,cpp}files verified viallvm-cov(dev_tools/check_llvm_be_coverage.py).dev_tools/check_doc_coverage.py).Table of Contents
[[nodiscard]] noexceptContractasm/asm goto& MSVC__asm1. Architectural Overview & Subsystem Map
The backend is organized into 34 implementation files (
src/llvm_gen_be*.cpp) and 30 header files (src/llvm_gen_be*.h), coordinated byLLVMBackendState(src/llvm_gen_be_internal.h):llvm_gen_be.h,llvm_gen_be_internal.hllvm_gen_be.cppback_end(),llvm_gen_be(),DataLayoutsynthesis, target triple sync, CLI option dispatch, IL verification, multi-TU state reset & cleanupllvm_gen_be_error.hllvm_gen_be_error.cpp[[nodiscard]] llvm_gen_be_error_t,llvm_gen_be_error_context_t, source-coordinate extraction (conv_seq_to_file_and_line), EDGf_errorbridgellvm_gen_be_type.hllvm_gen_be_type.cppptr,!tbaa&!tbaa.struct, GPU address spacesllvm_gen_be_const.hllvm_gen_be_const.cppAPInt/APFloat), UTF-8/16/32 strings, aggregates, bitfield byte packing, relocatable address constants (abk_*),blockaddressllvm_gen_be_expr.hllvm_gen_be_expr.cppnew/delete, C11/C++20 atomics, fold expressions, TR 18037 fixed-point, UBSan traps, builtinsllvm_gen_be_intrinsics.hllvm_gen_be_intrinsics.cppSSE/AVX/AVX-512/AMX/BMI/AES/SHA), ARM/AArch64 (NEON/SVE/Crypto/barriers/sysregs), RISC-V, PPC, s390x, LoongArch, MIPS, SPARC, Wasm SIMD128internal.h)llvm_gen_be_stmt.cppif,for,while,do-while,switch(case ranges),goto, computedgoto(indirectbr), VLAs (stacksave/stackrestore), RAIIScopeCleanupStackinternal.h)llvm_gen_be_decl.cppllvm.global_ctors/dtors,.CRT$XCU),__cxa_guard_*, C++20 modules, unlowered manglingllvm_gen_be_vtable.hllvm_gen_be_vtable.cpp_ZTV), VTTs (_ZTT), construction vtables (_ZTC),this/covariant/virtual thunks, MSVCVFTable/VBTable&vtordispthunks, devirtualizationdynamic_castllvm_gen_be_rtti.hllvm_gen_be_rtti.cpp_ZTI/_ZTSdescriptors, MSVC_TypeDescriptor& hierarchy descriptors,dynamic_cast(__dynamic_cast/__RTDynamicCast/void*),typeid(__cxa_bad_typeid)llvm_gen_be_ptrmem.hllvm_gen_be_ptrmem.cpp{ptr, adj}&{offset}representations, MSVC single/multiple/virtual inheritance models, virtual/non-virtual dispatch, base-to-derived conversionsllvm_gen_be_eh.hllvm_gen_be_eh.cpplandingpad/resume/__cxa_*&noexcepttermination (__clang_call_terminate), Windows SEH (catchswitch/catchpad/cleanuppad), outlined filters/cleanups,/EHallvm_gen_be_coro.hllvm_gen_be_coro.cppco_await/co_yield/co_return,llvm.coro.*intrinsicsllvm_gen_be_asm.hllvm_gen_be_asm.cppasm/asm goto(callbr), constraint canonicalization, multi-output struct unpacking, memory (*m) & clobber normalization, full x86/x64 MSVC__asmparserllvm_gen_be_omp.hllvm_gen_be_omp.cppparallel,for,sections,single,master/masked,critical,barrier,task/taskloop/taskwait/taskyield,flush,ordered,atomic,simd,teams distribute, GPUtargetoffloadingllvm_gen_be_abi_*.h(12)llvm_gen_be_abi_*.cpp(12)sret/byval,va_list/va_argllvm_gen_be_debug.hllvm_gen_be_debug*.cpp(3)DIBuilder, compile units, lexical scopes,DILocation(inlinedAt), full type graph (DICompositeType, bitfields, templates), SROA fragments, DWARF v5 macros, CodeViewllvm_gen_be_opt.hllvm_gen_be_opt.cppPassBuilder(O0–Oz), Loop/SLP vectorizers,CoroEarly/CoroSplit/CoroElide/CoroCleanup, PGO instrumentation & use,ASan/TSan/MSan/HWASan/SafeStack/ShadowCallStackllvm_gen_be_codegen.hllvm_gen_be_codegen.cppTargetMachinecreation, CPU/feature/reloc/code-model config,.ll,.bc,.s,.oemission, ThinLTOModuleSummaryIndex, Split DWARF.dwollvm_gen_be_driver.hllvm_gen_be_driver.cpplld/ld/clang++), multi-TU ThinLTO/FullLTO combined index & in-process linking2. Error Handling &
[[nodiscard]] noexceptContractEvery function in the LLVM backend adheres to a strict, zero-exception error-propagation contract defined in
src/llvm_gen_be_error.h:[[nodiscard]]Error Enum (llvm_gen_be_error_t):[[nodiscard]]directly to thetypedef enum classguarantees that the compiler enforces return-value inspection on every backend call site without cluttering individual function declarations.noexcept& Out-Parameters:All backend functions are marked
noexceptand returnllvm_gen_be_error_t, passing computedllvm::Type*,llvm::Value*,llvm::Constant*, or metadata nodes via validated pointer out-parameters.llvm_gen_be_error_context_t):Captures
error_code,file_name,line_number,column_number, EDGseq_number, and a 512-byte formatted diagnostic message viallvm_gen_be_format_diagnostic(resolving EDGa_source_positioncoordinates viaconv_seq_to_file_and_line) and bridges directly to the EDG front-end diagnostic output viallvm_gen_be_report_to_edg_fe.3. Deep Dive by Subsystem
3.1 Type System, DataLayout, TBAA, & Address Spaces (
llvm_gen_be_type.{h,cpp})build_data_layout): Queries EDG runtime target configuration variables (targ_little_endian,targ_sizeof_pointer,targ_alignof_pointer,targ_sizeof_short,targ_sizeof_int,targ_sizeof_long,targ_sizeof_long_long,targ_sizeof_float,targ_sizeof_double,targ_sizeof_long_double,targ_Right_Shift_Is_Arithmetic, etc.) rather than static compile-time macros, emitting valid LLVM data layout strings (e/E,m:e/m:o/m:w,p:64:64,i1:8:8-i8:8:8-...,f80:128:128,n8:16:32:64,S128).an_integer_kindvariants (ik_charthroughik_int128and C23_BitInt(N)arbitrary bit-width integersiN) and alla_float_kindvariants (fk_float->float,fk_double->double,fk_long_double->x86_fp80/fp128/ppc_fp128/doublebased on target layout and size,fk_float80->x86_fp80,fk_float128->fp128,fk_fp16->half,fk_bfloat16->bfloat).tk_complexlowers to two-element homogeneous structs{ T, T }.tk_vectorlowers tollvm::FixedVectorType::get(elem_ty, num_elems)orllvm::ScalableVectorTypefor SVE/RVV scalable vectors.tk_fixed_point(ISO/IEC TR 18037_Fract/_Accum, signed/unsigned,short/default/long, saturating/non-saturating) lowers to the underlying scaled integer width with exact fractional bit-shift metadata (llvm_get_fixed_point_scale).tk_struct/tk_classpre-registers an opaqueStructTypeinbe_state->type_cachebefore lowering field types to break recursive self-referential struct cycles.[N x i8]padding arrays between fields at non-contiguous byte offsets, packs adjacent bitfields into storage units (i8,i16,i32,i64), and lowers empty C++ classes (size == 1, no fields) to{ i8 }.#pragma packand__attribute__((packed))by emitting packedllvm::StructTypelayouts when field offsets violate natural alignment.tk_unionselects the largest/most-aligned member and appends tail padding[pad x i8]to match the total EDG union size.llvm::PointerType::get(ctx, addr_space)).llvm_resolve_target_address_spacemaps OpenCL/CUDA/HIP/SYCL/target named address spaces (__global,__local/__shared,__constant,__private,__generic,__gs/seg_gs,__fs/seg_fs) to target-specific LLVM address space numbers fornvptx64,amdgcn,spirv64, andx86_64.llvm_get_tbaa_type_nodeconstructs a rooted TBAA hierarchy ("Simple C/C++ TBAA"->"omnipotent char"(i8) -> scalar/enum/pointer/struct type descriptors).llvm_get_tbaa_access_tagandllvm_attach_tbaa_metadataattach!tbaaaccess tags to loads/stores, whilellvm_get_tbaa_struct_metadatagenerates!tbaa.structbyte-offset/size/tag triples for aggregatellvm.memcpyoperations.3.2 Constant Evaluation & Bitfield Packing (
llvm_gen_be_const.{h,cpp})ck_integer: Arbitrary-precision conversion from EDGan_integer_value(int_constant_value/uns_constant_valueor hex string fallback) tollvm::APIntandllvm::ConstantInt.ck_float: Exact bit-accurate IEEE-754 conversion viafp_to_hex_constant_string/APFloathandlingNaN(quiet/signaling),+Inf,-Inf, subnormals,half,bfloat,float,double,x86_fp80,fp128, andppc_fp128.ck_string: Supports narrow (char/ UTF-8),char16_t(uint16_tarray),char32_t(uint32_tarray), andwchar_t(16-bit on Windows, 32-bit on Unix) string literals with global constant deduplication inbe_state->string_literal_cache.ck_aggregate: Walksfirst_constantinitializer chains alongsidetk_struct/tk_classfields, packing adjacent bitfield constants viallvm_pack_constant_bitfield_bytes(handling both little-endian and big-endian bit offsets and multi-byte spans), synthesizing zero-padding[N x i8]arrays for gaps, and handling[N x T]array repeat/tail zero-initialization (ConstantAggregateZero).tk_unionconstants, wraps initialized active fields into an anonymous struct constant with tail[pad x i8]zero bytes when the active member is smaller than the union container.ck_address):abk_routine(function addresses),abk_variable(global/static variable addresses),abk_constant(pool constants),abk_string(deduplicated.strglobals),abk_temporary(deduplicated.tmp.constglobals inbe_state->temporary_constant_cache),abk_label(llvm::BlockAddress::getfor computed gotos), andabk_param_ref(constexpr parameter slot lookups).i8getGetElementPtrexpressions.3.3 Expressions, Casts, Atomics, Fixed-Point, & Builtins (
llvm_gen_be_expr.{h,cpp})llvm_lower_lvalue/llvm_lower_expression):llvm_lower_lvalueresolves addresses forenk_variable,enk_field(struct GEP + union bitcast),enk_deref,enk_array_sub,enk_operation(eok_indirect,eok_points_to,eok_dot_field,eok_Subscript,eok_comma,eok_question,eok_assign, prefix++/--,eok_lvalue_cast,eok_ref_cast,eok_base_cast,eok_derived_cast,eok_pm_field,eok_points_to_field),enk_temp_init, andenk_constant.llvm_lower_expressionevaluates all 100+an_expr_operator_kind(eok_*) andan_expr_node_kind(enk_*) variants, including short-circuiting&&(eok_land),||(eok_lor), and ternary? :(eok_question) with properPHInode merging and booleani1conversions.lshr+ mask +shl/ashrsign extension (for signed bitfields), and updates bitfields via read-modify-write masking ((old & ~(mask << shift)) | ((val & mask) << shift)), including compound assignments (+=,|=, etc.) and pre/post increment/decrement._Complex/std::complex):(ac - bd) + i(ad + bc)), division (((ac + bd)/(c^2 + d^2)) + i((bc - ad)/(c^2 + d^2))), negation, conjugation (eok_conj), real/imag projection (eok_real_part/eok_imag_part), equality/inequality, and scalar-to-complex / complex-to-complex conversions.llvm.sadd.sat/llvm.uadd.sat), subtraction (llvm.ssub.sat/llvm.usub.sat), scaled multiplication (llvm.smul.fix/llvm.umul.fix/llvm.smul.fix.sat/llvm.umul.fix.sat), scaled division (llvm.sdiv.fix/llvm.udiv.fix/llvm.sdiv.fix.sat/llvm.udiv.fix.sat), and fixed-point <-> integer/floating-point conversions (ldexp/ scaled shifts).new/delete/ Array Cookies):eok_new/enk_new_deletefor single objects and arrays: computes allocation size with overflow checking (llvm.umul.with.overflow), adds Itanium/MSVC array cookies (sizeof(size_t)/ alignment padding) when the element type has a non-trivial destructor oroperator delete[](void*, size_t)requires element counts, invokes_Znwm/_Znam/ aligned_ZnwmSt11align_val_t(or MSVC??2@YAPEAX_K@Z), runs element constructors in a loop, and lowerseok_delete(scalar destructor +_ZdlPvor reverse array destruction loop + cookie adjustment +_ZdaPv).__atomic_*&__sync_*):__ATOMIC_RELAXEDthrough__ATOMIC_SEQ_CST) tollvm::AtomicOrdering.__atomic_load[_n],__atomic_store[_n],__atomic_exchange[_n],__atomic_compare_exchange[_n](AtomicCmpXchgInstwith success/failure orderings and weak/strong flag),__atomic_fetch_{add,sub,and,or,xor,nand},__atomic_{add,sub,and,or,xor,nand}_fetch,__atomic_test_and_set,__atomic_clear,__atomic_thread_fence,__atomic_signal_fence, and__atomic_is_lock_free/__atomic_always_lock_free.llvm_lower_fold_expressionlowers unary left/right folds ((... op pack),(pack op ...)) and binary left/right folds ((init op ... op pack),(pack op ... op init)) across all 32 fold-eligible C++17 operators, returning identity elements (truefor&&,falsefor||,void()for,) on empty packs.llvm_lower_sizeof_packevaluatessizeof...(Ts)to asize_tconstant.llvm_lower_builtin_operation& Intrinsic Calls):__builtin_clz*(llvm.ctlz),__builtin_ctz*(llvm.cttz),__builtin_popcount*(llvm.ctpop),__builtin_bswap{16,32,64}(llvm.bswap),__builtin_bitreverse*(llvm.bitreverse),__builtin_ffs*,__builtin_clrsb*,__builtin_parity*.__builtin_{add,sub,mul}_overflowand*{s,u}{add,sub,mul}*_overflow(llvm.{s,u}{add,sub,mul}.with.overflow).__builtin_memcpy/memmove/memset,__builtin_bit_cast(bopk_bit_cast),__builtin_offsetof(bopk_offsetof),__builtin_clear_padding(synthesizes per-byte padding mask viallvm_compute_type_padding_maskcovering struct alignment holes, bitfield unused bits, and union tail padding),__builtin_launder,__builtin_assume_aligned,__builtin_prefetch.__builtin_shufflevector(bopk_shufflevector),__builtin_convertvector(bopk_convertvector),__builtin_reduce_{add,mul,and,or,xor,min,max}.__builtin_trap(llvm.trap),__builtin_debugtrap(llvm.debugtrap),__builtin_unreachable,__builtin_expect(llvm.expect),__builtin_assume(llvm.assume),__builtin_constant_p(llvm.is.constant),__builtin_frame_address(llvm.frameaddress),__builtin_return_address(llvm.returnaddress),__builtin_dwarf_cfa(llvm.eh.dwarf.cfa),__builtin_LINE/FILE/FUNCTION/COLUMN/__builtin_source_location(std::source_location::__impl), and MSVC__uuidof(_GUIDconstant synthesis).sanitize_undefined/enable_ubsan_checksis active, emits inline division-by-zero, signed-overflow (INT_MIN / -1), shift-out-of-bounds, and null-pointer checks branching to__ubsan_handle_divrem_overflow,__ubsan_handle_add_overflow,__ubsan_handle_shift_out_of_bounds, orllvm.trap.3.4 Target Architecture SIMD & System Intrinsics (
llvm_gen_be_intrinsics.{h,cpp})Dedicated target builtin dispatcher (
llvm_try_lower_target_builtin) supporting 10 hardware architectures:llvm_lower_x86_builtin):SSE/SSE2/SSE3/SSSE3/SSE4.1/SSE4.2:sqrtps/pd/ss/sd,rcpps/rsqrtps,minps/maxps/minpd/maxpd,paddb/w/d/q,psubb/w/d/q,pmullw/d,padds/psubs/paddus/psubus(llvm.sadd.sat/uadd.sat),pshufb,dpps/dppd,blendvps/blendvpd,movmskps/movmskpd/pmovmskb,crc32(llvm.x86.sse42.crc32.*),pcmpistri/pcmpestri,lfence/sfence/mfence/pause.AVX/AVX2/FMA: 256-bitvsqrt*,vmin*/vmax*,vfmadd*(llvm.fma.*),vperm2f128/vperm2i128,vpshufb,vpmovmskb,vzeroall/vzeroupper.AVX-512&AMX: 512-bit masked arithmetic, reductions,vpdpbusd(llvm.x86.avx512.vpdpbusd.*), and AMX tile operations (ldtilecfg,sttilecfg,tilezero,tileloadd64,tilestored64,tdpbssd/tdpbf16ps).BMI1/BMI2/AES/SHA/ System:bextr,bzhi,pdep,pext,lzcnt/tzcnt,aesenc/aesenclast/aesdec/aesdeclast/aesimc/aeskeygenassist,sha1*/sha256*,rdtsc/rdtscp(llvm.readcyclecounter),rdrand*/rdseed*.llvm_lower_arm_builtin):NEON:vadd*,vsub*,vmul*,vfma*(llvm.fma),vqadd*/vqsub*(saturating),vmin*/vmax*,vabs*/vneg*,vsqrt*,vaddv*/vminv*/vmaxv*(llvm.vector.reduce.*),vtbl*/vtbx*,vld1*/vst1*.SVE/SVE2: Predicated scalable vector operations (svadd,svsub,svmul,svmad,svmla,svcntb/h/w/dviallvm.vscale,svptrue).CRC32&Crypto:__crc32b/h/w/d/cb/ch/cw/cd(llvm.aarch64.crc32*),vaeseq_u8,vaesdq_u8,vaesmcq_u8,vaesimc_u8,vsha1*,vsha256*,vsha512*,vsm3*,vsm4*.__dmb,__dsb,__isb(llvm.aarch64.dmb/dsb/isb),__yield/__wfe/__wfi/__sev/__sevl(llvm.aarch64.hint),__arm_rsr*(llvm.read_register),__arm_wsr*(llvm.write_register),__cls*,__rbit*(llvm.bitreverse).llvm_lower_riscv_builtin):RVV(Vector Extension):vsetvl/vsetvlmax, vector arithmetic (vadd,vsub,vmul,vfmacc), reductions (vredsum,vredmax,vredmin).Zbb/Zbc/Zbs/Zba/Zk(Bitmanip & Scalar Crypto):clz,ctz,cpop,orc.b,rev8,rol,ror,clmul/clmulh/clmulr(llvm.riscv.clmul*),aes64*/sha256*/sha512*/sm3*/sm4*.llvm_lower_ppc_builtin):Altivec/VSX:vec_add,vec_sub,vec_mul,vec_madd(llvm.fma),vec_adds/vec_subs,vec_min/vec_max,vec_perm,vec_ld/vec_vsx_ld,vec_st/vec_vsx_st,__dcbz,__lwsync/__sync/__isync/__eieio.s390x(llvm_lower_s390x_builtin):vec_add,vec_sub,vec_mul,vec_madd,vec_perm,vec_cntlz,vec_cnttz,vec_popcnt) and transactional execution (__builtin_tbegin,__builtin_tend,__builtin_tabort).LSX/LASX, MIPSMSA, SPARCVIS, & WebAssemblySIMD128(llvm_lower_other_arch_builtin):__lsx_*and 256-bit__lasx_*vector arithmetic,cpucfg,crc_w_*,dbar/ibar.__builtin_msa_*vector arithmetic and min/max.__builtin_vis_*(faligndata,fpack*,pdist).wasm_i32x4_*,wasm_f32x4_*,wasm_v128_*,svmin/svmax/avgr/abs/sqrt,memory_size/memory_growviallvm.wasm.memory.size/grow).3.5 Control Flow, Statements, VLAs, & Scoped RAII Cleanups (
llvm_gen_be_stmt.cpp)stmk_block,stmk_if,stmk_while,stmk_end_test_while(do-while),stmk_for,stmk_switch(including GNU case rangescase low ... high:expanded intoSwitchInstrange targets),stmk_goto,stmk_label, andstmk_return.stmk_assigned_goto): Collects all address-taken labels in the current routine and emitsllvm::IndirectBrInstwith exact destination basic block lists.ScopeCleanupStack):llvm.stacksave/llvm.stackrestore), thread-safe local static initialization guards (__cxa_guard_abort), and SEH__finallyfunclets.return,break,continue, andgotocompares the source cleanup stack depth against the target scope depth (usingllvm_precompute_function_labelsfor forward and backwardgotostatements) and emits the exact sequence of intervening destructor calls andllvm.stackrestoreintrinsics in reverse construction order.({ ... })is active, protects enclosing scope cleanups usingstmt_expr_cleanup_depths.3.6 Declarations, Linkage, TLS, C++20 Modules, & Unlowered Name Mangling (
llvm_gen_be_decl.cpp)llvm_mangle_unlowered_entity):DO_IL_LOWERINGcan be disabled or bypassed for templates/inline routines, implements a complete fallback mangler supporting both Itanium C++ ABI (_Z..., nestedN...E,Stsubstitution, cv-qualifiersK/V, ref-qualifiersR/O, constructorsC1/C2, destructorsD0/D1/D2, conversion operatorscv<type>, overloaded operatorspl/mi/ml/eq/cl/etc., template argument listsI...E, vendor extended typesu7__bf16/Dh/g, and function parameter lists) and Microsoft Visual C++ ABI (?name@scope@@...).sc_static,sc_extern,sc_unspecified), weak/inline/template attributes (LinkOnceODRLinkage,WeakODRLinkage,WeakAnyLinkage,CommonLinkage), ELF/Mach-O visibility (Default,Hidden,Protected), Windowsdllexport/dllimport(DLLExportStorageClass/DLLImportStorageClass), and custom ELF/Mach-O/COFF__attribute__((section("..."))).llvm::Comdatgroups (Comdat::SelectionKind::Any) for inline variables, template instantiations, vtables, and typeinfo globals on ELF and COFF targets.__tls_init:llvm::GlobalValue::GeneralDynamicTLSModel,LocalDynamicTLSModel,InitialExecTLSModel, orLocalExecTLSModel.thread_localvariables requiring dynamic initialization, emits a guarded__tls_initfunction, an WeakODR_ZTH<var>thread-local wrapper alias/stub, and registers thread-local destructors via__cxa_thread_atexit._ZGV...) and lowers thread-safe initialization using Itanium__cxa_guard_acquire/__cxa_guard_release/__cxa_guard_abort(with an activeScopeCleanupthat invokes__cxa_guard_aborton exception unwind and registers__cxa_atexitfor destruction) or MSVC_Init_thread_header/_Init_thread_footer/_Init_thread_abort.llvm.global_ctors/llvm.global_dtors/.CRT$XCU):__sti__<tu>initialization routines for globals inbe_state->global_dynamic_inits(handlingconstructor(priority)attributes, default priority65535, and__cxa_atexitregistration) and appends them to@llvm.global_ctorsand@llvm.global_dtors(or.CRT$XCUfunction pointer tables on Windows MSVC targets).llvm_lower_module_metadata):primary_Scope->module_infoand imported module lists to emit module flags (C++20 Module,C++20 Module Partition),!edg.cpp20.moduleand!edg.cpp20.importsmetadata nodes, an idempotent guard variable@__module_init_guard_<mod>, and an external@__module_init_<mod>()routine that initializes imported modules before local TU constructors.3.7 C++ Object Model: VTables, VTTs, Construction VTables, & Thunks (
llvm_gen_be_vtable.{h,cpp})_ZTV,_ZTT,_ZTC):llvm_emit_class_vtablesconstructs the complete vtable group for polymorphic classes:vcall/vbaseoffsets for virtual bases,offset-to-top=0,@_ZTI<Class>RTTI pointer, and virtual function/thunk pointers, with@__cxa_pure_virtual/@__cxa_deleted_virtualfor pure/deleted methods).offset-to-top = -base_offset, base vbase offsets, RTTI pointer, andthis-adjusted / covariant thunks)._ZTC<Derived><offset>_<Base>) and Virtual Table Tables (_ZTT<Class>) in preorder inheritance graph order for classes with virtual bases.VFTable&VBTable):??_7<Class>@@6B@(VFTable) preceded by a pointer to the Complete Object Locator (??_R4<Class>@@6B@) in a two-element struct{ ptr @??_R4, [N x ptr] }so the exported symbol points to[N x ptr]at offset+sizeof(ptr).??_8<Class>@@7B@(VBTable) containing[i32 0, i32 vbase_offset_1, ...]for classes with virtual base classes._ZTv,_ZTh,_ZTch, & MSVCvtordisp):this-adjustment thunks (_ZTh<n>_...): adjuststhisby constant byte offsetnand tail-calls (musttailwhen variadic or eligible) the target method.this-adjustment thunks (_ZTv0_n<vcall>_...): loads the vtable pointer fromthis, reads thevcalloffset atvcall_offset, adds it tothis, and dispatches to the target method._ZTch<this_adj>_h<ret_adj>_.../_ZTcv...): adjuststhison entry, calls the underlying implementation, checks the returned pointer fornullptr, and applies static/virtual base adjustment to the non-null return pointer.vtordispthunks (?fn@Class@@$4PPPPPPPM@A@...): reads the 32-bitvtordispdisplacement atthis - 4, subtracts it together with the static base adjustment, and tail-calls the target method.llvm_try_devirtualize_call):final, or when the receiver object's dynamic type is statically proven (localalloca, global variable, or constructor/destructorthis).3.8 Run-Time Type Information (RTTI): Itanium & MSVC (
llvm_gen_be_rtti.{h,cpp})get_typeinfo_global):_ZTS<Type>mangled type name strings and_ZTI<Type>descriptors referencingvtable_prefix + 2 * sizeof(ptr):__cxxabiv1::__fundamental_type_infofor primitives andvoid.__cxxabiv1::__pointer_type_info(with cv-qualification bitmasks) for pointers.__cxxabiv1::__pointer_to_member_type_infofor pointers to members.__cxxabiv1::__class_type_infofor root classes/unions.__cxxabiv1::__si_class_type_infofor single public non-virtual inheritance.__cxxabiv1::__vmi_class_type_infofor multiple or virtual inheritance, computing diamond/repeated base flags (0x1non-diamond repeat,0x2diamond shaped) and__base_class_type_infoarrays with encoded(base_offset << 8) | (is_virtual ? 1 : 0) | (is_public ? 2 : 0)flags.get_msvc_type_descriptor&get_msvc_complete_object_locator):??_R0?AU<Class>@@@8(_TypeDescriptorwith??_7type_info@@6B@vptr,spare, and mangled name),??_R3(_s__RTTIClassHierarchyDescriptor),??_R2(_s__RTTIBaseClassArray),??_R1(_s__RTTIBaseClassDescriptorwithmdisp,pdisp,vdisp, and attributes), and??_R4(_s__RTTICompleteObjectLocatorusing 32-bit image-relative offsets on 64-bit Windows and direct pointers on 32-bit Windows).dynamic_cast(llvm_lower_dynamic_cast) &typeid(llvm_lower_typeid):dynamic_cast<void*>(p): checksp != nullptr, loadsoffset-to-topatvptr[-2], and returnsp + offset_to_top.dynamic_cast<Dest*>(p)/dynamic_cast<Dest&>(r): computessrc2dsthint (0public base,-1unknown,-2not a public base), calls__dynamic_cast(Itanium) or__RTDynamicCast(MSVC), and for reference casts checks the result fornullptrand branches to__cxa_bad_caston failure.typeid(*p): checksp == nullptr(branching to__cxa_bad_typeidon null dereference), loadsvptr[-1](Itanium) or invokes__RTtypeid(p)(MSVC).3.9 Pointers to Members (Data & Function): Itanium & MSVC (
llvm_gen_be_ptrmem.{h,cpp}){ i64 ptr, i64 adj }(or{ i32, i32 }on 32-bit targets). For non-virtual functions,ptris the function address andadjis the byte offset adjustment (evenon x86/RISC-V; on ARM/AArch64/MIPS,adjbit 0 encodes the virtual indicator whileptrholds the vtable byte offset). Call lowering (llvm_lower_pmf_call) tests the virtual bit, branches between direct call and vtable load (*(vptr + vtable_offset)), adjuststhis, and merges via aPHInode.ptr), Multiple Inheritance ({ ptr, i32 adj }), and Virtual Inheritance ({ ptr, i32 adj, i32 vindex }, loadingVBTableat*(this + adj) + vindex).ptrdiff_t(i64/i32) where-1(0xfff...) representsnullptr. Field access (llvm_lower_pdm_field) adds the byte offset to the base object pointer; conversions (llvm_lower_pm_conversion) check against-1before adding/subtracting base subobject offsets.i32where-1representsnullptr(or{ i32 mdisp, i32 pdisp, i32 vdisp }under virtual inheritance).3.10 Exception Handling: Itanium DWARF Unwinding & Windows SEH (
llvm_gen_be_eh.{h,cpp})@__gxx_personality_v0to functions withtryblocks or active RAII cleanups.current_landing_padsscopes intollvm::InvokeInst.throw expr(llvm_lower_throw) to@__cxa_allocate_exception, stores/constructs the exception object, and invokes@__cxa_throw(ex_ptr, @_ZTI<T>, @dtor)followed byunreachable; lowersthrow;(eok_rethrow) to@__cxa_rethrow().landingpad { ptr, i32 }blocks withaddClausefor catch handlers andsetCleanup(true)for RAII destructors, matching catch types via@llvm.eh.typeid.for+icmp eq, extracting exception pointers with@__cxa_begin_catch/@__cxa_end_catch, and resuming unwinding viaresume { ptr, i32 }or chaining to outer landing pads (llvm_emit_chained_cleanup_landingpad).noexcept/throw()functions, routes unhandled exceptions to acatch ptr nullterminate landing pad calling@__clang_call_terminate(__cxa_begin_catch->std::terminate).throw(T1, T2)), emits negative filter selector checks (sel < 0) calling@__cxa_call_unexpected.@__CxxFrameHandler3(or@__C_specific_handlerfor C SEH) and lowerstry/catchusing Windows funclet tokens:catchswitch within ... [label %catch.pad] unwind to caller,catchpad within %cs [ptr @TypeDesc, i32 flags, ptr %catch_var], andcatchret from %cp to label %cont._ThrowInfo(_TI...),_CatchableTypeArray(_CTA...), and_CatchableType(_CT...) descriptors and lowersthrowto@_CxxThrowException(ptr %ex_slot, ptr @_TI...).__try/__except/__finally/__leave:@llvm.localescape(...)in the parent function entry block for local variables accessed by filter or finally funclets.__except(filter_expr)expressions into dedicated filter functions (?filt$0@0@<fn>@@) using@llvm.eh.exceptionpointer/@llvm.eh.exceptioncode(_exception_info()/_exception_code()) and@llvm.localrecover.__finallyblocks into cleanup funclets (?fin$0@0@<fn>@@(i8 abnormal_termination, ptr frame_pointer)) invoked both on normal exit (abnormal_termination = 0) and insidecleanuppadunwind blocks (abnormal_termination = 1).__leavestatements (llvm_lower_seh_leave) by branching to the innermost enclosing__trybody exit block (seh_leave_blocks)./EHaasynchronous SEH (llvm_enable_async_seh_attributes) by attaching"async-exceptions"="true"and"seh-asynch"="true"function attributes and modeling volatile memory accesses.3.11 C++20 Coroutines (
llvm_gen_be_coro.{h,cpp})llvm_lower_coroutine_stmt,llvm_lower_coroutine_return,llvm_lower_co_await_or_yield):@llvm.coro.id(i32 align, ptr %promise, ptr null, ptr null), checks@llvm.coro.alloc(token %id)for heap elision, queries@llvm.coro.size.i64()(including over-aligned frame padding whenalign > __STDCPP_DEFAULT_NEW_ALIGNMENT__), allocates the coroutine frame via_Znwm/operator new, and initializes the frame handle with@llvm.coro.begin(token %id, ptr %mem).promise.get_return_object(),co_await promise.initial_suspend(), the coroutine body,promise.return_value(v)/promise.return_void(),promise.unhandled_exception()in the exception landing pad, andco_await promise.final_suspend().@llvm.coro.save(ptr %hdl)and@llvm.coro.suspend(token %save, i1 %is_final)with 3-way switch dispatch (0-> resume,1-> cleanup,default-> suspend block calling@llvm.coro.end(ptr %hdl, i1 false, token none)).@llvm.coro.free(token %id, ptr %hdl)and_ZdlPv.__builtin_coro_resume(@llvm.coro.resume),__builtin_coro_destroy(@llvm.coro.destroy),__builtin_coro_done(@llvm.coro.done),__builtin_coro_promise(@llvm.coro.promise), and__builtin_coro_noop(@llvm.coro.noop).3.12 Inline Assembly: GNU Extended
asm/asm goto& MSVC__asm(llvm_gen_be_asm.{h,cpp})stmk_asm):%0,%1,%w0,%x0,%k0,%q0, named%[sym],%%->$$literal escaping) into LLVMInlineAsmformat ($0,${0:w}, etc.).llvm_canonicalize_asm_constraintnormalizes target-specific constraints: tied inputs ("=r,0"), early-clobber ("=&r"), indirect memory outputs/inputs ("=*m","*m"), architecture-specific register constraints ("a"->"{eax}","b"->"{ebx}","c"->"{ecx}","d"->"{edx}","S"->"{esi}","D"->"{edi}","Yz"->"{xmm0}"), and clobber lists (~{memory},~{cc},~{dirflag},~{fpsr},~{flags}).{ T0, T1, ... }unpacked viaExtractValueInstand stored back to each output lvalue (with integer/pointer bitcast/trunc/zext coercion when register width differs from the C lvalue width).asm goto: When jump labels are present onstmk_asm, emits anllvm::CallBrInstwith fallthrough and indirect target basic blocks.__asmBlocks (lower_msvc_inline_asm):__asm { ... }blocks, comments (;), local labels, data directives (db,dw,dd,dq),rep/lockprefixes, memory addressing ([ebp + var],dword ptr [rax + rcx*4 + 8]), local/global C variable substitution into numbered$0,$1operands, automatic modified-register clobber detection (~{eax},~{ebx}, etc.), and emission withllvm::InlineAsm::AD_Intel.3.13 OpenMP 4.5 / 5.x Host Directives & GPU Target Offloading (
llvm_gen_be_omp.{h,cpp})libomp/__kmpc_*):parallel: Captures shared/private/firstprivate variables, outlines.omp_outlined.microtask(i32* .global_tid., i32* .bound_tid., ...), and emits@__kmpc_fork_call(ptr @ident, i32 argc, ptr @.omp_outlined., ...). Also respectsif(cond)(__kmpc_serialized_parallel/__kmpc_end_serialized_parallel) andnum_threads(n)(__kmpc_push_num_threads).for/distribute: Static (__kmpc_for_static_init_4/8+__kmpc_for_static_fini) and dynamic/guided/runtime (__kmpc_dispatch_init_4/8+__kmpc_dispatch_next_4/8) loop chunking.reduction: Emits thread-private accumulators, a.omp.reduction.red_listpointer array, an outlined@.omp_reduction_func, and@__kmpc_reduce_nowait/@__kmpc_end_reduce_nowaitwith atomic fallback loop.sections&single:@__kmpc_for_static_init_4section switch dispatch and@__kmpc_single/@__kmpc_end_single(pluscopyprivatebroadcast via@__kmpc_copyprivate).task,taskloop,taskwait, &taskyield:@__kmpc_omp_task_alloc,@__kmpc_omp_task,@__kmpc_omp_task_with_deps,@__kmpc_omp_taskloop,@__kmpc_omp_taskwait, and@__kmpc_omp_taskyield.@__kmpc_critical/@__kmpc_end_critical(with named critical spinlocks),@__kmpc_barrier,@__kmpc_master/@__kmpc_end_master,@__kmpc_masked/@__kmpc_end_masked,@__kmpc_ordered/@__kmpc_end_ordered,@__kmpc_flush+fence seq_cst, andomp atomic(read,write,update,captureviaAtomicRMWInst/AtomicCmpXchgInst).simd&declare simd: Attaches!llvm.loop.vectorize.enable,!llvm.loop.vectorize.width, and!llvm.loop.parallel_accessesmetadata to loops, and emits Vector Function ABI (_ZGVbN4v_...,_ZGVdN8v_...,_ZGVeN16v_...,_ZGVnN4v_...) SIMD clones for#pragma omp declare simd.libomptarget):parse_omp_map_clausesparsesmap(to:),map(from:),map(tofrom:),map(alloc:),map(release:), andmap(delete:)clauses intoOMP_TGT_MAPTYPE_*bitmasks (0x01TO,0x02FROM,0x10ALWAYS,0x20DELETE,0x200PARAM,0x400IMPLICIT).lower_omp_targetconstructs.offload_baseptrs,.offload_ptrs,.offload_sizes, and@.offload_maptypes, populates%struct.__tgt_kernel_arguments, invokes@__tgt_target_kernel(ptr @ident, i64 device_id, i32 num_teams, i32 thread_limit, ptr @.__omp_offloading_entry, ptr %kernel_args), and falls back to the host execution region if@__tgt_target_kernelreturns non-zero.lower_omp_target_data_regionemits@__tgt_target_data_begin_mapper,@__tgt_target_data_end_mapper, and@__tgt_target_data_update_mapperfortarget data,target enter data,target exit data, andtarget update.compile_omp_device_modulesynthesizes a dedicated GPU devicellvm::Modulefornvptx64-nvidia-cudaoramdgcn-amd-amdhsa(ptx_kernel/amdgpu_kernelcalling conventions,!nvvm.annotations), compiles it viaTargetMachine(or emits a structured PTX/bitcode image), and embeds it into@.omp_offloading.device_imageand.omp_offloading_entriesin the host module.3.14 Multi-Architecture Target Calling Convention ABIs (12 Architectures)
Centralized dispatcher
llvm_compute_function_abi_info+ 12 dedicated target psABI modules:llvm_gen_be_abi_sysv_x86_64.{h,cpp}): Recursive eightbyte classification (NO_CLASS,INTEGER,SSE,SSEUP,X87,X87UP,COMPLEX_X87,MEMORY) with post-merger cleanups, register pressure tracking (6 GPRs, 8 XMMs), 1- and 2-eightbyte register coercion (i64,double,{i64, i64},{i64, double},{double, i64},{double, double},<2 x float>),sret/byval, non-trivial C++ aggregate invisible references, and[1 x { i32, i32, ptr, ptr }]va_list/va_argregister-save-area + overflow-area branching.llvm_gen_be_abi_win64.{h,cpp}): 4-slot positional register model (RCX/XMM0,RDX/XMM1,R8/XMM2,R9/XMM3), power-of-two integer coercion (i8,i16,i32,i64) vs. indirect pointer passing for composites of size!= 1, 2, 4, 8,__vectorcall(X86_VectorCall) HVA support inXMM0–XMM5, and contiguousptrva_list/va_arg.llvm_gen_be_abi_aapcs64.{h,cpp}): HFA/HVA detection (1–4 homogeneous float/half/double/quad/vector elements passed inV0–V7), composites <= 16 bytes coerced to[N x i64]inX0–X7, composites > 16 bytes passed indirectly by pointer, Darwinarm64char*va_listvs. Linux ELF[1 x { ptr, ptr, ptr, i32, i32 }]va_list, and Windows ARM64EC emulation-compatible thunk signatures (build_arm64ec_thunk_signature).llvm_gen_be_abi_x86_32.{h,cpp}):cdecl,stdcall(X86_StdCall),fastcall(X86_FastCall),thiscall(X86_ThisCallplacingthisinECX), andregparm(1..3)inregattribute assignment.llvm_gen_be_abi_arm32.{h,cpp}):AAPCSandAAPCS-VFPHFA detection, 4-byte/8-byte alignment[N x i32]/[N x i64]register coercion, andsretfor composites > 4 bytes.llvm_gen_be_abi_riscv64.{h,cpp}): Hardware FP flattening ({ float, float },{ double, int },{ int, double }), 1x/2x XLEN (i64/[2 x i64]) coercion for aggregates <= 16 bytes, and indirect reference passing for aggregates > 16 bytes.llvm_gen_be_abi_loongarch64.{h,cpp}): GAR ($a0–$a7) and FAR ($fa0–$fa7) classification (float_float,integer_float,float_integer,integer_integer,memory).llvm_gen_be_abi_mips.{h,cpp}): 32-bit O32 and 64-bit N64 register chunk coercion, soft-float vs. hard-float handling, andbyval/sretplacement.llvm_gen_be_abi_ppc64.{h,cpp}): ELFv2 up-to-8-element HFA detection (f1–f13), AltiVec/VSX vector passing (v2–v13), and GPR (r3–r10) octword coercion.s390x(llvm_gen_be_abi_s390x.{h,cpp}): GPR (%r2–%r6) and FPR (%f0,%f2,%f4,%f6) tracking, single-float struct FPR promotion, 1/2/4/8-byte power-of-two struct integer coercion, and[1 x { i64, i64, ptr, ptr }]va_list.llvm_gen_be_abi_sparc.{h,cpp}): 32-bit V8 indirectbyvalpassing vs. 64-bit V9 register coercion for aggregates up to 32 bytes.llvm_gen_be_abi_wasm.{h,cpp}): Direct scalar/single-element struct unpacking and indirect linear-memory pointer passing (byval/sret) for multi-field composites onwasm32andwasm64.3.15 Debug Information: DWARF v4/v5, Split DWARF, & CodeView (
llvm_gen_be_debug*.{h,cpp})Split across three focused files (
llvm_gen_be_debug.cpp,llvm_gen_be_debug_scopes.cpp,llvm_gen_be_debug_types.cpp):Dwarf Version), Split DWARF (splitDebugFilename.dwo), and Windows CodeView (CodeViewmodule flag =1for.pdbemission when targeting*-windows-msvc).llvm_gen_be_debug_scopes.cpp): Maintains a scope stack (DICompileUnit->DINamespace->DISubprogram->DILexicalBlock), maps EDGa_seq_numbersource coordinates toDIFile+ line + column, and supportsDILocation::get(..., inlinedAt)for inlined call chains (llvm_debug_create_inlined_location).llvm_gen_be_debug_types.cpp):DIBasicTypewithDW_ATE_boolean,DW_ATE_signed,DW_ATE_unsigned,DW_ATE_float,DW_ATE_UTF,DW_ATE_complex_float), pointers/references (DIDerivedType), qualifiers (DW_TAG_const_type,DW_TAG_volatile_type,DW_TAG_restrict_type), typedefs (DW_TAG_typedef), arrays/vectors (DICompositeTypewithDISubrange), and subroutines (DISubroutineType).DIDerivedTypemembers (includingDIFlagBitFieldbit offsets/sizes,DIFlagPublic/Protected/Private, static members),createInheritancebase classes (with virtual basevtableoffsets), vptr holder links, member function declarations, andDITemplateTypeParameter/DITemplateValueParameterlists.DW_TAG_enumeration_typewithDIEnumeratorconstants andDIFlagEnumClassforenum class).llvm_gen_be_debug.cpp):#dbg_declare/llvm.dbg.declarefor allocas,#dbg_value/llvm.dbg.valuewithDIExpression::createFragmentExpression(offset_bits, size_bits)for scalarized struct fragments (llvm_debug_emit_fragment_value),DIGlobalVariableExpressionfor globals (andDICommonBlockfor common blocks),DIImportedEntityforusingdeclarations/directives, andDIMacroFile/DIMacro(DW_MACINFO_define/DW_MACINFO_undef) for DWARF v5-g3macro debugging.3.16 Optimization Pipeline, Sanitizers, PGO, LTO, & Code Emission (
llvm_gen_be_opt.{h,cpp},llvm_gen_be_codegen.{h,cpp})run_optimization_pipeline):LoopAnalysisManager,FunctionAnalysisManager,CGSCCAnalysisManager, andModuleAnalysisManagerwithPassBuilder.CoroEarlyPass,CoroSplitPass,CoroElidePass,CoroCleanupPass),Mem2Reg/SROA, and eitherbuildO0DefaultPipelineorbuildPerModuleDefaultPipeline(O1,O2,O3,Os,Oz) with configurable Loop and SLP vectorization.buildThinLTOPreLinkDefaultPipeline) and FullLTO (buildLTODefaultPipeline) pipelines.-fprofile-generate[=<dir>]: RunsPGOInstrumentationGenand sets__llvm_profile_filenamewhen a custom directory/file is specified.-fprofile-use=<profdata>: RunsPGOInstrumentationUsewith the supplied.profdatafile.-fsanitize=): Configures and runsAddressSanitizerPass(SanitizeAddress),ThreadSanitizerPass(SanitizeThread),MemorySanitizerPass(SanitizeMemory),HWAddressSanitizerPass(SanitizeHWAddress), and attachesSafeStack(safestack) andShadowCallStack(shadowcallstack) attributes alongside stack protector modes (ssp,sspstrong,sspreq).llvm_gen_be_codegen.cpp):InitializeAllTargetInfos,InitializeAllTargets,InitializeAllTargetMCs,InitializeAllAsmParsers,InitializeAllAsmPrinters)..ll), LLVM bitcode (.bc, optionally embedding aModuleSummaryIndexfor ThinLTO), target assembly (.sviaCodeGenFileType::AssemblyFile), and native relocatable object code (.o/.objviaCodeGenFileType::ObjectFile).3.17 Native Toolchain Discovery, Linker Driver, & Front-End CLI Integration (
llvm_gen_be_driver.{h,cpp},cmd_line.{h,c})discover_target_toolchain&build_native_linker_args):crt1.o/Scrt1.o,crti.o,crtbegin.o,crtend.o,crtn.o), macOS Xcode / CommandLineTools SDKs (xcrun --show-sdk-path,-syslibroot), and Windows MSVC / Windows SDK library paths.-fsanitize=*), PGO profile runtimes (-fprofile-instr-generate), OpenMP runtimes (-fopenmp/-lomp), C++ standard libraries (-lc++/-lstdc++/msvcprt.lib), and user-L/-l/-Wl,flags.run_thinlto_combined_index_and_link&llvm_finalize_multi_tu_link):cpfe a.cpp b.cpp -flto=thin -o app), each TU emits bitcode/object files and registers them inbe_state->extra_linker_inputs; after the final TU,llvm_finalize_multi_tu_linkparses all bitcode modules, builds the combinedModuleSummaryIndex, links the IR modules viallvm::Linker::linkModules, runs the LTO optimization pipeline, emits the native object, and links the final executable.cpfe(src/cmd_line.h,src/cmd_line.c):--llvm,--gen_llvm_file_name(--emit-llvm),--gen_llvm_bc_file_name(--emit-llvm-bc),--gen_llvm_thinlto_index,--gen_obj_file_name/-c,--gen_asm_file_name/-S,-o <file>.-O0,-O1,-O2,-O3,-Os,-Oz,--llvm_opt_level,-flto,-flto=thin,-flto=full,-fprofile-generate[=<path>],-fprofile-use=<path>.-g,--llvm_debug_info,-gsplit-dwarf[=<dwo>],-fsanitize={address,thread,memory,undefined,hwaddress,safe-stack,shadow-call-stack},-fstack-protector,-fstack-protector-strong,-fstack-protector-all.--target=<triple>/-target <triple>,-mcpu=<cpu>/-march=<arch>,-mattr=<features>,-fPIC/-fpic/-fPIE/-fpie/-fno-pic,-mcmodel={tiny,small,kernel,medium,large},-fopenmp,-L<dir>,-l<lib>,-Wl,<arg>.4. Front-End Decoupling & Integration Changes
To ensure the EDG front end operates cleanly as a native compiler front end when
BACK_END_IS_LLVM_GEN_BE == 1without breakingc_gen_beorcp_gen_bebuilds:src/host_envir.h&src/target.h:BACK_END_IS_LLVM_GEN_BE(defaulting toFALSE) and guardedBACK_END_IS_C_GEN_BEso the two cannot be simultaneously active.COMPILE_MULTIPLE_SOURCE_FILESandDO_IL_LOWERINGcompatibility whenBACK_END_IS_LLVM_GEN_BEis enabled.src/c_gen_be.{h,c}&src/cp_gen_be.{h,c}:back_end()declarations and definitions with#if !BACK_END_IS_LLVM_GEN_BEsollvm_gen_be.cppprovides the canonicalback_end()entry point.src/cfe.c&src/fe_wrapup.c:llvm_gen_be.hwhenBACK_END_IS_LLVM_GEN_BEis enabled.llvm_finalize_multi_tu_link()after the multi-TU compilation loop incfe.candllvm_gen_be_cleanup()infe_wrapup.c.skip_il_read = TRUEby default forBACK_END_IS_LLVM_GEN_BEso in-memory IL is lowered directly without unnecessary disk serialization, and allowed-o <output>with both single and multiple input source files.src/il_alloc.c,src/layout.c,src/lower_c99.c,src/lower_eh.c,src/lower_il.c,src/lower_name.c,src/sizeof.c,src/statements.c,src/sys_predef.c):BACK_END_IS_C_GEN_BEorBACK_END_IS_CP_GEN_BEexisted, ensuring proper layout, exception lowering, and predefined macro registration whenBACK_END_IS_LLVM_GEN_BEis active.CMakeLists.txt,src/CMakeLists.txt,tests/CMakeLists.txt,CMakePresets.json):src/CMakeLists.txtto C++17 (CMAKE_CXX_STANDARD 17) required by LLVM headers.ENABLE_LLVM_BACKENDandEDG_LLVM_BE_COVERAGECMake options, automatic Homebrew/system LLVMfind_package(LLVM CONFIG)detection, and presetsllvm-backend-debug,llvm-backend-release, andllvm-backend-coverage.check_doc_coverageverifying 100% Doxygen coverage on every build.5. Chronological Summary of All 10 Commits
Commit 1:
c3770edf17— LLVM IR backend (initial pass)src/llvm_gen_be.cppandsrc/llvm_gen_be.h.ENABLE_LLVM_BACKENDintoCMakeLists.txt,src/CMakeLists.txt,cmake/macro-conf.cmake,src/host_envir.h,src/cfe.c, andsrc/cmd_line.{h,c}.LLVMContext,Module, andIRBuilderinitialization, basic primitive integer/float/pointer type translation, simple global/function declaration emission, and basic arithmetic expression lowering.Commit 2:
b08d2a4fd9— LLVM IR backend: implement types, control flow, ABI, expressions, and C++ testslocal_vars), LValue vs. RValue evaluation with implicit loads, and dynamicTargetTriple/DataLayoutconstruction.@llvm.global_ctors/@llvm.global_dtorsdynamic initializer registration.if,while,do-while,for,switch,break,continue,goto), GEP indexing, direct/indirect/vararg/sretcalls, casts, and initial C++ unit tests.Commit 3:
72e30b8274— LLVM IR backend: implement exception handling, inline assembly, computed gotos, and test suite__gxx_personality_v0,landingpad,__cxa_allocate_exception,__cxa_throw,__cxa_rethrow,__cxa_begin_catch,__cxa_end_catch, andinvokelowering).stmk_asminline assembly lowering tollvm::InlineAsmwith constraint and clobber translation.stmk_assigned_goto) viallvm::IndirectBrInstandllvm::BlockAddress.fp_to_hex_constant_string), UTF-16/UTF-32 string constant arrays, and.github/workflows/llvm_be_coverage.yml.Commit 4:
c387283f31— LLVM IR backend: add RTTI/EH dispatch, inline asm outputs, opaque ptr support, and verificationllvm::verifyFunctionandllvm::verifyModulewith source position diagnostic reporting.get_typeinfo_global) and catch clause type matching via@llvm.eh.typeid.for.*m), and extraction into lvalue destinations.ptr) and addedbfloat16,fp16,fp80, andfp128float/complex mappings.Commit 5:
5cc528b69f— LLVM IR backend: decouple C-backend macros, dynamically resolve target layouts, and refine codegenTARG_*macros inllvm_gen_bewith dynamic runtimetarg_*variables so cross-target layouts resolve accurately at runtime.BACK_END_IS_LLVM_GEN_BEfromBACK_END_IS_C_GEN_BEacrosssrc/host_envir.h,src/target.h,src/il_alloc.c,src/lower_c99.c,src/lower_eh.c,src/lower_il.c,src/lower_name.c,src/sizeof.c,src/statements.c, andsrc/sys_predef.c.read_memory_regioninget_scope_for_routine_definition) and guaranteed basic block termination prior to IR verification.Commit 6:
e06c445859— LLVM IR backend: implement target ABIs, DWARF debug info, code emission, and pass pipelinellvm_gen_be_error.{h,cpp},llvm_gen_be_type.{h,cpp},llvm_gen_be_const.{h,cpp},llvm_gen_be_expr.{h,cpp},llvm_gen_be_debug*.{h,cpp},llvm_gen_be_opt.{h,cpp}, andllvm_gen_be_codegen.{h,cpp}.llvm_gen_be_abi_sysv_x86_64.{h,cpp}), ARM64 AAPCS64 (llvm_gen_be_abi_aapcs64.{h,cpp}), and Windows x64 (llvm_gen_be_abi_win64.{h,cpp}).DIBuilderDWARF debug metadata emission, LLVM NewPassManager(O0–Oz) optimization pipelines, andTargetMachine.o/.s/.bcemission.Commit 7:
7fa91abfbf— LLVM IR backend: standardize noexcept error propagation, integrate DWARF scopes, and update test suitellvm_gen_be_error_twith[[nodiscard]]at the type definition and annotated all backend APIs withnoexcept, migrating all internal and external helpers to returnllvm_gen_be_error_twith pointer out-parameters.be_state->err_contextacross codegen and pass execution.DISubprogram,DILexicalBlockscopes, andllvm.dbg.declareparameter/local variable metadata directly into routine lowering, and hookedllvm_gen_be_cleanup()intosrc/fe_wrapup.c.Commit 8:
7f49d998df— LLVM IR backend: modularize vtables, EH, inline asm, coroutines, atomics, and revamp test suitellvm_gen_be_vtable.{h,cpp},llvm_gen_be_rtti.{h,cpp},llvm_gen_be_eh.{h,cpp},llvm_gen_be_asm.{h,cpp},llvm_gen_be_coro.{h,cpp},llvm_gen_be_decl.cpp,llvm_gen_be_stmt.cpp, andllvm_gen_be_abi_riscv64.{h,cpp}.llvm.coro.*), C11/C++20 atomic builtins (__atomic_*), and Windows SEH funclet unwinding (catchswitch/catchpad/cleanuppad).dev_tools/check_doc_coverage.pyandDoxyfile.llvm_beenforcing 100% Doxygen documentation coverage, and consolidated the test suite into self-contained C++ unit test binaries (tests/test_llvm_*.cpp).Commit 9:
d9b6bcef10— LLVM IR backend: implement multi-target ABIs, member pointers, OpenMP, PGO/LTO pipelines, and expanded test coveragellvm_gen_be_abi_arm32,llvm_gen_be_abi_loongarch64,llvm_gen_be_abi_mips,llvm_gen_be_abi_ppc64,llvm_gen_be_abi_s390x,llvm_gen_be_abi_sparc,llvm_gen_be_abi_wasm, andllvm_gen_be_abi_x86_32.llvm_gen_be_ptrmem.{h,cpp}) for both Itanium and MSVC (single, multiple, and virtual inheritance) models.llvm_gen_be_omp.{h,cpp}) and native linker driver orchestration (llvm_gen_be_driver.{h,cpp}) with PGO (-fprofile-generate/-fprofile-use), ThinLTO/FullLTO, and sanitizer pipelines.Commit 10:
9ab18501e1— LLVM IR backend: implement target intrinsics, OpenMP 5.x offloading, TBAA, and 100% coveragesrc/llvm_gen_be_intrinsics.{h,cpp}covering SIMD and system builtins across x86/x86_64 (SSE–AVX-512,AMX,BMI,AES,SHA), ARM/AArch64 (NEON,SVE,CRC32,Crypto, barriers, sysregs), RISC-V (RVV,Zbb/Zbc/Zbs), PowerPC (Altivec/VSX),s390x, LoongArch (LSX/LASX), MIPS (MSA), SPARC (VIS), and WebAssembly (SIMD128).__tgt_target_kernel,__tgt_target_data_*_mapper,nvptx64/amdgcndevice module compilation) and constructs forsimd,teams distribute,taskloop,taskyield,flush,ordered,master/masked,atomic,declare simd, anddeclare reduction.!tbaa,!tbaa.struct), ISO/IEC TR 18037 fixed-point intrinsics, C++17 fold expressions (enk_fold),sizeof...(pack),new/deletearray cookies,__builtin_clear_paddingmasks, unlowered C++ entity mangling, C++20 module initializer guards, construction vtables (_ZTC), MSVCvtordispthunks and_ThrowInfo, full MSVC__asmparsing, DWARF v5 macros/fragments/inlinedAt, and multi-TU ThinLTO/FullLTO linking.dev_tools/check_llvm_be_coverage.pyand expanded the unit test suite to achieve 100.00% function, line, region, branch, and Doxygen coverage.6. Testing, Fuzzing, & 100% Coverage Verification
Unit & Integration Test Suite (
tests/)The branch includes 29 standalone C++ test executables (
27,486 linesof test code intests/test_llvm_*.cpp) plus differential fuzzing and integration suites:test_llvm_expressionstests/test_llvm_expressions.cppnew/deletecookies, calls, atomics, fold expressions, fixed-point, UBSantest_llvm_declarationstests/test_llvm_declarations.cpp__tls_init, local static guards,global_ctors/dtors,.CRT$XCU, C++20 modules, unlowered Itanium/MSVC manglingtest_llvm_abitests/test_llvm_abi.cppsret,byval,va_argtest_llvm_Control_Flowtests/test_llvm_control_flow.cppif/else,while,do-while,for,switch(case ranges),goto, computedgoto(indirectbr), VLAs, scoped RAII destructor cleanupstest_llvm_vtable_rttitests/test_llvm_vtable_rtti.cpp_ZTV/_ZTT/_ZTC,this/covariant/virtual thunks, MSVCVFTable/VBTable/vtordisp, Itanium & MSVC RTTI,dynamic_cast,typeid, devirtualizationtest_llvm_const_evaluationtests/test_llvm_const_evaluation.cppNaN/Inf/fp80/fp128/half/bfloat), UTF-8/16/32 strings, nested struct/union/array aggregates, bitfield packing, address constantstest_llvm_type_loweringtests/test_llvm_type_lowering.cpp_BitInt, vectors, complex, fixed-point, recursive/packed structs, bitfields, unions, VLAs, functions, TBAA hierarchies (!tbaa,!tbaa.struct), GPU addr spacestest_llvm_orchestratortests/test_llvm_orchestrator.cppback_end(),llvm_gen_be(),DataLayout, target triple sync, CLI options, native toolchain discovery, linker args, multi-TU ThinLTO/FullLTO linkingtest_llvm_debug_infotests/test_llvm_debug_info.cppinlinedAt, composite/template/bitfield/enum types, SROA fragments, DWARF v5 macros,DIImportedEntity,DICommonBlocktest_llvm_builtinstests/test_llvm_builtins.cppbit_cast,offsetof,shufflevector,convertvector,__builtin_clear_padding,source_location,__uuidoftest_llvm_exceptionstests/test_llvm_exceptions.cpplandingpad/__cxa_throw/__cxa_begin_catch/noexceptterminate/dynamic specs, Windows SEHcatchswitch/catchpad/cleanuppad,__leave,/EHa,_ThrowInfotest_llvm_omptests/test_llvm_omp.cppparallel,for(static/dynamic),reduction,sections,single,task/taskloop,critical,barrier,ordered,flush,atomic,simd,declare simd, GPUtargetoffloadingtest_llvm_coro_atomicstests/test_llvm_coro_atomics.cpp@llvm.coro.*intrinsics, C11/C++20 atomic operations & fencestest_llvm_decltests/test_llvm_decl.cppdik_*), and multi-TU state reset validationtest_llvm_target_intrinsicstests/test_llvm_target_intrinsics.cppSSE/AVX/AVX-512/AMX/BMI/AES/SHA), ARM/AArch64 (NEON/SVE/CRC32/Crypto/barriers/sysregs), RISC-V, PPC, s390x, LoongArch, MIPS, SPARC, Wasm SIMD128test_llvm_inline_asmtests/test_llvm_inline_asm.cppasm, multi-output structs, constraint canonicalization, indirect memory*m, register clobbers,asm goto(callbr)test_llvm_msvc_asmtests/test_llvm_msvc_asm.cpp__asmIntel syntax parser, local/global variable substitution, addressing modes, directives, clobber inferencetest_llvm_errortests/test_llvm_error.cppllvm_gen_be_error_tstatus codes,llvm_gen_be_error_context_t, source coordinate formatting, EDG front-end diagnostic bridgetest_llvm_type_translationtests/test_llvm_type_translation.cpptest_llvm_opt_pipelinetests/test_llvm_opt_pipeline.cppPassBuilder(O0–Oz), vectorizers, coroutine passes, PGO gen/use,ASan/TSan/MSan/HWASan/SafeStack/ShadowCallStacktest_llvm_codegentests/test_llvm_codegen.cppTargetMachineinitialization,.ll/.bc/.s/.oemission, Split DWARF.dwo, ThinLTO summary emissiontest_llvm_fuzz/fuzz_llvm_backendtests/test_llvm_fuzz.cppLLVMFuzzerTestOneInput)test_llvm_datalayout/lto/pgo/driver_flag/build_config/verifier/modules/stmttests/test_llvm_*.cppReproducing Build, Test, & 100% Coverage Checks Locally