Skip to content

Phase 27: Complete Codegen Extensions - #46

Merged
MarcoFPO merged 3 commits into
mainfrom
feature/codegen-all-extensions
Mar 14, 2026
Merged

Phase 27: Complete Codegen Extensions#46
MarcoFPO merged 3 commits into
mainfrom
feature/codegen-all-extensions

Conversation

@MarcoFPO

Copy link
Copy Markdown
Owner

Summary

  • Struct types: Proper LLVM struct IR from field types (was falling back to i64)
  • Variant types: Tagged union layout {i32, max_payload} with accurate sizing
  • Fn types: Function pointer representation as i8*
  • Element-size-aware Load/Store: Dynamic element size from M-node type lookup (was hardcoded 8 bytes)
  • Generic computes: abs, min, max, clamp, bhaskara_approx (fixed-point sine approximation)
  • Scoped region cleanup: Zero-init frame buffers at loop iteration boundaries (only innermost scoped regions)

QA Fixes Applied

  • Array byte size uses actual element type size instead of * 8
  • Region cleanup only zeros R:frame (innermost), not R:game (which holds game state)
  • Variant payload sizing uses type_ref_byte_size for correctness
  • bhaskara_approx returns 0 on division-by-zero

Test plan

  • All 371 existing tests pass
  • Zero clippy warnings
  • snake.ftl check passes (9 PROVEN, 3 ASSUMED contracts)

🤖 Generated with Claude Code

Marco Doehler and others added 3 commits March 14, 2026 21:12
…-aware load/store

Replace fallback i64 representations with proper LLVM types:
- Struct types map to LLVM struct types with correct field layouts
- Variant types map to tagged unions (i32 tag + largest payload)
- Fn types map to i8* function pointers
- Load/Store operations now compute element sizes from M-node type info
- type_ref_byte_size updated to handle struct (sum of fields) and variant (tag + max payload)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…) and scoped region cleanup

Extend emit_generic_compute with five new operations: abs (absolute value),
min/max (signed integer comparison), clamp (three-input bounded range), and
bhaskara_approx (fixed-point Bhaskara sine approximation for graphics/games).
Add emit_scoped_region_cleanup to zero-initialize scoped region memory at the
start of each loop iteration, ensuring frame buffers are reset between cycles.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…riant sizing, bhaskara div-by-zero

- Array byte size now uses element type size instead of hardcoded *8
- Scoped region cleanup only zeros innermost (frame) regions, not game state
- Variant max-payload uses type_ref_byte_size for accurate sizing
- bhaskara_approx returns 0 on division-by-zero instead of numerator/1

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@MarcoFPO
MarcoFPO merged commit 2a8fffb into main Mar 14, 2026
1 check passed
@MarcoFPO
MarcoFPO deleted the feature/codegen-all-extensions branch March 14, 2026 21:19
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the code generation capabilities by introducing more accurate and robust type representations for complex data structures like structs, variants, and function pointers. It also improves memory management through dynamic element sizing and scoped region cleanup, and expands the set of supported generic compute operations, leading to a more complete and reliable code generation pipeline.

Highlights

  • Type Representation: Implemented proper LLVM IR generation for Struct, Variant (tagged unions), and Fn types, moving away from generic i64 representation.
  • Dynamic Memory Sizing: Introduced dynamic calculation of element sizes for memory operations, replacing hardcoded values and improving accuracy for arrays, structs, and variants.
  • Scoped Region Cleanup: Added functionality to zero-initialize memory for innermost frame-scoped regions at loop iteration boundaries, enhancing memory safety.
  • New Generic Computes: Extended the code generator with support for abs, min, max, clamp, and bhaskara_approx (fixed-point sine approximation) operations.
  • QA Fixes: Addressed several quality assurance issues, including correct array byte sizing, precise variant payload sizing, and a division-by-zero guard for bhaskara_approx.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • flux-ftl/src/codegen.rs
    • Refactored type representation logic for structs, variants, and function types.
    • Updated byte size calculation for various types, including arrays, structs, and variants.
    • Introduced a new utility function to determine memory element sizes dynamically.
    • Modified memory load and store operations to utilize dynamic element sizing.
    • Integrated scoped region cleanup into loop generation.
    • Implemented a new function for zero-initializing scoped region memory.
    • Added support for several new generic compute operations: abs, min, max, clamp, and bhaskara_approx.
