forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIntegers.swift.gyb
1166 lines (977 loc) · 33.1 KB
/
Integers.swift.gyb
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
//===--- Integers.swift.gyb -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: rm -rf %t && mkdir -p %t && %S/../../utils/gyb -DWORD_BITS=%target-ptrsize %s -o %t/out.swift
// RUN: %S/../../utils/line-directive %t/out.swift -- %target-build-swift -parse-stdlib %t/out.swift -o %t/a.out
// RUN: %S/../../utils/line-directive %t/out.swift -- %target-run %t/a.out
// REQUIRES: executable_test
import Swift
%{
#
# Utility code for later in this template
#
from math import log
from string import maketrans
# Number of bits in the Builtin.Word type
word_bits = int(WORD_BITS) # int(CMAKE_SIZEOF_VOID_P) * 8
# Number of bits in integer literals.
builtinIntLiteralBits = 2048
IntLiteral = 'Int%s' % builtinIntLiteralBits
# 32-bit iOS simulator doesn't have Int128 support, so we stop at
# double-word. When we've implemented the arithmetic algorithms
# for bignum, we can go further.
fixedBitWidths = [2**x for x in range(3, 8) if 2**x <= 2*word_bits]
minFixedBits = fixedBitWidths[0]
maxFixedBits = fixedBitWidths[-1]
def capitalize(s):
return s[:1].upper() + s[1:]
class struct(object):
def __init__(self, **kw):
self.__dict__ = kw
def __repr__(self):
return 'struct(%r)' % self.__dict__
binaryArithmetic = [
struct(operator='+', name='add', llvmName='add', kind='+'),
struct(operator='-', name='subtract', llvmName='sub', kind='+'),
struct(operator='*', name='multiply', llvmName='mul', kind='*'),
struct(operator='/', name='divideBy', llvmName='div', kind='/'),
struct(
operator='%', name='remainderWhenDividedBy', llvmName='rem', kind='/')
]
binaryBitwise = [
struct(operator='&', name='and'),
struct(operator='|', name='or'),
struct(operator='^', name='xor')]
maskingShifts = [
struct(
operator='&>>', nonMaskingOperator='>>',
name='maskingShiftRight', llvmName=lambda s:['lshr','ashr'][s]),
struct(
operator='&<<', nonMaskingOperator='<<',
name='maskingShiftLeft', llvmName=lambda _: 'shl'),
]
}%
//===--- Bits for the Stdlib ----------------------------------------------===//
extension Bool {
@_transparent
public init(_ value: Builtin.Int1) {
self.init(_builtinBooleanLiteral: value)
}
@_transparent
// Renamed from _value to __value, because the deserializer crashes
// if stdlib is compiled with -sil-serialize-all (rdar://problem/23620491).
// TODO: rename it back to _value when the deserializer is fixed.
public var __value: Builtin.Int1 {
return Builtin.trunc_Int${word_bits}_Int1((self ? 1 : 0)._value)
}
}
// This should go in the stdlib separately, probably.
extension IntegerLiteralConvertible
where Self : _BuiltinIntegerLiteralConvertible {
/// Create an instance initialized to `value`.
@_transparent
public init(integerLiteral value: Self) {
self = value
}
}
infix operator &<< { associativity none precedence 160 }
infix operator &<<= { associativity right precedence 90 assignment }
infix operator &>> { associativity none precedence 160 }
infix operator &>>= { associativity right precedence 90 assignment }
@_transparent
public func _assertCond(
@autoclosure condition: () -> Bool,
@autoclosure _ message: () -> String,
file: StaticString = __FILE__, line: UInt = __LINE__) {
let ok = condition()
if _isDebugAssertConfiguration() {
precondition(ok, message, file: file, line: line)
}
Builtin.condfail((!ok).__value)
}
//===--- Prototype Implementation -----------------------------------------===//
//===----------------------------------------------------------------------===//
//===--- ArithmeticType ---------------------------------------------------===//
//===----------------------------------------------------------------------===//
public protocol ArithmeticType {
/// Initialize to zero
init()
% for x in binaryArithmetic:
// defaulted below
@warn_unused_result
func ${x.operator}(lhs: Self, rhs: Self) -> Self
// defaulted below
func ${x.operator}=(inout lhs: Self, rhs: Self)
// implementation hook
mutating func ${x.name}InPlace(rhs: Self)
% end
/// defaulted below
prefix func -(lhs: Self) -> Self
}
% for x in binaryArithmetic:
@_transparent
@warn_unused_result
public func ${x.operator} <T: ArithmeticType>(lhs: T, rhs: T) -> T {
var lhs = lhs
lhs.${x.name}InPlace(rhs)
return lhs
}
@_transparent
public func ${x.operator}= <T: ArithmeticType>(inout lhs: T, rhs: T) {
lhs.${x.name}InPlace(rhs)
}
% end
@_transparent
@warn_unused_result
public prefix func -<T: ArithmeticType>(x: T) -> T {
return T() - x
}
//===----------------------------------------------------------------------===//
//===--- IntegerType ------------------------------------------------------===//
//===----------------------------------------------------------------------===//
public typealias Word = Int${word_bits}
public typealias UWord = UInt${word_bits}
public protocol IntegerType
: Comparable, ArithmeticType,
IntegerLiteralConvertible, CustomStringConvertible {
// Dispatching through these puts less stress on the user reading
// the interface and error messages (and on the type checker) than
// does having many operator overloads.
@warn_unused_result
func isEqualTo(rhs: Self) -> Bool
@warn_unused_result
func isLessThan(rhs: Self) -> Bool
/// The number of bits required to represent our value. If `self`
/// is negative, returns the index of the least significant bit of
/// our representation such that all more-significant bits are 1.
/// Has the value -1 if `self` is 0.
var mostSignificantBit: Word { get }
@warn_unused_result
func uword(n: Word) -> UWord
mutating func replaceUWord(n: Word, with newBits: UWord)
init<T : IntegerType>(_ source: T)
init<T : IntegerType>(extendingOrTruncating source: T)
}
extension IntegerType {
/// The number of words required to represent our value. If `self`
/// is negative, returns the index of the least significant words of
/// our representation such that all more-significant words are -1.
/// Has the value -1 if `self` is 0.
@_transparent
public // transparent
var _mostSignificantWord: Word {
let msb = mostSignificantBit
return msb < 0 ? msb : msb / ${word_bits}
}
}
//===--- Homogeneous comparison -------------------------------------------===//
@_transparent
@warn_unused_result
public func == <T : IntegerType>(lhs:T, rhs: T) -> Bool {
return lhs.isEqualTo(rhs)
}
@_transparent
@warn_unused_result
public func < <T : IntegerType>(lhs: T, rhs: T) -> Bool {
return lhs.isLessThan(rhs)
}
//===--- Heterogeneous comparison -----------------------------------------===//
@_transparent
@warn_unused_result
public func == <T : IntegerType, U : IntegerType>(lhs:T, rhs: U) -> Bool {
return (lhs > 0) == (rhs > 0)
&& T(extendingOrTruncating: rhs) == lhs
&& U(extendingOrTruncating: lhs) == rhs
}
@_transparent
@warn_unused_result
public func != <T : IntegerType, U : IntegerType>(lhs:T, rhs: U) -> Bool {
return !(lhs == rhs)
}
@_transparent
@warn_unused_result
public func < <T : IntegerType, U : IntegerType>(lhs: T, rhs: U) -> Bool {
let lhsSign = lhs < 0 ? -1 : lhs > 0 ? 1 : 0
let rhsSign = rhs < 0 ? -1 : rhs > 0 ? 1 : 0
if lhsSign != rhsSign { return lhsSign < rhsSign }
// if we get here, lhs and rhs have the same sign. If they're
// negative, then T and U are both signed types, and one of them can
// represent values of the other type. Otherwise, lhs and rhs are
// positive, and one of T, U may be signed and the other unsigned.
// In this case, we can conceptually subtract 1 from the bitWidth of
// any signed type, and either the resulting bitWidths are the same
// or one can represent every value of the other.
let rT = T(extendingOrTruncating: rhs)
// Can we round-trip rhs through T?
if U(extendingOrTruncating: rT) == rhs {
return lhs < rT
}
return U(extendingOrTruncating: lhs) < rhs
}
@inline(__always)
@warn_unused_result
public func <= <T : IntegerType, U : IntegerType>(lhs: T, rhs: U) -> Bool {
return !(rhs < lhs)
}
@inline(__always)
@warn_unused_result
public func >= <T : IntegerType, U : IntegerType>(lhs: T, rhs: U) -> Bool {
return !(lhs < rhs)
}
@inline(__always)
@warn_unused_result
public func > <T : IntegerType, U : IntegerType>(lhs: T, rhs: U) -> Bool {
return rhs < lhs
}
//===--- Ambiguity breakers -----------------------------------------------===//
// These two versions of the operators are not ordered with respect to
// one another:
//
// <T : Comparable>(T,T) -> Bool
// <T : IntegerType, U : IntegerType>(T,U) -> Bool
//
// so we define:
//
// <T : IntegerType>(T,T) -> Bool
@inline(__always)
@warn_unused_result
public func <= <T : IntegerType>(lhs: T, rhs: T) -> Bool {
return !(rhs < lhs)
}
@inline(__always)
@warn_unused_result
public func >= <T : IntegerType>(lhs: T, rhs: T) -> Bool {
return !(lhs < rhs)
}
@inline(__always)
@warn_unused_result
public func > <T : IntegerType>(lhs: T, rhs: T) -> Bool {
return rhs < lhs
}
//===----------------------------------------------------------------------===//
//===--- FixedWidthIntegerType --------------------------------------------===//
//===----------------------------------------------------------------------===//
public enum ArithmeticOverflow { case None, Overflow }
public protocol FixedWidthIntegerType : IntegerType {
static var bitWidth : Word { get }
% for x in binaryArithmetic:
%{
comment = '''
/// Return a pair consisting of `self` ${x.operator} `rhs`,
/// truncated to fit if necessary, and a flag indicating whether an
/// arithmetic overflow occurred.''' + ('''
///
/// Requires: `rhs != 0`''' if x.kind == '/' else '')
}%
${comment}
@warn_unused_result
func ${x.name}WithOverflow(
rhs: Self
) -> (partialValue: Self, overflow: ArithmeticOverflow)
% end
static var max: Self { get }
static var min: Self { get }
% for x in binaryBitwise + maskingShifts:
@warn_unused_result
func ${x.name}(rhs: Self) -> Self
% end
@warn_unused_result
func countLeadingZeros() -> Word
init(_truncatingBits bits: UWord)
var _lowUWord: UWord { get }
}
% for x in binaryBitwise:
@warn_unused_result
@_transparent
public func ${x.operator} <T: FixedWidthIntegerType>(lhs: T, rhs: T) -> T {
return lhs.${x.name}(rhs)
}
@_transparent
public func ${x.operator}= <T: FixedWidthIntegerType>(inout lhs: T, rhs: T) {
lhs = lhs.${x.name}(rhs)
}
% end
% for x in maskingShifts:
@warn_unused_result
@_transparent
public func ${x.operator} <T: FixedWidthIntegerType>(lhs: T, rhs: T) -> T {
return lhs.${x.name}(rhs)
}
@_transparent
public func ${x.operator}= <T: FixedWidthIntegerType>(inout lhs: T, rhs: T) {
lhs = lhs ${x.operator} rhs
}
@warn_unused_result
@_transparent
public func ${x.operator} <
T: FixedWidthIntegerType, U: IntegerType
>(lhs: T, rhs: U) -> T {
return lhs.${x.name}(T(extendingOrTruncating: rhs))
}
@_transparent
public func ${x.operator}= <
T: FixedWidthIntegerType, U: IntegerType
>(inout lhs: T, rhs: U) {
lhs = lhs ${x.operator} rhs
}
@warn_unused_result
@_transparent
public func ${x.nonMaskingOperator} <
T: FixedWidthIntegerType, U: IntegerType
>(lhs: T, rhs: U) -> T {
let shift = rhs < -T.bitWidth ? -T.bitWidth
: rhs > T.bitWidth ? T.bitWidth
: Word(rhs)
return lhs ${x.nonMaskingOperator} shift
}
// "Smart shift", supporting overshifts and negative shifts
@warn_unused_result
@_transparent
public func ${x.nonMaskingOperator} <
T: FixedWidthIntegerType
>(lhs: T, rhs: Word) -> T {
let overshiftR = T.min < 0 ? lhs &>> (T.bitWidth - 1) : 0
let overshiftL: T = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < T.bitWidth) {
return lhs.${x.name}(T(extendingOrTruncating: rhs))
}
return overshift${'LR'['R' in x.name]}
}
if _slowPath(rhs <= -T.bitWidth) {
return overshift${'RL'['R' in x.name]}
}
return lhs ${x.operator.translate(maketrans('<>', '><'))} -rhs
}
@_transparent
public func ${x.nonMaskingOperator}= <
T: FixedWidthIntegerType
>(inout lhs: T, rhs: T) {
lhs = lhs ${x.nonMaskingOperator} rhs
}
@_transparent
public func ${x.nonMaskingOperator}= <
T: FixedWidthIntegerType, U: IntegerType
>(inout lhs: T, rhs: U) {
lhs = lhs ${x.nonMaskingOperator} rhs
}
% end
@warn_unused_result
@inline(__always)
public prefix func ~ <T: FixedWidthIntegerType>(x: T) -> T {
return 0 &- x &- 1
}
extension FixedWidthIntegerType {
public init<Other: IntegerType>(clamping source: Other) {
if _slowPath(source < Self.min) {
self = Self.min
}
else if _slowPath(source > Self.max) {
self = Self.max
}
else { self = Self(extendingOrTruncating: source) }
}
% for x in binaryArithmetic:
@_transparent
public mutating func ${x.name}InPlace(rhs: Self) {
let (result, overflow) = self.${x.name}WithOverflow(rhs)
_assertCond(overflow == .None, "overflow in ${x.name}")
self = result
}
/// Return `self ${x.operator} rhs`. If an arithmetic overflow
/// occurs, the behavior is undefined.
///
/// Note: use this function to avoid the cost of overflow checking
/// when you are sure that the operation won't overflow.
@warn_unused_result
@_transparent
public func unsafe${capitalize(x.name)}(rhs: Self) -> Self {
let (result, overflow) = self.${x.name}WithOverflow(rhs)
if (overflow != .None) {
if (_isDebugAssertConfiguration()) {
_preconditionFailure("overflow in unsafe${capitalize(x.name)}")
}
else {
Builtin.conditionallyUnreachable()
}
}
return result
}
% end
@_transparent
public init() {
self = 0
}
@_transparent
public init<T : IntegerType>(extendingOrTruncating source: T) {
if Self.bitWidth <= ${word_bits} {
self = Self.init(_truncatingBits: source.uword(0))
}
else {
var result: Self = source < 0 ? ~0 : 0
// start with the most significant word
var n = source.mostSignificantBit / ${word_bits}
while n >= 0 {
// masking is OK here because this we have already ensured
// that Self.bitWidth > ${word_bits}. Not masking results in
// infinite recursion.
result &<<= ${word_bits}
result |= Self(_truncatingBits: source.uword(n))
n -= 1
}
self = result
}
}
@_transparent
public func uword(n: Word) -> UWord {
var n = n
_precondition(n >= 0, "Negative word index")
var x = self
while n > 0 {
x &>>= Swift.min(Self(_truncatingBits: Self._bitWidth) &- 1, ${word_bits})
n -= 1
}
return x._lowUWord
}
@_transparent
public mutating func replaceUWord(n: Word, with newBits: UWord) {
// Make sure the masking shift is going to be OK.
_sanityCheck(Self.bitWidth > ${word_bits} * n)
self ^= Self(_truncatingBits: newBits ^ uword(n)) &<< (${word_bits} * n)
}
@_transparent
public // transparent
static var _highBitIndex: Self {
return Self.init(_truncatingBits: Self._bitWidth &- 1)
}
@_transparent
public static var _bitWidth : UWord {
return UWord(bitWidth._storage)
}
}
% for x in binaryArithmetic:
% if x.kind != '/':
@warn_unused_result
public func &${x.operator} <T: FixedWidthIntegerType>(lhs: T, rhs: T) -> T {
return lhs.${x.name}WithOverflow(rhs).partialValue
}
% end
% end
//===----------------------------------------------------------------------===//
//===--- UnsignedIntegerType ----------------------------------------------===//
//===----------------------------------------------------------------------===//
public protocol UnsignedIntegerType : IntegerType {
}
extension UnsignedIntegerType {
public var description: String {
if self == 0 {
return "0"
}
let ascii0 = 48
var buf: [UnicodeScalar] = []
var x = self
repeat {
let r = x % 10
x /= 10
buf.append(
UnicodeScalar(
ascii0 + Swift.Int(Word(extendingOrTruncating: r)._storage)))
}
while x != 0
return String(buf.reverse().lazy.map { Character($0) })
}
}
extension UnsignedIntegerType where Self : FixedWidthIntegerType {
@_transparent
public init<T : IntegerType>(_ source: T) {
_assertCond(
source >= 0, "negative value \(source) not representable by \(Self.self)")
let requiredBits = source.mostSignificantBit + 1
_assertCond(
requiredBits <= Self.bitWidth,
"\(Self.self) cannot store all \(requiredBits) bits "
+ "needed for unsigned representation of \(source)")
self.init(extendingOrTruncating: source)
}
@_transparent
public static var max: Self {
return ~0
}
@_transparent
public static var min: Self {
return 0
}
@_transparent
public var mostSignificantBit: Word {
return Self.bitWidth - 1 - self.countLeadingZeros()
}
}
//===----------------------------------------------------------------------===//
//===--- SignedIntegerType ------------------------------------------------===//
//===----------------------------------------------------------------------===//
public protocol SignedIntegerType : IntegerType {
typealias AbsoluteValue : IntegerType
var absoluteValue: AbsoluteValue { get }
}
extension SignedIntegerType {
public var description: String {
let base = String(absoluteValue)
return self < 0 ? "-" + base : base
}
}
extension SignedIntegerType where Self : FixedWidthIntegerType {
@_transparent
public init<T : IntegerType>(_ source: T) {
let requiredBits = source.mostSignificantBit + (source >= 0 ? 2 : 1)
_assertCond(
requiredBits <= Self.bitWidth,
"\(Self.self) cannot store all \(requiredBits) bits "
+ "needed for signed representation of \(source)")
self.init(extendingOrTruncating: source)
}
@_transparent
public static var max: Self {
return ~min
}
@_transparent
public static var min: Self {
return -1 &<< Self._highBitIndex
}
@_transparent
public var mostSignificantBit: Word {
let x = self < 0 ? ~self : self
return Self.bitWidth - 1 - x.countLeadingZeros()
}
}
//===--- Concrete FixedWidthIntegers --------------------------------------===//
% for bits in fixedBitWidths:
% for signed in True, False:
% Self = ('Int%d' if signed else 'UInt%d') % bits
% Unsigned = 'Signed' if signed else 'Unsigned'
% u = 's' if signed else 'u'
% z = 's' if signed else 'z'
public struct ${Self}
: FixedWidthIntegerType, ${Unsigned}IntegerType,
_BuiltinIntegerLiteralConvertible {
@_transparent
public init(_builtinIntegerLiteral x: _MaxBuiltinIntegerType) {
_storage = Builtin.truncOrBitCast_${IntLiteral}_Int${bits}(x)
Builtin.condfail(
Builtin.cmp_ne_${IntLiteral}(
Builtin.${'s' if signed else 'z'}extOrBitCast_Int${bits}_${IntLiteral}(
_storage), x))
}
@_transparent
public init(bitPattern x: ${'U' if signed else ''}Int${bits}) {
_storage = x._storage
}
@warn_unused_result
public func isEqualTo(rhs: ${Self}) -> Bool {
return Bool(Builtin.cmp_eq_Int${bits}(_storage, rhs._storage))
}
@warn_unused_result
public func isLessThan(rhs: ${Self}) -> Bool {
return Bool(Builtin.cmp_${u}lt_Int${bits}(_storage, rhs._storage))
}
% for x in binaryArithmetic:
/// Return a pair consisting of `self` ${x.operator} `rhs`,
/// truncated to fit if necessary, and a flag indicating whether an
/// arithmetic overflow occurred.
@warn_unused_result
@_transparent
public func ${x.name}WithOverflow(
rhs: ${Self}
) -> (partialValue: ${Self}, overflow: ArithmeticOverflow) {
% if x.kind == '/':
// No LLVM primitives for checking overflow of division
// operations, so we check manually.
if _slowPath(
rhs == 0
${'|| self == %s.min && rhs == -1' % Self if signed else ''}
) {
return (partialValue: self, overflow: .Overflow)
}
let (newStorage, overflow) = (
Builtin.${u}${x.llvmName}_Int${bits}(self._storage, rhs._storage),
false.__value)
% else:
let (newStorage, overflow)
= Builtin.${u}${x.llvmName}_with_overflow_Int${bits}(
self._storage, rhs._storage, false.__value)
% end
return (
partialValue: ${Self}(newStorage),
overflow: Bool(overflow) ? .Overflow : .None)
}
% end
@_transparent
public init(_ _storage: Builtin.Int${bits}) {
self._storage = _storage
}
% for x in binaryBitwise:
@warn_unused_result
@_transparent
public func ${x.name}(rhs: ${Self}) -> ${Self} {
return ${Self}(
Builtin.${x.name}_Int${bits}(self._storage, rhs._storage))
}
% end
% for x in maskingShifts:
@warn_unused_result
@_transparent
public func ${x.name}(rhs: ${Self}) -> ${Self} {
let rhs_ = rhs & ${Self}._highBitIndex
return ${Self}(
Builtin.${x.llvmName(signed)}_Int${bits}(self._storage, rhs_._storage))
}
% end
@_transparent
public static var bitWidth : Word { return ${bits} }
@_transparent
@warn_unused_result
public func countLeadingZeros() -> Word {
return Word(
${Self}(
Builtin.int_ctlz_Int${bits}(self._storage, false.__value)
)._lowUWord._storage)
}
@_transparent
public // transparent
var _lowUWord: UWord {
% truncOrExt = z + 'ext' if bits <= word_bits else 'trunc'
return UWord(
Builtin.${truncOrExt}OrBitCast_Int${bits}_Int${word_bits}(_storage)
)
}
@_transparent
public // transparent
init(_truncatingBits bits: UWord) {
% truncOrExt = 'zext' if bits > word_bits else 'trunc'
self.init(
Builtin.${truncOrExt}OrBitCast_Int${word_bits}_Int${bits}(bits._storage))
}
% if signed:
@_transparent
public var absoluteValue: U${Self} {
let base = U${Self}(_storage)
return self < 0 ? ~base + 1 : base
}
% end
public var _storage: Builtin.Int${bits}
}
% end
% end
//===--- Tests ------------------------------------------------------------===//
typealias DWord = Int${word_bits*2}
typealias UDWord = UInt${word_bits*2}
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var tests = TestSuite("Integers")
tests.test("Literals") {
// Testing against the official Int types so as not to depend on
// unimplemented stuff.
let a: UInt8 = 0b1_0_11_0_111
expectEqual(unsafeBitCast(a, Swift.UInt8.self), 0b1_0_11_0_111)
let b: Int16 = 183
expectEqual(unsafeBitCast(b, Swift.Int16.self), 0b1_0_11_0_111)
let c: Int16 = -183
expectEqual(unsafeBitCast(c, Swift.Int16.self), -183)
let d: Int8 = 127
expectEqual(unsafeBitCast(d, Swift.Int8.self), 127)
let e: UInt8 = 255
expectEqual(unsafeBitCast(e, Swift.UInt8.self), 255)
}
tests.test("Signed Literal Trap") {
expectCrashLater()
let _: Int8 = 128
}
tests.test("Unsigned Literal Trap") {
expectCrashLater()
let _: UInt8 = 256
}
tests.test("Equality") {
expectEqual(183 as UInt8, 183)
expectNotEqual(183 as UInt8, 184)
expectEqual(49 as Int8, 49)
expectNotEqual(-49 as Int8, 49)
}
func indexOrder<T: RandomAccessIndexType>(x: T, y: T)
-> ExpectedComparisonResult {
return x < y ? .LT : x > y ? .GT : .EQ
}
tests.test("Ordering") {
checkComparable([127, 183, 184, 255] as [UInt8], oracle: indexOrder)
checkComparable([-128, -1, 83, 84, 127] as [Int8], oracle: indexOrder)
checkComparable([127, 183, 184, 255, 65535] as [UInt16], oracle: indexOrder)
checkComparable([-32768, -32767, 83, 84, 32767] as [Int16], oracle: indexOrder)
}
tests.test("Simple-Arithmetic") {
expectEqual(1 as Int8 + 2, 3)
expectEqual(1 as Int8 - 2, -1)
expectEqual(-5 as Int8 + 11, 6)
expectEqual(3 as Int8 * 4, 12)
expectEqual(4 as Int8 * -7, -28)
expectEqual(-4 as Int8 * -7, 28)
expectEqual(5 as Int8 / 2, 2)
expectEqual(6 as Int8 / 2, 3)
expectEqual(7 as Int8 / 2, 3)
expectEqual(5 as Int8 % 3, 2)
expectEqual(6 as Int8 % 3, 0)
expectEqual(7 as Int8 % 3, 1)
}
tests.test("Simple-Bitwise") {
expectEqual(0b100_1001 as Int8 >> 1, 0b10_0100)
expectEqual(-0b100_1001 as Int8 >> 1, -0b10_0101)
expectEqual(0b1011_0111 as UInt8 >> 1, 0b0101_1011)
expectEqual(0b100_1001 as Int8 >> 1, 0b10_0100)
expectEqual(-0b100_1001 as Int8 >> 1, -0b10_0101)
expectEqual(0b1011_0111 as UInt8 >> 1, 0b0101_1011)
expectEqual(0b1011_0111 as UInt8 & 0b0110_1110, 0b0010_0110)
expectEqual(0b1011_0111 as UInt8 | 0b0110_1110, 0xFF)
expectEqual(0b1011_0111 as UInt8 ^ 0b0110_1110, 0b1101_1001)
}
tests.test("MinMax") {
expectEqual(255, UInt8.max)
expectEqual(0, UInt8.min)
expectEqual(127, Int8.max)
expectEqual(-128, Int8.min)
}
tests.test("CountLeadingZeros") {
expectEqual(0, UInt8.max.countLeadingZeros())
expectEqual(8, UInt8.min.countLeadingZeros())
expectEqual(1, Int8.max.countLeadingZeros())
expectEqual(0, Int8.min.countLeadingZeros())
}
tests.test("mostSignificantBit") {
expectEqual(7, UInt8.max.mostSignificantBit)
expectEqual(-1, UInt8.min.mostSignificantBit)
expectEqual(6, Int8.max.mostSignificantBit)
expectEqual(-1, (0 as Int8).mostSignificantBit)
expectEqual(6, Int8.min.mostSignificantBit)
}
tests.test("Conversion8to16") {
expectEqual(255, UInt16(UInt8.max))
expectEqual(255, Int16(UInt8.max))
expectEqual(0, UInt16(UInt8.min))
expectEqual(0, Int16(UInt8.min))
expectEqual(127, Int16(Int8.max))
let negativeValue = Int8.min
expectCrashLater()
_ = UInt16(negativeValue)
}
tests.test("Conversion16to8") {
expectEqual(255, UInt8(255 as UInt16))
expectEqual(255, UInt8(255 as Int16))
expectEqual(0, UInt8(0 as UInt16))
expectEqual(0, UInt8(0 as Int16))
expectEqual(127, Int8(127 as UInt16))
expectEqual(127, Int8(127 as Int16))
expectEqual(-128, Int8(-128 as Int16))
let tooLarge: UInt16 = 128
expectCrashLater()
_ = Int8(tooLarge)
}
tests.test("Conversion16to8a") {
let tooLarge: Int16 = 128
expectCrashLater()
_ = Int8(tooLarge)
}
tests.test("Conversion16to8b") {
let tooLarge: Int16 = 256
expectCrashLater()
_ = UInt8(tooLarge)
}
tests.test("Conversion16to8c") {
let tooLarge: UInt16 = 256
expectCrashLater()
_ = UInt8(tooLarge)
}
tests.test("ConversionWordToDWord") {
expectEqual(1 << ${word_bits} - 1, UDWord(UWord.max))
expectEqual(1 << ${word_bits} - 1, DWord(UWord.max))
expectEqual(0, UDWord(UWord.min))
expectEqual(0, DWord(UWord.min))
expectEqual(1 << ${word_bits-1} - 1, DWord(Word.max))
let negativeValue = Word.min
expectCrashLater()
_ = UDWord(negativeValue)
}
tests.test("ConversionDWordToWord") {
expectEqual(~0, UWord(1 << ${word_bits} - 1 as UDWord))
expectEqual(~0, UWord(1 << ${word_bits} - 1 as DWord))
expectEqual(0, UWord(0 as UDWord))
expectEqual(0, UWord(0 as DWord))
expectEqual(Word.max, Word(1 << ${word_bits-1} - 1 as UDWord))
expectEqual(Word.max, Word(1 << ${word_bits-1} - 1 as DWord))
expectEqual(Word.min, Word(-1 << ${word_bits-1} as DWord))
let tooLarge: UDWord = 1 << ${word_bits-1}
expectCrashLater()
_ = Word(tooLarge)
}
tests.test("ConversionDWordToWordA") {
let tooLarge: DWord = 1 << ${word_bits}
expectCrashLater()
_ = Word(tooLarge)
}
tests.test("ConversionDWordToWordB") {
let tooLarge: DWord = 1 << ${word_bits}
expectCrashLater()
_ = UWord(tooLarge)
}
tests.test("ConversionDWordToWordC") {
let tooLarge: UDWord = 1 << ${word_bits}
expectCrashLater()
_ = UWord(tooLarge)