-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Float80Utils.pas
2742 lines (2306 loc) · 92.4 KB
/
Float80Utils.pas
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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Float80Utils
Main aim of this library is to provide a mean of converting to and from
double-extended-precision (80bit) floating point numbers.
It is meant for environments where type Extended is declared only as an
alias for type Double (64bit float) - typically 64bit applications where
SSE, which does not support 80bit floats, is used as a primary FPU.
Beyond the conversion routines, there are also some utilities - namely
functions for number information or encoding/decoding the float80 type
from/to its constituent parts (mantissa, exponent, sign).
From user perspective, there is not much difference, but it must be noted
that the unit can be compiled in two modes, each totally different.
First, default mode, is using assembly to directly access x87 FPU and does
the conversion there.
In this mode, auxiliry functions provided here (access to status and
control word, exceptions masking and so on) operates directly on real x87
registers and exceptions raising is also managed by the x87 FPU.
Second is PurePascal mode. In it, a complete pascal implementation of
conversion is used instead, so it can be called even on systems with no
suitable FPU.
Auxiliary functions are operating on local software implementation of
status and control word and do not access the hardware.
This implementation partially emulates the conversion how it is done on
x87, including exception raising (exception masking and pre- and
post-calculation nature of exceptions are honored) and changes given by
selected rounding mode (note that precision mode does not affect
conversions even on real x87 FPU).
But remember it is only an emulation, not simulation - there are
differences, notably condition codes are not affected by exceptions, and
when raising an unmasked exception, the exception status bits are not set,
summary flag bit is not set both for masked and unmasked exceptions.
Top of the stack, busy and stack fault flags are outright ignored.
Version 1.1.1 (2024-04-14)
Last change 2024-04-14
©2020-2024 František Milt
Contacts:
František Milt: [email protected]
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.Float80Utils
Dependencies:
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
Library AuxExceptions is required only when rebasing local exception classes
(see symbol Float80Utils_UseAuxExceptions for details).
Indirect dependencies:
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
StrRect - github.com/TheLazyTomcat/Lib.StrRect
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit Float80Utils;
{
Float80_PurePascal
If you want to compile this unit without ASM, don't want to or cannot define
PurePascal for the entire project and at the same time you don't want to or
cannot make changes to this unit, define this symbol for the entire project
and this unit will be compiled in PurePascal mode.
}
{$IFDEF Float80_PurePascal}
{$DEFINE PurePascal}
{$ENDIF}
{
Float80Utils_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
Float80Utils_UseAuxExceptions to achieve this.
}
{$IF Defined(Float80Utils_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IFDEF ENDIAN_BIG}
// sadly, I have no way of developing for BE systems :(
{$MESSAGE FATAL 'Big-endian architecture not supported'}
{$ENDIF}
{$IF defined(CPUX86_64) or defined(CPUX64)}
{$DEFINE x64}
{$ELSEIF defined(CPU386)}
{$DEFINE x86}
{$ELSE}
{$DEFINE PurePascal}
{$IFEND}
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$INLINE ON}
{$DEFINE CanInline}
{$IFNDEF PurePascal}
{$ASMMODE Intel}
{$ENDIF}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ELSE}
{$IF CompilerVersion >= 17} // Delphi 2005+
{$DEFINE CanInline}
{$ELSE}
{$UNDEF CanInline}
{$IFEND}
{$ENDIF}
{$H+}
interface
uses
SysUtils,
AuxTypes {contains declaration of Float80 type}
{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions - declaration
===============================================================================}
type
EF80UException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
EF80UInvalidFlag = class(EF80UException);
{-------------------------------------------------------------------------------
Library-specific exceptions - FPU exceptions
-------------------------------------------------------------------------------}
type
EF80UFPUException = class(EF80UException)
protected
fControlWord: UInt16;
fStatusWord: UInt16;
Function DefaultMessage: String; virtual; abstract;
public
constructor CreateNoClear(const Msg: String{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
constructor Create(const Msg: String);
constructor CreateDefMsgNoClear({$IFNDEF FPC}Dummy: Integer = 0{$ENDIF});
constructor CreateDefMsg;
{
ControlWord and StatusWord properties hold content of control word and
status word registers respectively as they were when this exception was
created - they can be used for example to probe masked signaled exceptions.
}
// StatusWord holds content of status word as it was when this exception
// was created - can be used to probe masked signaled exceptions
property ControlWord: UInt16 read fControlWord;
property StatusWord: UInt16 read fStatusWord;
end;
// FPU stack errors
EF80UStackFault = class(EF80UFPUException);
{-------------------------------------------------------------------------------
Library-specific exceptions - individual FPU exception classes
-------------------------------------------------------------------------------}
type
EF80UStackOverflow = class(EF80UStackFault)
protected
Function DefaultMessage: String; override;
end;
EF80UStackUnderflow = class(EF80UStackFault)
protected
Function DefaultMessage: String; override;
end;
EF80UInvalidOp = class(EF80UFPUException) // invalid operation/operand
protected
Function DefaultMessage: String; override;
end;
EF80UDenormal = class(EF80UFPUException)
protected
Function DefaultMessage: String; override;
end;
EF80UDivByZero = class(EF80UFPUException)
protected
Function DefaultMessage: String; override;
end;
EF80UOverflow = class(EF80UFPUException)
protected
Function DefaultMessage: String; override;
end;
EF80UUnderflow = class(EF80UFPUException)
protected
Function DefaultMessage: String; override;
end;
EF80UPrecision = class(EF80UFPUException)
protected
Function DefaultMessage: String; override;
end;
{===============================================================================
Auxiliary routines - declaration
===============================================================================}
{-------------------------------------------------------------------------------
Auxiliary routines - x87 status word access
-------------------------------------------------------------------------------}
{
Note that x87 status register is read only - it can only be changed by
clearing exceptions.
}
const
// status word masks
X87SW_EX_InvalidOP = UInt16($0001);
X87SW_EX_Denormal = UInt16($0002);
X87SW_EX_DivByZero = UInt16($0004);
X87SW_EX_Overflow = UInt16($0008);
X87SW_EX_Underflow = UInt16($0010);
X87SW_EX_Precision = UInt16($0020);
X87SW_StackFault = UInt16($0040);
X87SW_ExceptionSummary = UInt16($0080);
X87SW_FPUBusy = UInt16($8000);
X87SW_ConditionCode_C0 = UInt16($0100);
X87SW_ConditionCode_C1 = UInt16($0200);
X87SW_ConditionCode_C2 = UInt16($0400);
X87SW_ConditionCode_C3 = UInt16($4000);
X87SW_TopOfStack = UInt16($3800); // bits 11..13
X87SW_SHIFT_TopOfStack = 11;
//------------------------------------------------------------------------------
{
EmulatedX87StatusWord
Returns true when a real x87 status register is used, false when operating
on an emulated local implementation of status word.
}
Function EmulatedX87StatusWord: Boolean;{$IF Defined(CanInline) and not Defined(FPC)} inline;{$IFEND}
{
GetX87StatusWord
Returns current value of status word.
}
Function GetX87StatusWord: UInt16;{$IFNDEF PurePascal} register; assembler;{$ENDIF}
{-------------------------------------------------------------------------------
Auxiliary routines - x87 control word access
-------------------------------------------------------------------------------}
const
// control word masks
X87CW_EMASK_InvalidOP = UInt16($0001);
X87CW_EMASK_Denormal = UInt16($0002);
X87CW_EMASK_DivByZero = UInt16($0004);
X87CW_EMASK_Overflow = UInt16($0008);
X87CW_EMASK_Underflow = UInt16($0010);
X87CW_EMASK_Precision = UInt16($0020);
X87CW_InfinityControl = UInt16($1000);
X87CW_Precision = UInt16($0300); // bits 8..9
X87CW_Rounding = UInt16($0C00); // bits 10..11
X87CW_SHIFT_Precision = 8;
X87CW_SHIFT_Rounding = 10;
//------------------------------------------------------------------------------
{
EmulatedX87ControlWord
Returns true when a real x87 control register is used, false when operating
on an emulated local implementation of control word.
}
Function EmulatedX87ControlWord: Boolean;{$IFDEF CanInline} inline;{$ENDIF}
{
GetX87ControlWord
Returns current value of control word.
}
Function GetX87ControlWord: UInt16;{$IFNDEF PurePascal} register; assembler;{$ENDIF}
{
SetX87ControlWord
Set control word to a passed value.
}
procedure SetX87ControlWord(NewValue: UInt16);{$IFNDEF PurePascal} register; assembler;{$ENDIF}
{
Sets x87 control word to $1372 - denormal, underflow and precision exceptions
are masked (others are unmasked), precision is set to extended, rounding is
set to nearest and infinity control bit is 1.
Call this routine only when the control word is NOT emulated (ie. a real CPU
register is used) and the program is compiled so that x87 FPU is not used as
primary mean of floating point arithmetics and/or is not automatically
initialized (if the control word is $037F - a default value set by F(N)INIT
instruction - you can safely assume it was not properly initialized).
WARNING - the initialization must be done in each execution thread.
}
procedure InitX87ControlWord;{$IFDEF CanInline} inline;{$ENDIF}
{-------------------------------------------------------------------------------
Auxiliary routines - abstracted SW and CW access
-------------------------------------------------------------------------------}
type
TX87PrecisionMode = (pmSingle,pmReserved,pmDouble,pmExtended);
TX87RoundingMode = (rmNearest,rmDown,rmUp,rmTruncate);
TX87StatusFlag = (sfStackFault,sfExceptionSummary,sfFPUBusy,sfConditionCodeC0,
sfConditionCodeC1,sfConditionCodeC2,sfConditionCodeC3);
TX87StatusFlags = set of TX87StatusFlag;
TX87ControlFlag = (cfInfinityControl);
TX87ControlFlags = set of TX87ControlFlag;
//------------------------------------------------------------------------------
{
GetX87PrecisionMode
Returns current value of precision mode from control word.
}
Function GetX87PrecisionMode: TX87PrecisionMode;
{
SetX87PrecisionMode
Sets precision mode to a selected NewValue and returns previous value of
precision mode.
}
Function SetX87PrecisionMode(NewValue: TX87PrecisionMode): TX87PrecisionMode;
//------------------------------------------------------------------------------
{
GetX87RoundingMode
Returns current value of rounding mode from control word.
}
Function GetX87RoundingMode: TX87RoundingMode;
{
SetX87RoundingMode
Sets rounding mode to a selected NewValue and returns previous value of
rounding mode.
}
Function SetX87RoundingMode(NewValue: TX87RoundingMode): TX87RoundingMode;
//------------------------------------------------------------------------------
{
GetX87TopOfStack
Returns current top of the stack pointer from the status word.
}
Function GetX87TopOfStack: Integer;
{
SetX87TopOfStack
Sets top of the stack to a selected NewValue and returns previous value of
rounding mode.
WARNING - it does not change the top of the stack when operating on real
status register (ie. not in PurePascal mode) as status register is
read-only.
}
Function SetX87TopOfStack(NewValue: Integer): Integer;
//------------------------------------------------------------------------------
{
GetX87StatusFlag
Returns current value of selected flag in the status word.
}
Function GetX87StatusFlag(Flag: TX87StatusFlag): Boolean;
{
SetX87StatusFlag
Sets value of selected flag in the status word to a NewValue and returns
previous state of this flag.
WARNING - it does not change the flag when operating on real status register
(read-only status register).
}
Function SetX87StatusFlag(Flag: TX87StatusFlag; NewValue: Boolean): Boolean;
//------------------------------------------------------------------------------
{
GetX87StatusFlags
Returns status of all flags in the status word. When the flag is set, it is
included in the result, when it is clear, it is excluded.
}
Function GetX87StatusFlags: TX87StatusFlags;
{
SetX87StatusFlags
Sets new status of all flags in the status word. If a flag is included
in the NewValue, it will be set, when it is not included, it will be cleared.
Return value is previous state of all status flags.
WARNING - it does not change any flag when operating on real status register
(read-only status register).
}
Function SetX87StatusFlags(NewValue: TX87StatusFlags): TX87StatusFlags;
//------------------------------------------------------------------------------
{
GetX87ControlFlag
Returns current value of selected flag in the control word.
}
Function GetX87ControlFlag(Flag: TX87ControlFlag): Boolean;
{
SetX87ControlFlag
Sets value of selected flag in the control word to a NewValue and returns
previous state of this flag.
}
Function SetX87ControlFlag(Flag: TX87ControlFlag; NewValue: Boolean): Boolean;
//------------------------------------------------------------------------------
{
GetX87ControlFlags
Returns status of all flags in the control word. When the flag is set, it is
included in the result, when it is clear, it is excluded.
}
Function GetX87ControlFlags: TX87ControlFlags;
{
SetX87ControlFlags
Sets new status of all flags in the control word. If a flag is included
in the NewValue, it will be set, when it is not included, it will be cleared.
Return value is previous state of all control flags.
}
Function SetX87ControlFlags(NewValue: TX87ControlFlags): TX87ControlFlags;
{-------------------------------------------------------------------------------
Auxiliary routines - abstracted x87 exception flags access
-------------------------------------------------------------------------------}
type
TX87Exception = (excInvalidOp,excDenormal,excDivByZero,excOverflow,
excUnderflow,excPrecision);
TX87Exceptions = set of TX87Exception;
const
AllX87Exceptions = [excInvalidOp,excDenormal,excDivByZero,excOverflow,
excUnderflow,excPrecision];
//------------------------------------------------------------------------------
{
GetX87ExceptionMask
Returns current value of selected exception mask bit.
}
Function GetX87ExceptionMask(Exception: TX87Exception): Boolean;
{
SetX87ExceptionMask
Sets value of selected exception mask bit in the control word to a NewValue
and returns previous value of this bit.
When the bit is set (true), the selected exception will be masked and not
raised on its occurence.
When clear (false), the exception is unmasked and can be raised.
}
Function SetX87ExceptionMask(Exception: TX87Exception; NewValue: Boolean): Boolean;
//------------------------------------------------------------------------------
{
GetX87ExceptionMasks
Returns status of all exception mask bits in the control word. When the bit
is set, the exception is included in the result, when it is clear, the
exception is excluded from the result.
}
Function GetX87ExceptionMasks: TX87Exceptions;
{
SetX87ExceptionMasks
Sets new value of all exception mask bits in the control word. If an
exception is included in the NewValue, the mask bit will be set, when it is
not included, the mask bit will be cleared.
Return value is previous state of all exception mask bits.
}
Function SetX87ExceptionMasks(NewValue: TX87Exceptions): TX87Exceptions;
//------------------------------------------------------------------------------
{
GetX87ExceptionFlag
Returns current value of selected exception flag bit.
}
Function GetX87ExceptionFlag(Exception: TX87Exception): Boolean;
{
SetX87ExceptionFlag
Sets value of selected exception flag bit in the status word to a NewValue
and returns previous value of this bit.
WARNING - changes nothing when operating on real status register as it is
read-only.
}
Function SetX87ExceptionFlag(Exception: TX87Exception; NewValue: Boolean): Boolean;
//------------------------------------------------------------------------------
{
GetX87ExceptionFlags
Returns status of all exception flag bits in the status word. When the bit
is set, the exception is included in the result, when it is clear, the
exception is excluded from the result.
}
Function GetX87ExceptionFlags: TX87Exceptions;
{
SetX87ExceptionFlags
Sets new value of all exception flag bits in the status word. If an exception
is included in the NewValue, the flag bit will be set, when it is not
included, the flag bit will be cleared.
Return value is previous state of all exception flag bits.
WARNING - changes nothing when operating on real status register.
}
Function SetX87ExceptionFlags(NewValue: TX87Exceptions): TX87Exceptions;
//------------------------------------------------------------------------------
{
ClearX87Exceptions
In PurePascal it completely clears the status word (resets all exception
flag bits, sets top of stack to 0, clears all condition codes and other
flags)
When operating on real status register, it just executes FCLEX instruction
(it clears exception flag bits, FPU busy flag, summary status flag and
stack fault flag, condition codes and top of the stack are undefined).
}
procedure ClearX87Exceptions;{$IFNDEF PurePascal} register; assembler;{$ENDIF}
{
RaiseX87Exceptions
Raises first encountered exception according to flags set in the passed
status word.
Parameter Mask controls whether to honor exception masking (true) or not
(false) when raising an exception (when honored, the masked exceptions are
NOT raised, when not honored, all exceptions can be raised, even those
masked).
Mask bits are taken from the parameter ConrolWord, not from the actual
register.
The exception flag bits are traversed one by one and, when a set bit is
encountered, it is cleared and a corresponding exception is raised (if
allowed by masking - see parameter Mask).
Only one exception is raised in each call, even when multiple bits are set.
The order in which the bits are traversed and therefore the order of
exceptions raising is:
InvalidOP/StackUnderflow/StackOverflow (they all fall in one group)
Denormal
DivByZero
Underflow
Overflow
Precision
}
procedure RaiseX87Exceptions(var StatusWord: UInt16; Mask: Boolean = True; ConrolWord: UInt16 = 0); overload;
{
RaiseX87Exceptions
Calls the first overload with an input being current value of status word
(be it a real register or emulation).
Note that this function will NOT change the status word.
}
procedure RaiseX87Exceptions(Mask: Boolean = True); overload;
{===============================================================================
--------------------------------------------------------------------------------
Float80 <-> Float64 conversions
--------------------------------------------------------------------------------
===============================================================================}
type
// overlay for easier work with 10-byte extended precision float
TFloat80Overlay = packed record
case Integer of
0: (Part_64: UInt64;
Part_16: UInt16);
1: (Mantissa: UInt64;
SignExponent: UInt16);
2: (Words: array[0..4] of UInt16);
3: (Bytes: array[0..9] of UInt8);
end;
PFloat80Overlay = ^TFloat80Overlay;
const
FLOAT64_EXPONENTBIAS = 1023;
FLOAT80_EXPONENTBIAS = 16383;
{===============================================================================
Conversion routines - declaration
===============================================================================}
procedure Float64ToFloat80(Float64Ptr,Float80Ptr: Pointer);{$IFNDEF PurePascal} register; assembler;{$ENDIF} overload;
Function Float64ToFloat80(Value: Float64): Float80;{$IFDEF CanInline} inline;{$ENDIF} overload;
procedure DoubleToExtended(DoublePtr,ExtendedPtr: Pointer);{$IFDEF CanInline} inline;{$ENDIF} overload;
Function DoubleToExtended(Value: Float64): Float80;{$IFDEF CanInline} inline;{$ENDIF} overload;
//------------------------------------------------------------------------------
procedure Float80ToFloat64(Float80Ptr,Float64Ptr: Pointer);{$IFNDEF PurePascal} register; assembler;{$ENDIF} overload;
Function Float80ToFloat64(Value: Float80): Float64;{$IFDEF CanInline} inline;{$ENDIF} overload;
procedure ExtendedToDouble(ExtendedPtr,DoublePtr: Pointer);{$IFDEF CanInline} inline;{$ENDIF} overload;
Function ExtendedToDouble(Value: Float80): Float64;{$IFDEF CanInline} inline;{$ENDIF} overload;
{===============================================================================
--------------------------------------------------------------------------------
Float80 utilities
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
Utility routines - declaration
===============================================================================}
{-------------------------------------------------------------------------------
Utility routines - number information functions
-------------------------------------------------------------------------------}
Function IsValid(const Value: Float80): Boolean;
Function IsZero(const Value: Float80): Boolean;
Function IsDenormal(const Value: Float80): Boolean;
Function IsNaN(const Value: Float80): Boolean;
Function IsInfinite(const Value: Float80): Boolean;
Function IsNormal(const Value: Float80): Boolean; // returns false on zero
Function IsPseudoValue(const Value: Float80): Boolean;{$IFDEF CanInline} inline;{$ENDIF} // not IsValid
Function IsPseudoDenormal(const Value: Float80): Boolean;
Function IsPseudoNaN(const Value: Float80): Boolean;
Function IsPseudoInfinity(const Value: Float80): Boolean;
Function IsUnnormal(const Value: Float80): Boolean;
{-------------------------------------------------------------------------------
Utility routines - sign-related functions
-------------------------------------------------------------------------------}
type
TFloat80ValueSign = -1..1;
{
Following three routines will raise and EF80UInvalidOp exception when an
invalidly encoded number is passed.
}
Function Sign(const Value: Float80): TFloat80ValueSign;
Function Abs(const Value: Float80): Float80;
Function Neg(const Value: Float80): Float80;
{-------------------------------------------------------------------------------
Utility routines - floats encoding/decoding
-------------------------------------------------------------------------------}
procedure MapToFloat80Buffer(out Buffer; High16: UInt16; Low64: UInt64);
Function MapToFloat80(High16: UInt16; Low64: UInt64): Float80;{$IFDEF CanInline} inline;{$ENDIF}
Function MapToExtended(High16: UInt16; Low64: UInt64): Extended;
procedure MapFromFloat80Buffer(const Buffer; out High16: UInt16; out Low64: UInt64);
procedure MapFromFloat80(const Value: Float80; out High16: UInt16; out Low64: UInt64);{$IFDEF CanInline} inline;{$ENDIF}
procedure MapFromExtended(const Value: Extended; out High16: UInt16; out Low64: UInt64);
//------------------------------------------------------------------------------
{
EncodeFloat80Buffer
EncodeFloat80
EncodeExtended
When BiasedExp is true, it indicates that the passed exponent is already
biased and will be stored as is. When false, the passed exponent will be
biased before storing.
NOTE - the valid range for exponent is -16383..+16384 when biased, 0..32767
when unbiased. The exponent is clamped (limited to a prescribed
range) before biasing and storing.
When IntBit is true, it indicates that the passed mantissa contains the
integer bit (bit 63) and will be stored as is. When false, the integer bit
in passed mantissa is ignored and its value for storage is implied from the
exponent.
}
procedure EncodeFloat80Buffer(out Buffer; Mantissa: UInt64; Exponent: Int16; Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);
Function EncodeFloat80(Mantissa: UInt64; Exponent: Int16; Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True): Float80; {$IFDEF CanInline} inline;{$ENDIF}
Function EncodeExtended(Mantissa: UInt64; Exponent: Int16; Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True): Extended;{$IFDEF CanInline} inline;{$ENDIF}
{
DecodeFloat80Buffer
DecodeFloat80
DecodeExtended
When BiasedExp is set to true, the returned exponent is exponent as is
stored in the value, that is, biased. When false, the returned exponent is
unbiased (its true value).
NOTE - returned exponent will be within range of -16383..+16384 when
biased, 0..32767 when unbiased.
When IntBit is set to true, the returned mantissa contains the integer bit
(bit 63) as it is stored in the number. When false, the integer bit is
masked-out and is zero, irrespective of its actual value.
}
procedure DecodeFloat80Buffer(const Buffer; out Mantissa: UInt64; out Exponent: Int16; out Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);
procedure DecodeFloat80(const Value: Float80; out Mantissa: UInt64; out Exponent: Int16; out Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);{$IFDEF CanInline} inline;{$ENDIF}
procedure DecodeExtended(const Value: Extended; out Mantissa: UInt64; out Exponent: Int16; out Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);{$IFDEF CanInline} inline;{$ENDIF}
//------------------------------------------------------------------------------
{
Since conversions in this library are vorking with double-precision (64bit)
floats, one might want to decode/encode these floats too. Threfore...
}
procedure MapToFloat64Buffer(out Buffer; Value: UInt64);
Function MapToFloat64(Value: UInt64): Float64;{$IFDEF CanInline} inline;{$ENDIF}
Function MapToDouble(Value: UInt64): Double;{$IFDEF CanInline} inline;{$ENDIF}
Function MapFromFloat64Buffer(const Buffer): UInt64;
Function MapFromFloat64(const Value: Float64): UInt64;{$IFDEF CanInline} inline;{$ENDIF}
Function MapFromDouble(const Value: Double): UInt64;{$IFDEF CanInline} inline;{$ENDIF}
//------------------------------------------------------------------------------
{
EncodeFloat64Buffer
EncodeFloat64
EncodeDouble
When BiasedExp is true, it indicates that the passed exponent is already
biased and will be stored as is. When false, the passed exponent will be
biased before storing.
NOTE - the valid range for exponent is -1023..+1024 when biased, 0..2047
when unbiased. The exponent is clamped (limited to a prescribed
range) before biasing and storing.
Integer bit, when passed in the mantissa, is ignored - it is implied for
double-precision float.
NOTE - only lowest 52 bits of the mantissa are used, other bits gets
masked-out before storage.
}
procedure EncodeFloat64Buffer(out Buffer; Mantissa: UInt64; Exponent: Int16; Sign: Boolean; BiasedExp: Boolean = False);
Function EncodeFloat64(Mantissa: UInt64; Exponent: Int16; Sign: Boolean; BiasedExp: Boolean = False): Float64;{$IFDEF CanInline} inline;{$ENDIF}
Function EncodeDouble(Mantissa: UInt64; Exponent: Int16; Sign: Boolean; BiasedExp: Boolean = False): Double;{$IFDEF CanInline} inline;{$ENDIF}
{
DecodeFloat64Buffer
DecodeFloat64
DecodeDouble
When BiasedExp is set to true, the returned exponent is exponent as is
stored in the value, that is, biased. When false, the returned exponent is
unbiased (its true value).
NOTE - returned exponent will be within range of -1023..+1024 when biased,
0..2047 when unbiased.
When IntBit is set to true, the returned mantissa contains the integer bit
(bit 52) inferred from the number class (0 for denormals and zero,
1 otherwise). When false, the integer bit is masked-out and is zero,
irrespective of actual value.
NOTE - only lowest 52 bits (53 with integer bit) of the mantissa are valid,
other bits will always be zero.
}
procedure DecodeFloat64Buffer(const Buffer; out Mantissa: UInt64; out Exponent: Int16; out Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);
procedure DecodeFloat64(const Value: Float64; out Mantissa: UInt64; out Exponent: Int16; out Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);{$IFDEF CanInline} inline;{$ENDIF}
procedure DecodeDouble(const Value: Double; out Mantissa: UInt64; out Exponent: Int16; out Sign: Boolean; BiasedExp: Boolean = False; IntBit: Boolean = True);{$IFDEF CanInline} inline;{$ENDIF}
implementation
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
// do not place this any higher
{$IF SizeOf(Extended) = 8}
{$DEFINE Extended64}
{$ELSEIF SizeOf(Extended) = 10}
{$UNDEF Extended64}
{$ELSE}
{$MESSAGE FATAL 'Unsupported platform, type extended must be 8 or 10 bytes.'}
{$IFEND}
{===============================================================================
Internal constants and types
===============================================================================}
const
F64_MASK_SIGN = UInt64($8000000000000000); // sign bit
{$IFNDEF FPC}
F64_MASK_NSGN = UInt64($7FFFFFFFFFFFFFFF); // non-sign bits
{$ENDIF}
F64_MASK_EXP = UInt64($7FF0000000000000); // exponent
F64_MASK_FRAC = UInt64($000FFFFFFFFFFFFF); // fraction/mantissa
{$IFDEF PurePascal}
F64_MASK_FHB = UInt64($0008000000000000); // highest bit of the mantissa
{$ENDIF}
F64_MASK_INTB = UInt64($0010000000000000); // integer bit of the mantissa
F80_MASK16_SIGN = UInt16($8000);
F80_MASK16_NSGN = UInt16($7FFF);
F80_MASK16_EXP = UInt16($7FFF);
F80_MASK64_FRAC = UInt64($7FFFFFFFFFFFFFFF);
{$IFDEF PurePascal}
F80_MASK64_FHB = UInt64($4000000000000000);
{$ENDIF}
F80_MASK64_INTB = UInt64($8000000000000000);
{===============================================================================
Library-specific exceptions - implementation
===============================================================================}
{-------------------------------------------------------------------------------
Library-specific exceptions - FPU exceptions
-------------------------------------------------------------------------------}
constructor EF80UFPUException.CreateNoClear(const Msg: String{$IFNDEF FPC}; Dummy: Integer = 0{$ENDIF});
begin
inherited Create(Msg);
fStatusWord := GetX87StatusWord;
end;
//------------------------------------------------------------------------------
constructor EF80UFPUException.Create(const Msg: String);
begin
CreateNoClear(Msg);
If EmulatedX87StatusWord then
ClearX87Exceptions;
end;
//------------------------------------------------------------------------------
constructor EF80UFPUException.CreateDefMsgNoClear({$IFNDEF FPC}Dummy: Integer = 0{$ENDIF});
begin
CreateNoClear(DefaultMessage);
end;
//------------------------------------------------------------------------------
constructor EF80UFPUException.CreateDefMsg;
begin
Create(DefaultMessage);
end;
{-------------------------------------------------------------------------------
Library-specific exceptions - individual FPU exception classes
-------------------------------------------------------------------------------}
Function EF80UStackOverflow.DefaultMessage: String;
begin
Result := 'Floting point unit stack overflow';
end;
//------------------------------------------------------------------------------
Function EF80UStackUnderflow.DefaultMessage: String;
begin
Result := 'Floting point unit stack underflow';
end;
//------------------------------------------------------------------------------
Function EF80UInvalidOp.DefaultMessage: String;
begin
Result := 'Invalid floating point operand';
end;
//------------------------------------------------------------------------------
Function EF80UDenormal.DefaultMessage: String;
begin
Result := 'Denormal floating point operand';
end;
//------------------------------------------------------------------------------
Function EF80UDivByZero.DefaultMessage: String;
begin
Result := 'Floating point division by zero';
end;
//------------------------------------------------------------------------------
Function EF80UOverflow.DefaultMessage: String;
begin
Result := 'Floating point arithmetic overflow';
end;
//------------------------------------------------------------------------------
Function EF80UUnderflow.DefaultMessage: String;
begin
Result := 'Floating point arithmetic underflow';
end;
//------------------------------------------------------------------------------
Function EF80UPrecision.DefaultMessage: String;
begin
Result := 'Inexact floating point result';
end;
{===============================================================================
Auxiliary routines - implementation
===============================================================================}
{-------------------------------------------------------------------------------
Auxiliary routines - x87 status word access
-------------------------------------------------------------------------------}
{$IFDEF PurePascal}
threadvar
Pas_X87SW: UInt16;
SWInit: Boolean; // initalized by the compiler to false
{$ENDIF}
//------------------------------------------------------------------------------
Function EmulatedX87StatusWord: Boolean;
begin
{$IFDEF PurePascal}
Result := True;
{$ELSE}
Result := False;
{$ENDIF}
end;
//------------------------------------------------------------------------------
Function GetX87StatusWord: UInt16;
{$IFNDEF PurePascal}
asm
FSTSW AX
end;
{$ELSE}
begin