TypeTrees for Autodiff
What are TypeTrees?
Memory layout descriptors for Enzyme. Tell Enzyme exactly how types are structured in memory so it can compute derivatives efficiently.
Structure
TypeTree
Type
Example: fn compute(x: &f32, data: &[f32]) -> f32
Input 0: x: &f32
TypeTree
Input 1: data: &[f32]
TypeTree
Output: f32
TypeTree
Why Needed?
- Enzyme can’t deduce complex type layouts from LLVM IR
- Prevents slow memory pattern analysis
- Enables correct derivative computation for nested structures
- Tells Enzyme which bytes are differentiable vs metadata
What Enzyme Does With This Information:
Without TypeTrees:
; Enzyme sees generic LLVM IR:
define float @distance(ptr %p1, ptr %p2) {
; Has to guess what these pointers point to
; Slow analysis of all memory operations
; May miss optimization opportunities
}
With TypeTrees:
define "enzyme_type"="{[-1]:Float@float}" float @distance(
ptr "enzyme_type"="{[-1]:Pointer, [-1,0]:Float@float}" %p1,
ptr "enzyme_type"="{[-1]:Pointer, [-1,0]:Float@float}" %p2
) {
; Enzyme knows exact type layout
; Can generate efficient derivative code directly
}
TypeTrees - Offset and -1 Explained
Type Structure
Type
Offset Values
Regular Offset (0, 4, 8, etc.)
Specific byte position within a structure
TypeTree for &Point (internal representation):
TypeTree
Generates LLVM
"enzyme_type"="{[-1]:Pointer, [-1,0]:Float@float, [-1,4]:Float@float, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer}"
Offset -1 (Special: “Everywhere”)
Means “this pattern repeats for ALL elements”
Example 1: Direct Array [f32; 100] (no pointer indirection)
TypeTree
Generates LLVM: "enzyme_type"="{[-1]:Float@float}"
Example 1b: Array Reference &[f32; 100] (with pointer indirection)
TypeTree
Generates LLVM: "enzyme_type"="{[-1]:Pointer, [-1,-1]:Float@float}"
Instead of listing 100 separate Types with offsets 0,4,8,12...396
Example 2: Slice &[i32]
// Pointer to slice data
TypeTree
Generates LLVM: "enzyme_type"="{[-1]:Pointer, [-1,-1]:Integer}"
Example 3: Mixed Structure
TypeTree
Key Distinction: Single Values vs Arrays
Single Values use offset 0 for precision:
&f32has exactly one f32 value at offset 0- More precise than using -1 (“everywhere”)
- Generates:
{[-1]:Pointer, [-1,0]:Float@float}
Arrays use offset -1 for efficiency:
&[f32; 100]has the same pattern repeated 100 times- Using -1 avoids listing 100 separate offsets
- Generates:
{[-1]:Pointer, [-1,-1]:Float@float}