-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathsetobj.py
1711 lines (1346 loc) · 55.9 KB
/
setobj.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Support for native homogeneous sets.
"""
import collections
import contextlib
import math
import operator
from functools import cached_property
from llvmlite import ir
from numba.core import types, typing, cgutils
from numba.core.imputils import (lower_builtin, lower_cast,
iternext_impl, impl_ret_borrowed,
impl_ret_new_ref, impl_ret_untracked,
for_iter, call_len, RefType)
from numba.misc import quicksort
from numba.cpython import slicing
from numba.core.errors import NumbaValueError, TypingError
from numba.core.extending import overload, overload_method, intrinsic
def get_payload_struct(context, builder, set_type, ptr):
"""
Given a set value and type, get its payload structure (as a
reference, so that mutations are seen by all).
"""
payload_type = types.SetPayload(set_type)
ptrty = context.get_data_type(payload_type).as_pointer()
payload = builder.bitcast(ptr, ptrty)
return context.make_data_helper(builder, payload_type, ref=payload)
def get_entry_size(context, set_type):
"""
Return the entry size for the given set type.
"""
llty = context.get_data_type(types.SetEntry(set_type))
return context.get_abi_sizeof(llty)
# Note these values are special:
# - EMPTY is obtained by issuing memset(..., 0xFF)
# - (unsigned) EMPTY > (unsigned) DELETED > any other hash value
EMPTY = -1
DELETED = -2
FALLBACK = -43
# Minimal size of entries table. Must be a power of 2!
MINSIZE = 16
# Number of cache-friendly linear probes before switching to non-linear probing
LINEAR_PROBES = 3
DEBUG_ALLOCS = False
def get_hash_value(context, builder, typ, value):
"""
Compute the hash of the given value.
"""
typingctx = context.typing_context
fnty = typingctx.resolve_value_type(hash)
sig = fnty.get_call_type(typingctx, (typ,), {})
fn = context.get_function(fnty, sig)
h = fn(builder, (value,))
# Fixup reserved values
is_ok = is_hash_used(context, builder, h)
fallback = ir.Constant(h.type, FALLBACK)
return builder.select(is_ok, h, fallback)
@intrinsic
def _get_hash_value_intrinsic(typingctx, value):
def impl(context, builder, typ, args):
return get_hash_value(context, builder, value, args[0])
fnty = typingctx.resolve_value_type(hash)
sig = fnty.get_call_type(typingctx, (value,), {})
return sig, impl
def is_hash_empty(context, builder, h):
"""
Whether the hash value denotes an empty entry.
"""
empty = ir.Constant(h.type, EMPTY)
return builder.icmp_unsigned('==', h, empty)
def is_hash_deleted(context, builder, h):
"""
Whether the hash value denotes a deleted entry.
"""
deleted = ir.Constant(h.type, DELETED)
return builder.icmp_unsigned('==', h, deleted)
def is_hash_used(context, builder, h):
"""
Whether the hash value denotes an active entry.
"""
# Everything below DELETED is an used entry
deleted = ir.Constant(h.type, DELETED)
return builder.icmp_unsigned('<', h, deleted)
def check_all_set(*args):
if not all([isinstance(typ, types.Set) for typ in args]):
raise TypingError(f"All arguments must be Sets, got {args}")
if not all([args[0].dtype == s.dtype for s in args]):
raise TypingError(f"All Sets must be of the same type, got {args}")
SetLoop = collections.namedtuple('SetLoop', ('index', 'entry', 'do_break'))
class _SetPayload(object):
def __init__(self, context, builder, set_type, ptr):
payload = get_payload_struct(context, builder, set_type, ptr)
self._context = context
self._builder = builder
self._ty = set_type
self._payload = payload
self._entries = payload._get_ptr_by_name('entries')
self._ptr = ptr
@property
def mask(self):
return self._payload.mask
@mask.setter
def mask(self, value):
# CAUTION: mask must be a power of 2 minus 1
self._payload.mask = value
@property
def used(self):
return self._payload.used
@used.setter
def used(self, value):
self._payload.used = value
@property
def fill(self):
return self._payload.fill
@fill.setter
def fill(self, value):
self._payload.fill = value
@property
def finger(self):
return self._payload.finger
@finger.setter
def finger(self, value):
self._payload.finger = value
@property
def dirty(self):
return self._payload.dirty
@dirty.setter
def dirty(self, value):
self._payload.dirty = value
@property
def entries(self):
"""
A pointer to the start of the entries array.
"""
return self._entries
@property
def ptr(self):
"""
A pointer to the start of the NRT-allocated area.
"""
return self._ptr
def get_entry(self, idx):
"""
Get entry number *idx*.
"""
entry_ptr = cgutils.gep(self._builder, self._entries, idx)
entry = self._context.make_data_helper(self._builder,
types.SetEntry(self._ty),
ref=entry_ptr)
return entry
def _lookup(self, item, h, for_insert=False):
"""
Lookup the *item* with the given hash values in the entries.
Return a (found, entry index) tuple:
- If found is true, <entry index> points to the entry containing
the item.
- If found is false, <entry index> points to the empty entry that
the item can be written to (only if *for_insert* is true)
"""
context = self._context
builder = self._builder
intp_t = h.type
mask = self.mask
dtype = self._ty.dtype
tyctx = context.typing_context
fnty = tyctx.resolve_value_type(operator.eq)
sig = fnty.get_call_type(tyctx, (dtype, dtype), {})
eqfn = context.get_function(fnty, sig)
one = ir.Constant(intp_t, 1)
five = ir.Constant(intp_t, 5)
# The perturbation value for probing
perturb = cgutils.alloca_once_value(builder, h)
# The index of the entry being considered: start with (hash & mask)
index = cgutils.alloca_once_value(builder,
builder.and_(h, mask))
if for_insert:
# The index of the first deleted entry in the lookup chain
free_index_sentinel = mask.type(-1) # highest unsigned index
free_index = cgutils.alloca_once_value(builder, free_index_sentinel)
bb_body = builder.append_basic_block("lookup.body")
bb_found = builder.append_basic_block("lookup.found")
bb_not_found = builder.append_basic_block("lookup.not_found")
bb_end = builder.append_basic_block("lookup.end")
def check_entry(i):
"""
Check entry *i* against the value being searched for.
"""
entry = self.get_entry(i)
entry_hash = entry.hash
with builder.if_then(builder.icmp_unsigned('==', h, entry_hash)):
# Hashes are equal, compare values
# (note this also ensures the entry is used)
eq = eqfn(builder, (item, entry.key))
with builder.if_then(eq):
builder.branch(bb_found)
with builder.if_then(is_hash_empty(context, builder, entry_hash)):
builder.branch(bb_not_found)
if for_insert:
# Memorize the index of the first deleted entry
with builder.if_then(is_hash_deleted(context, builder, entry_hash)):
j = builder.load(free_index)
j = builder.select(builder.icmp_unsigned('==', j, free_index_sentinel),
i, j)
builder.store(j, free_index)
# First linear probing. When the number of collisions is small,
# the lineary probing loop achieves better cache locality and
# is also slightly cheaper computationally.
with cgutils.for_range(builder, ir.Constant(intp_t, LINEAR_PROBES)):
i = builder.load(index)
check_entry(i)
i = builder.add(i, one)
i = builder.and_(i, mask)
builder.store(i, index)
# If not found after linear probing, switch to a non-linear
# perturbation keyed on the unmasked hash value.
# XXX how to tell LLVM this branch is unlikely?
builder.branch(bb_body)
with builder.goto_block(bb_body):
i = builder.load(index)
check_entry(i)
# Perturb to go to next entry:
# perturb >>= 5
# i = (i * 5 + 1 + perturb) & mask
p = builder.load(perturb)
p = builder.lshr(p, five)
i = builder.add(one, builder.mul(i, five))
i = builder.and_(mask, builder.add(i, p))
builder.store(i, index)
builder.store(p, perturb)
# Loop
builder.branch(bb_body)
with builder.goto_block(bb_not_found):
if for_insert:
# Not found => for insertion, return the index of the first
# deleted entry (if any), to avoid creating an infinite
# lookup chain (issue #1913).
i = builder.load(index)
j = builder.load(free_index)
i = builder.select(builder.icmp_unsigned('==', j, free_index_sentinel),
i, j)
builder.store(i, index)
builder.branch(bb_end)
with builder.goto_block(bb_found):
builder.branch(bb_end)
builder.position_at_end(bb_end)
found = builder.phi(ir.IntType(1), 'found')
found.add_incoming(cgutils.true_bit, bb_found)
found.add_incoming(cgutils.false_bit, bb_not_found)
return found, builder.load(index)
@contextlib.contextmanager
def _iterate(self, start=None):
"""
Iterate over the payload's entries. Yield a SetLoop.
"""
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
one = ir.Constant(intp_t, 1)
size = builder.add(self.mask, one)
with cgutils.for_range(builder, size, start=start) as range_loop:
entry = self.get_entry(range_loop.index)
is_used = is_hash_used(context, builder, entry.hash)
with builder.if_then(is_used):
loop = SetLoop(index=range_loop.index, entry=entry,
do_break=range_loop.do_break)
yield loop
@contextlib.contextmanager
def _next_entry(self):
"""
Yield a random entry from the payload. Caller must ensure the
set isn't empty, otherwise the function won't end.
"""
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
zero = ir.Constant(intp_t, 0)
one = ir.Constant(intp_t, 1)
mask = self.mask
# Start walking the entries from the stored "search finger" and
# break as soon as we find a used entry.
bb_body = builder.append_basic_block('next_entry_body')
bb_end = builder.append_basic_block('next_entry_end')
index = cgutils.alloca_once_value(builder, self.finger)
builder.branch(bb_body)
with builder.goto_block(bb_body):
i = builder.load(index)
# ANDing with mask ensures we stay inside the table boundaries
i = builder.and_(mask, builder.add(i, one))
builder.store(i, index)
entry = self.get_entry(i)
is_used = is_hash_used(context, builder, entry.hash)
builder.cbranch(is_used, bb_end, bb_body)
builder.position_at_end(bb_end)
# Update the search finger with the next position. This avoids
# O(n**2) behaviour when pop() is called in a loop.
i = builder.load(index)
self.finger = i
yield self.get_entry(i)
class SetInstance(object):
def __init__(self, context, builder, set_type, set_val):
self._context = context
self._builder = builder
self._ty = set_type
self._entrysize = get_entry_size(context, set_type)
self._set = context.make_helper(builder, set_type, set_val)
@property
def dtype(self):
return self._ty.dtype
@property
def payload(self):
"""
The _SetPayload for this set.
"""
# This cannot be cached as the pointer can move around!
context = self._context
builder = self._builder
ptr = self._context.nrt.meminfo_data(builder, self.meminfo)
return _SetPayload(context, builder, self._ty, ptr)
@property
def value(self):
return self._set._getvalue()
@property
def meminfo(self):
return self._set.meminfo
@property
def parent(self):
return self._set.parent
@parent.setter
def parent(self, value):
self._set.parent = value
def get_size(self):
"""
Return the number of elements in the size.
"""
return self.payload.used
def set_dirty(self, val):
if self._ty.reflected:
self.payload.dirty = cgutils.true_bit if val else cgutils.false_bit
def _add_entry(self, payload, entry, item, h, do_resize=True):
context = self._context
builder = self._builder
old_hash = entry.hash
entry.hash = h
self.incref_value(item)
entry.key = item
# used++
used = payload.used
one = ir.Constant(used.type, 1)
used = payload.used = builder.add(used, one)
# fill++ if entry wasn't a deleted one
with builder.if_then(is_hash_empty(context, builder, old_hash),
likely=True):
payload.fill = builder.add(payload.fill, one)
# Grow table if necessary
if do_resize:
self.upsize(used)
self.set_dirty(True)
def _add_key(self, payload, item, h, do_resize=True, do_incref=True):
context = self._context
builder = self._builder
found, i = payload._lookup(item, h, for_insert=True)
not_found = builder.not_(found)
with builder.if_then(not_found):
# Not found => add it
entry = payload.get_entry(i)
old_hash = entry.hash
entry.hash = h
if do_incref:
self.incref_value(item)
entry.key = item
# used++
used = payload.used
one = ir.Constant(used.type, 1)
used = payload.used = builder.add(used, one)
# fill++ if entry wasn't a deleted one
with builder.if_then(is_hash_empty(context, builder, old_hash),
likely=True):
payload.fill = builder.add(payload.fill, one)
# Grow table if necessary
if do_resize:
self.upsize(used)
self.set_dirty(True)
def _remove_entry(self, payload, entry, do_resize=True, do_decref=True):
# Mark entry deleted
entry.hash = ir.Constant(entry.hash.type, DELETED)
if do_decref:
self.decref_value(entry.key)
# used--
used = payload.used
one = ir.Constant(used.type, 1)
used = payload.used = self._builder.sub(used, one)
# Shrink table if necessary
if do_resize:
self.downsize(used)
self.set_dirty(True)
def _remove_key(self, payload, item, h, do_resize=True):
context = self._context
builder = self._builder
found, i = payload._lookup(item, h)
with builder.if_then(found):
entry = payload.get_entry(i)
self._remove_entry(payload, entry, do_resize)
return found
def add(self, item, do_resize=True):
context = self._context
builder = self._builder
payload = self.payload
h = get_hash_value(context, builder, self._ty.dtype, item)
self._add_key(payload, item, h, do_resize)
def add_pyapi(self, pyapi, item, do_resize=True):
"""A version of .add for use inside functions following Python calling
convention.
"""
context = self._context
builder = self._builder
payload = self.payload
h = self._pyapi_get_hash_value(pyapi, context, builder, item)
self._add_key(payload, item, h, do_resize)
def _pyapi_get_hash_value(self, pyapi, context, builder, item):
"""Python API compatible version of `get_hash_value()`.
"""
argtypes = [self._ty.dtype]
resty = types.intp
def wrapper(val):
return _get_hash_value_intrinsic(val)
args = [item]
sig = typing.signature(resty, *argtypes)
is_error, retval = pyapi.call_jit_code(wrapper, sig, args)
# Handle return status
with builder.if_then(is_error, likely=False):
# Raise nopython exception as a Python exception
builder.ret(pyapi.get_null_object())
return retval
def contains(self, item):
context = self._context
builder = self._builder
payload = self.payload
h = get_hash_value(context, builder, self._ty.dtype, item)
found, i = payload._lookup(item, h)
return found
def discard(self, item):
context = self._context
builder = self._builder
payload = self.payload
h = get_hash_value(context, builder, self._ty.dtype, item)
found = self._remove_key(payload, item, h)
return found
def pop(self):
context = self._context
builder = self._builder
lty = context.get_value_type(self._ty.dtype)
key = cgutils.alloca_once(builder, lty)
payload = self.payload
with payload._next_entry() as entry:
builder.store(entry.key, key)
# since the value is returned don't decref in _remove_entry()
self._remove_entry(payload, entry, do_decref=False)
return builder.load(key)
def clear(self):
context = self._context
builder = self._builder
intp_t = context.get_value_type(types.intp)
minsize = ir.Constant(intp_t, MINSIZE)
self._replace_payload(minsize)
self.set_dirty(True)
def copy(self):
"""
Return a copy of this set.
"""
context = self._context
builder = self._builder
payload = self.payload
used = payload.used
fill = payload.fill
other = type(self)(context, builder, self._ty, None)
no_deleted_entries = builder.icmp_unsigned('==', used, fill)
with builder.if_else(no_deleted_entries, likely=True) \
as (if_no_deleted, if_deleted):
with if_no_deleted:
# No deleted entries => raw copy the payload
ok = other._copy_payload(payload)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot copy set",))
with if_deleted:
# Deleted entries => re-insert entries one by one
nentries = self.choose_alloc_size(context, builder, used)
ok = other._allocate_payload(nentries)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot copy set",))
other_payload = other.payload
with payload._iterate() as loop:
entry = loop.entry
other._add_key(other_payload, entry.key, entry.hash,
do_resize=False)
return other
def intersect(self, other):
"""
In-place intersection with *other* set.
"""
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
with payload._iterate() as loop:
entry = loop.entry
found, _ = other_payload._lookup(entry.key, entry.hash)
with builder.if_then(builder.not_(found)):
self._remove_entry(payload, entry, do_resize=False)
# Final downsize
self.downsize(payload.used)
def difference(self, other):
"""
In-place difference with *other* set.
"""
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
with other_payload._iterate() as loop:
entry = loop.entry
self._remove_key(payload, entry.key, entry.hash, do_resize=False)
# Final downsize
self.downsize(payload.used)
def symmetric_difference(self, other):
"""
In-place symmetric difference with *other* set.
"""
context = self._context
builder = self._builder
other_payload = other.payload
with other_payload._iterate() as loop:
key = loop.entry.key
h = loop.entry.hash
# We must reload our payload as it may be resized during the loop
payload = self.payload
found, i = payload._lookup(key, h, for_insert=True)
entry = payload.get_entry(i)
with builder.if_else(found) as (if_common, if_not_common):
with if_common:
self._remove_entry(payload, entry, do_resize=False)
with if_not_common:
self._add_entry(payload, entry, key, h)
# Final downsize
self.downsize(self.payload.used)
def issubset(self, other, strict=False):
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
cmp_op = '<' if strict else '<='
res = cgutils.alloca_once_value(builder, cgutils.true_bit)
with builder.if_else(
builder.icmp_unsigned(cmp_op, payload.used, other_payload.used)
) as (if_smaller, if_larger):
with if_larger:
# self larger than other => self cannot possibly a subset
builder.store(cgutils.false_bit, res)
with if_smaller:
# check whether each key of self is in other
with payload._iterate() as loop:
entry = loop.entry
found, _ = other_payload._lookup(entry.key, entry.hash)
with builder.if_then(builder.not_(found)):
builder.store(cgutils.false_bit, res)
loop.do_break()
return builder.load(res)
def isdisjoint(self, other):
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
res = cgutils.alloca_once_value(builder, cgutils.true_bit)
def check(smaller, larger):
# Loop over the smaller of the two, and search in the larger
with smaller._iterate() as loop:
entry = loop.entry
found, _ = larger._lookup(entry.key, entry.hash)
with builder.if_then(found):
builder.store(cgutils.false_bit, res)
loop.do_break()
with builder.if_else(
builder.icmp_unsigned('>', payload.used, other_payload.used)
) as (if_larger, otherwise):
with if_larger:
# len(self) > len(other)
check(other_payload, payload)
with otherwise:
# len(self) <= len(other)
check(payload, other_payload)
return builder.load(res)
def equals(self, other):
context = self._context
builder = self._builder
payload = self.payload
other_payload = other.payload
res = cgutils.alloca_once_value(builder, cgutils.true_bit)
with builder.if_else(
builder.icmp_unsigned('==', payload.used, other_payload.used)
) as (if_same_size, otherwise):
with if_same_size:
# same sizes => check whether each key of self is in other
with payload._iterate() as loop:
entry = loop.entry
found, _ = other_payload._lookup(entry.key, entry.hash)
with builder.if_then(builder.not_(found)):
builder.store(cgutils.false_bit, res)
loop.do_break()
with otherwise:
# different sizes => cannot possibly be equal
builder.store(cgutils.false_bit, res)
return builder.load(res)
@classmethod
def allocate_ex(cls, context, builder, set_type, nitems=None):
"""
Allocate a SetInstance with its storage.
Return a (ok, instance) tuple where *ok* is a LLVM boolean and
*instance* is a SetInstance object (the object's contents are
only valid when *ok* is true).
"""
intp_t = context.get_value_type(types.intp)
if nitems is None:
nentries = ir.Constant(intp_t, MINSIZE)
else:
if isinstance(nitems, int):
nitems = ir.Constant(intp_t, nitems)
nentries = cls.choose_alloc_size(context, builder, nitems)
self = cls(context, builder, set_type, None)
ok = self._allocate_payload(nentries)
return ok, self
@classmethod
def allocate(cls, context, builder, set_type, nitems=None):
"""
Allocate a SetInstance with its storage. Same as allocate_ex(),
but return an initialized *instance*. If allocation failed,
control is transferred to the caller using the target's current
call convention.
"""
ok, self = cls.allocate_ex(context, builder, set_type, nitems)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot allocate set",))
return self
@classmethod
def from_meminfo(cls, context, builder, set_type, meminfo):
"""
Allocate a new set instance pointing to an existing payload
(a meminfo pointer).
Note the parent field has to be filled by the caller.
"""
self = cls(context, builder, set_type, None)
self._set.meminfo = meminfo
self._set.parent = context.get_constant_null(types.pyobject)
context.nrt.incref(builder, set_type, self.value)
# Payload is part of the meminfo, no need to touch it
return self
@classmethod
def choose_alloc_size(cls, context, builder, nitems):
"""
Choose a suitable number of entries for the given number of items.
"""
intp_t = nitems.type
one = ir.Constant(intp_t, 1)
minsize = ir.Constant(intp_t, MINSIZE)
# Ensure number of entries >= 2 * used
min_entries = builder.shl(nitems, one)
# Find out first suitable power of 2, starting from MINSIZE
size_p = cgutils.alloca_once_value(builder, minsize)
bb_body = builder.append_basic_block("calcsize.body")
bb_end = builder.append_basic_block("calcsize.end")
builder.branch(bb_body)
with builder.goto_block(bb_body):
size = builder.load(size_p)
is_large_enough = builder.icmp_unsigned('>=', size, min_entries)
with builder.if_then(is_large_enough, likely=False):
builder.branch(bb_end)
next_size = builder.shl(size, one)
builder.store(next_size, size_p)
builder.branch(bb_body)
builder.position_at_end(bb_end)
return builder.load(size_p)
def upsize(self, nitems):
"""
When adding to the set, ensure it is properly sized for the given
number of used entries.
"""
context = self._context
builder = self._builder
intp_t = nitems.type
one = ir.Constant(intp_t, 1)
two = ir.Constant(intp_t, 2)
payload = self.payload
# Ensure number of entries >= 2 * used
min_entries = builder.shl(nitems, one)
size = builder.add(payload.mask, one)
need_resize = builder.icmp_unsigned('>=', min_entries, size)
with builder.if_then(need_resize, likely=False):
# Find out next suitable size
new_size_p = cgutils.alloca_once_value(builder, size)
bb_body = builder.append_basic_block("calcsize.body")
bb_end = builder.append_basic_block("calcsize.end")
builder.branch(bb_body)
with builder.goto_block(bb_body):
# Multiply by 4 (ensuring size remains a power of two)
new_size = builder.load(new_size_p)
new_size = builder.shl(new_size, two)
builder.store(new_size, new_size_p)
is_too_small = builder.icmp_unsigned('>=', min_entries, new_size)
builder.cbranch(is_too_small, bb_body, bb_end)
builder.position_at_end(bb_end)
new_size = builder.load(new_size_p)
if DEBUG_ALLOCS:
context.printf(builder,
"upsize to %zd items: current size = %zd, "
"min entries = %zd, new size = %zd\n",
nitems, size, min_entries, new_size)
self._resize(payload, new_size, "cannot grow set")
def downsize(self, nitems):
"""
When removing from the set, ensure it is properly sized for the given
number of used entries.
"""
context = self._context
builder = self._builder
intp_t = nitems.type
one = ir.Constant(intp_t, 1)
two = ir.Constant(intp_t, 2)
minsize = ir.Constant(intp_t, MINSIZE)
payload = self.payload
# Ensure entries >= max(2 * used, MINSIZE)
min_entries = builder.shl(nitems, one)
min_entries = builder.select(builder.icmp_unsigned('>=', min_entries, minsize),
min_entries, minsize)
# Shrink only if size >= 4 * min_entries && size > MINSIZE
max_size = builder.shl(min_entries, two)
size = builder.add(payload.mask, one)
need_resize = builder.and_(
builder.icmp_unsigned('<=', max_size, size),
builder.icmp_unsigned('<', minsize, size))
with builder.if_then(need_resize, likely=False):
# Find out next suitable size
new_size_p = cgutils.alloca_once_value(builder, size)
bb_body = builder.append_basic_block("calcsize.body")
bb_end = builder.append_basic_block("calcsize.end")
builder.branch(bb_body)
with builder.goto_block(bb_body):
# Divide by 2 (ensuring size remains a power of two)
new_size = builder.load(new_size_p)
new_size = builder.lshr(new_size, one)
# Keep current size if new size would be < min_entries
is_too_small = builder.icmp_unsigned('>', min_entries, new_size)
with builder.if_then(is_too_small):
builder.branch(bb_end)
builder.store(new_size, new_size_p)
builder.branch(bb_body)
builder.position_at_end(bb_end)
# Ensure new_size >= MINSIZE
new_size = builder.load(new_size_p)
# At this point, new_size should be < size if the factors
# above were chosen carefully!
if DEBUG_ALLOCS:
context.printf(builder,
"downsize to %zd items: current size = %zd, "
"min entries = %zd, new size = %zd\n",
nitems, size, min_entries, new_size)
self._resize(payload, new_size, "cannot shrink set")
def _resize(self, payload, nentries, errmsg):
"""
Resize the payload to the given number of entries.
CAUTION: *nentries* must be a power of 2!
"""
context = self._context
builder = self._builder
# Allocate new entries
old_payload = payload
ok = self._allocate_payload(nentries, realloc=True)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
(errmsg,))
# Re-insert old entries
# No incref since they already were the first time they were inserted
payload = self.payload
with old_payload._iterate() as loop:
entry = loop.entry
self._add_key(payload, entry.key, entry.hash,
do_resize=False, do_incref=False)
self._free_payload(old_payload.ptr)
def _replace_payload(self, nentries):
"""
Replace the payload with a new empty payload with the given number
of entries.
CAUTION: *nentries* must be a power of 2!
"""
context = self._context
builder = self._builder
# decref all of the previous entries
with self.payload._iterate() as loop:
entry = loop.entry
self.decref_value(entry.key)
# Free old payload
self._free_payload(self.payload.ptr)
ok = self._allocate_payload(nentries, realloc=True)
with builder.if_then(builder.not_(ok), likely=False):
context.call_conv.return_user_exc(builder, MemoryError,
("cannot reallocate set",))
def _allocate_payload(self, nentries, realloc=False):
"""
Allocate and initialize payload for the given number of entries.
If *realloc* is True, the existing meminfo is reused.
CAUTION: *nentries* must be a power of 2!
"""
context = self._context
builder = self._builder