Activity
  • No human activity has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly enhances the codegen capabilities by adding proper LLVM IR generation for structs, variants, and function types, and by making memory operations element-size aware. It also introduces several useful generic compute functions and scoped region cleanup. The changes are substantial and well-structured.

My review focuses on a few areas related to correctness and performance:

  • Correctness of type size calculations, especially for structs with padding and for pointer types on different architectures.
  • Performance of lookup operations in newly added helper functions.
  • Efficiency of the implementation for scoped region cleanup.

Overall, this is a great step forward for the project. Addressing the identified issues will improve the robustness and performance of the code generator.

Comment thread flux-ftl/src/codegen.rs
Comment on lines +637 to +640
TypeBody::Struct { fields, .. } => fields
.iter()
.map(|f| self.type_ref_byte_size(&f.type_ref))
.sum(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current size calculation for TypeBody::Struct sums the sizes of its fields. This is incorrect as it ignores padding that LLVM may add for alignment, especially for non-packed structs (which are the default). This can lead to incorrect memory allocations and subtle bugs.

To fix this, you should get the size from the LLVM type itself using the module's DataLayout. A possible approach is:

if let Some(llvm_type) = self.type_body_to_llvm(&td.body) {
    let data_layout = self.module.get_data_layout();
    return data_layout.get_store_size(&llvm_type);
}

However, be aware of potential circular dependencies between type_ref_byte_size and type_body_to_llvm. You might need to introduce memoization or refactor the size calculation to resolve this.

Comment thread flux-ftl/src/codegen.rs
.unwrap_or(0)
}
_ => 8,
TypeBody::Fn { .. } => 8, // pointer size

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The size of a function pointer (TypeBody::Fn) is hardcoded to 8 bytes. This is incorrect for 32-bit targets like wasm32, where pointers are 4 bytes. This will cause incorrect size calculations for types containing function pointers.

Suggested change
TypeBody::Fn { .. } => 8, // pointer size
TypeBody::Fn { .. } => self.module.get_data_layout().get_pointer_size() as u64, // pointer size

Comment thread flux-ftl/src/codegen.rs
Comment on lines +658 to +674
fn get_memory_element_size(&self, mem_node_id: &str) -> u64 {
for mem in &self.program.memories {
if mem.id.0 == mem_node_id
&& let MemoryOp::Alloc { type_ref, .. } = &mem.op
{
if let TypeRef::Id { node } = type_ref
&& let Some(td) =
self.program.types.iter().find(|t| t.id.0 == node.0)
&& let TypeBody::Array { element, .. } = &td.body
{
return self.type_ref_byte_size(element);
}
return self.type_ref_byte_size(type_ref);
}
}
8 // fallback
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function performs a linear scan over self.program.memories on every call, which is inefficient. The CodeGenerator already has a memory_map HashMap that should be used for an O(1) lookup instead.

Additionally, the fallback value of 8 is a magic number and will be incorrect on 32-bit targets. This should be replaced with a target-aware pointer size.

    fn get_memory_element_size(&self, mem_node_id: &str) -> u64 {
        if let Some(mem) = self.memory_map.get(mem_node_id) {
            if let MemoryOp::Alloc { type_ref, .. } = &mem.op
            {
                if let TypeRef::Id { node } = type_ref
                    && let Some(td) =
                        self.program.types.iter().find(|t| t.id.0 == node.0)
                    && let TypeBody::Array { element, .. } = &td.body
                {
                    return self.type_ref_byte_size(element);
                }
                return self.type_ref_byte_size(type_ref);
            }
        }
        self.module.get_data_layout().get_pointer_size() as u64 // fallback
    }

Comment thread flux-ftl/src/codegen.rs
Comment on lines +1101 to +1104
fn emit_scoped_region_cleanup(
&self,
builder: &inkwell::builder::Builder<'ctx>,
) -> Result<(), CodegenError> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function has a couple of areas for performance improvement:

  1. The logic to find outer_scoped_ids involves a nested loop (iter().filter() containing iter().any()), which results in O(N^2) complexity where N is the number of regions. This can be optimized to O(N) by first building a HashMap of regions for quick parent lookups.
  2. The call to builder.build_memset uses a hardcoded alignment of 1. This is functionally correct but can be very inefficient. You should provide a more appropriate alignment, such as the alignment of the allocated type, to allow for more optimized memset implementations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant