Module Sarek_codegen.Sarek_ir_c_arith

Wrapping signed integer arithmetic for the C-family emitters (CUDA C, which HIP also compiles, OpenCL C and MSL).

Rule. Sarek integers follow OCaml: int32 and int64 +, -, *, unary - and lsl wrap modulo 232 / 264, as the Interpreter and Native backends compute them (Int32.add, Int64.mul, ...). In C, CUDA C, OpenCL C and MSL signed +, -, * and unary - are undefined behaviour on overflow, which a compiler may assume never happens; so is lsl of a negative value in C and in C++ before C++20 (CUDA C, MSL). OpenCL C defines its shifts as bit operations on the low bits of the count, so lsl goes through the unsigned type there only for uniformity. The C-family emitters therefore print these operators on signed integer operands through the unsigned type of the same width, where they are defined modulo 2n, and convert the result back:

The Int32/Int64 stdlib intrinsics add, sub, mul, neg and shift_left use the same forms in their device templates.

The way back is a bit reinterpretation in OpenCL C (as_int, as_long) and MSL (as_type<int>, as_type<long>), so the result's bits are the unsigned result's. CUDA C uses a cast: converting an out-of-range unsigned value is implementation-defined before C++20, and nvcc/NVRTC and clang (HIP) define it as reduction modulo 2n, which C++20 made normative.

PTX (add.u32, mul.lo.u32, neg.s32 on registers) and GLSL/WGSL (whose integer arithmetic is defined to wrap) already wrap and do not use this module.

Scope. Every Add/Sub/Mul/Shl node and every Neg whose operand types are known signed integers, whoever built the node: the user's kernel or a compiler pass (fusion, matrix rewrite, ...); the IR does not tell them apart. Not affected:

Index arithmetic. The +, -, * and lsl chain at the root of an array subscript (a.(y * w + x - 1)), of a cooperative-matrix load/store offset or stride, and of a for bound (for i = 0 to k - 1) keeps C's signed operators. The no-overflow assumption is what lets the compiler fold address arithmetic (clang merges a 3x3 stencil's adjacent loads into global_load_b96 with immediate offsets on gfx1100 only with it: 3 loads instead of 6) and compute a loop's trip count; measured on the RX 7900 XTX (HIP), wrapping these positions slowed a 3x3 convolution by 10 % and the WMMA GEMMs by about 25 %, which this exemption removed. The rule is therefore the one Sarek_ir_for_bound already states for a for bound of max_int: a kernel whose index arithmetic overflows int32 is outside the contract on the C-family backends (an overflowing subscript is anyway an out-of-range index unless a later operation wraps it back).

An immutable let whose every use is index arithmetic is index arithmetic too: in let off = row * k + i * 4 in a.(off) the definition of off keeps C's operators, as if it were written in the subscript (wrapping it cost an extra sign extension and 64-bit address add per iteration on gfx1100 instead of an immediate-offset load). The set is the greatest one closed under this rule (a let used only in another index let's definition qualifies); a name bound more than once anywhere in the kernel and its helpers, a mutable let and a let with any other use are excluded.

Only the root chain is exempt: an operand that is anything else (a load, a call, land, /, a let with other uses) is printed by the general rule, so a.((h * 31 + c) land mask) still hashes with wrapping.

Typing. The IR does not annotate an operator with its type, so int_width reconstructs it from variables, literals, casts, array element types (resolved in the function being emitted: the kernel and each helper have their own arrays), record fields, variant payloads read through v.data.C_v, helper return types and intrinsic signatures. Each emitted node is typed once: every emitted node goes through visit, which hands its typing down to the children the emitter prints (Sarek_ir_c_types). When an operand's type cannot be determined the operator is printed as before (plain C), which is the only safe choice when it might be a float.

type width = Sarek_ir_c_types.width =
  1. | W32
  2. | W64

Signed integer widths. W32 covers every operand C promotes to int (int32, bool, 8-bit storage).

Operand types of one function (its arrays) and of the kernel (record and variant layouts, helper return types, index lets).

val env_of_kernel : ?records:(string * (string * Sarek_ir_types.elttype) list) list -> Sarek_ir_types.kernel -> env

The kernel body's environment. records (the ~types table the emitter declares its structs from) takes precedence over k.kern_types.

val for_helper : env -> Sarek_ir_types.helper_func -> env

The environment of helper hf: its own arrays, the kernel's layouts.

val visit : env -> Sarek_ir_types.expr -> (unit -> unit) -> unit

visit env e emit runs emit (which prints e) with e's typing available to the arms that print e's children. Every C emitter routes each expression node through it, so each node is typed once.

val empty : unit -> env

No knowledge: only literals, variables and casts are typed.

val typing_steps : env -> int

Nodes typed so far with this environment (and the environments derived from it): each emitted node is typed once, so this grows linearly with the kernel. For tests.

val index_steps : env -> int

Worklist pops and dependency visits of the index-let propagation, linear in the number of lets. For tests.

val is_index_let : env -> Sarek_ir_types.var -> bool

is_index_let env v: v is bound once, by an immutable let of an integer value, and every use of it is index arithmetic (see Index arithmetic).

val int_width : env -> Sarek_ir_types.expr -> width option

int_width env e is the signed integer width of e's C type, or None when e is not an integer or its type cannot be determined.

binop_width env op a b is Some w when op a b must be printed wrapping: op is Add, Sub, Mul or Shl and the operands are signed integers of known types (w is their common C type; for Shl, the left operand's).

type spelling = {
  1. int32 : string;
  2. uint32 : string;
  3. int64 : string;
  4. uint64 : string;
  5. uint64_suffix : string;
    (*

    of an unsigned 64-bit literal

    *)
  6. to_int32 : string;
  7. to_int64 : string;
}

The type spellings of one C dialect, and how its unsigned result is turned back into the signed type: a cast in CUDA C, as_int/as_long in OpenCL C, as_type<int>/as_type<long> in MSL (bit reinterpretations, so no implementation-defined conversion is involved).

val cuda : spelling
val opencl : spelling
val metal : spelling
val emit_index : env -> gen_expr:(Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit) -> Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit

Print the index expression e (a subscript, a cooperative-matrix offset or stride, a for bound, an index let's initialiser): the chain of signed +, -, * and lsl at its root in plain C, everything below it with gen_expr. See Index arithmetic above.

val emit_binop_arm : env -> spelling -> gen_expr:(Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit) -> operator_text:string -> Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit

The EBinop arm of a C emitter for the node e: wrapping when binop_width says so, else (a <operator_text> b).

val emit_unop_arm : env -> spelling -> gen_expr:(Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit) -> operator_text:string -> Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit

The EUnop arm of a C emitter for the node e: a negated integer literal folded to its constant, a wrapping Neg on a signed integer, else Sarek_ir_intrinsic_dispatch.emit_unop.

val emit_let_init : env -> gen_expr:(Stdlib.Buffer.t -> Sarek_ir_types.expr -> unit) -> Stdlib.Buffer.t -> Sarek_ir_types.var -> Sarek_ir_types.expr -> unit

The initialiser of let v = e: emit_index when v is an index let, gen_expr otherwise.