Skip to content

Commit 9b9272a

Browse files
authored
[mypyc] Don't explicitly assign NULL values in setup functions (#15379)
While investigating something unrelated I stumbled across the `*_setup` functions, and I noticed that they contain a lot of code that looks like this: ```c self->abc = NULL; self->xyz = NULL; // ... ``` Something told me that assigning `NULL` to a bunch of fields is propably not needed, and when looking at the docs for `tp_alloc()` I found this reference to [`allocfunc`](https://docs.python.org/3/c-api/typeobj.html#c.allocfunc), the typedef for `tp_alloc()`: > It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, ***and initialized to zeros***, ... Emphasis is mine. Basically I added a simple check that removes lines that assigns `NULL` values in setup functions. This removes about ~4100 lines from the C file when self-compiling.
1 parent 4aa18ea commit 9b9272a

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

mypyc/codegen/emitclass.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,12 @@ def generate_setup_for_class(
578578

579579
for base in reversed(cl.base_mro):
580580
for attr, rtype in base.attributes.items():
581-
emitter.emit_line(rf"self->{emitter.attr(attr)} = {emitter.c_undefined_value(rtype)};")
581+
value = emitter.c_undefined_value(rtype)
582+
583+
# We don't need to set this field to NULL since tp_alloc() already
584+
# zero-initializes `self`.
585+
if value != "NULL":
586+
emitter.emit_line(rf"self->{emitter.attr(attr)} = {value};")
582587

583588
# Initialize attributes to default values, if necessary
584589
if defaults_fn is not None:

0 commit comments

Comments
 (0)