Skip to content

Commit

Permalink
[mypyc] Don't explicitly assign NULL values in setup functions (#15379
Browse files Browse the repository at this point in the history
)

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.
  • Loading branch information
dosisod committed Jun 12, 2023
1 parent 4aa18ea commit 9b9272a
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion mypyc/codegen/emitclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,12 @@ def generate_setup_for_class(

for base in reversed(cl.base_mro):
for attr, rtype in base.attributes.items():
emitter.emit_line(rf"self->{emitter.attr(attr)} = {emitter.c_undefined_value(rtype)};")
value = emitter.c_undefined_value(rtype)

# We don't need to set this field to NULL since tp_alloc() already
# zero-initializes `self`.
if value != "NULL":
emitter.emit_line(rf"self->{emitter.attr(attr)} = {value};")

# Initialize attributes to default values, if necessary
if defaults_fn is not None:
Expand Down

0 comments on commit 9b9272a

Please sign in to comment.