-
Notifications
You must be signed in to change notification settings - Fork 0
/
ap.cpp
12421 lines (11138 loc) · 367 KB
/
ap.cpp
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
/*************************************************************************
ALGLIB 3.17.0 (source code generated 2020-12-27)
Copyright (c) Sergey Bochkanov (ALGLIB project).
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
//
// if AE_OS==AE_LINUX (will be redefined to AE_POSIX in ap.h),
// set _GNU_SOURCE flag BEFORE any #includes to get affinity
// management functions
//
#if (AE_OS==AE_LINUX) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include "stdafx.h"
#include "ap.h"
#include <limits>
#include <locale.h>
#include <ctype.h>
#if defined(AE_CPU)
#if (AE_CPU==AE_INTEL)
#if AE_COMPILER==AE_MSVC
#include <intrin.h>
#endif
#endif
#endif
// disable some irrelevant warnings
#if (AE_COMPILER==AE_MSVC) && !defined(AE_ALL_WARNINGS)
#pragma warning(disable:4100)
#pragma warning(disable:4127)
#pragma warning(disable:4611)
#pragma warning(disable:4702)
#pragma warning(disable:4996)
#endif
/////////////////////////////////////////////////////////////////////////
//
// THIS SECTION IMPLEMENTS BASIC FUNCTIONALITY LIKE
// MEMORY MANAGEMENT FOR VECTORS/MATRICES WHICH IS
// SHARED BETWEEN C++ AND PURE C LIBRARIES
//
/////////////////////////////////////////////////////////////////////////
namespace alglib_impl
{
/*
* OS-specific includes
*/
#ifdef AE_USE_CPP
}
#endif
#if AE_OS==AE_WINDOWS || defined(AE_DEBUG4WINDOWS)
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#include <windows.h>
#include <process.h>
#elif AE_OS==AE_POSIX || defined(AE_DEBUG4POSIX)
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>
#include <sys/time.h>
#endif
/* Debugging helpers for Windows */
#ifdef AE_DEBUG4WINDOWS
#include <windows.h>
#include <stdio.h>
#endif
#ifdef AE_USE_CPP
namespace alglib_impl
{
#endif
/*
* local definitions
*/
#define x_nb 16
#define AE_DATA_ALIGN 64
#define AE_PTR_ALIGN sizeof(void*)
#define DYN_BOTTOM ((void*)1)
#define DYN_FRAME ((void*)2)
#define AE_LITTLE_ENDIAN 1
#define AE_BIG_ENDIAN 2
#define AE_MIXED_ENDIAN 3
#define AE_SER_ENTRY_LENGTH 11
#define AE_SER_ENTRIES_PER_ROW 5
#define AE_SM_DEFAULT 0
#define AE_SM_ALLOC 1
#define AE_SM_READY2S 2
#define AE_SM_TO_STRING 10
#define AE_SM_TO_CPPSTRING 11
#define AE_SM_TO_STREAM 12
#define AE_SM_FROM_STRING 20
#define AE_SM_FROM_STREAM 22
#define AE_LOCK_CYCLES 512
#define AE_LOCK_TESTS_BEFORE_YIELD 16
#define AE_CRITICAL_ASSERT(x) if( !(x) ) abort()
/* IDs for set_dbg_value */
#define _ALGLIB_USE_ALLOC_COUNTER 0
#define _ALGLIB_USE_DBG_COUNTERS 1
#define _ALGLIB_USE_VENDOR_KERNELS 100
#define _ALGLIB_VENDOR_MEMSTAT 101
#define _ALGLIB_DEBUG_WORKSTEALING 200
#define _ALGLIB_WSDBG_NCORES 201
#define _ALGLIB_WSDBG_PUSHROOT_OK 202
#define _ALGLIB_WSDBG_PUSHROOT_FAILED 203
#define _ALGLIB_SET_GLOBAL_THREADING 1001
#define _ALGLIB_SET_NWORKERS 1002
/* IDs for get_dbg_value */
#define _ALGLIB_GET_ALLOC_COUNTER 0
#define _ALGLIB_GET_CUMULATIVE_ALLOC_SIZE 1
#define _ALGLIB_GET_CUMULATIVE_ALLOC_COUNT 2
#define _ALGLIB_GET_CORES_COUNT 1000
#define _ALGLIB_GET_GLOBAL_THREADING 1001
#define _ALGLIB_GET_NWORKERS 1002
/*************************************************************************
Lock.
This is internal structure which implements lock functionality.
*************************************************************************/
typedef struct
{
#if AE_OS==AE_WINDOWS
volatile ae_int_t * volatile p_lock;
char buf[sizeof(ae_int_t)+AE_LOCK_ALIGNMENT];
#elif AE_OS==AE_POSIX
pthread_mutex_t mutex;
#else
ae_bool is_locked;
#endif
} _lock;
/*
* Error tracking facilities; this fields are modified every time ae_set_error_flag()
* is called with non-zero cond. Thread unsafe access, but it does not matter actually.
*/
static const char * sef_file = "";
static int sef_line = 0;
static const char * sef_xdesc = "";
/*
* Global flags, split into several char-sized variables in order
* to avoid problem with non-atomic reads/writes (single-byte ops
* are atomic on all modern architectures);
*
* Following variables are included:
* * threading-related settings
*/
unsigned char _alglib_global_threading_flags = _ALGLIB_FLG_THREADING_SERIAL>>_ALGLIB_FLG_THREADING_SHIFT;
/*
* DESCRIPTION: recommended number of active workers:
* * positive value >=1 is used to specify exact number of active workers
* * 0 means that ALL available cores are used
* * negative value means that all cores EXCEPT for cores_to_use will be used
* (say, -1 means that all cores except for one will be used). At least one
* core will be used in this case, even if you assign -9999999 to this field.
*
* Default value = 0 (fully parallel execution) when AE_NWORKERS is not defined
* = 0 for manually defined number of cores (AE_NWORKERS is defined)
* PROTECTION: not needed; runtime modification is possible, but we do not need exact
* synchronization.
*/
#if defined(AE_NWORKERS) && (AE_NWORKERS<=0)
#error AE_NWORKERS must be positive number or not defined at all.
#endif
#if defined(AE_NWORKERS)
ae_int_t _alglib_cores_to_use = 0;
#else
ae_int_t _alglib_cores_to_use = 0;
#endif
/*
* Debug counters
*/
ae_int_t _alloc_counter = 0;
ae_int_t _alloc_counter_total = 0;
ae_bool _use_alloc_counter = ae_false;
ae_int_t _dbg_alloc_total = 0;
ae_bool _use_dbg_counters = ae_false;
ae_bool _use_vendor_kernels = ae_true;
ae_bool debug_workstealing = ae_false; /* debug workstealing environment? False by default */
ae_int_t dbgws_pushroot_ok = 0;
ae_int_t dbgws_pushroot_failed = 0;
#ifdef AE_SMP_DEBUGCOUNTERS
__declspec(align(AE_LOCK_ALIGNMENT)) volatile ae_int64_t _ae_dbg_lock_acquisitions = 0;
__declspec(align(AE_LOCK_ALIGNMENT)) volatile ae_int64_t _ae_dbg_lock_spinwaits = 0;
__declspec(align(AE_LOCK_ALIGNMENT)) volatile ae_int64_t _ae_dbg_lock_yields = 0;
#endif
/*
* Allocation debugging
*/
ae_bool _force_malloc_failure = ae_false;
ae_int_t _malloc_failure_after = 0;
/*
* Trace-related declarations:
* alglib_trace_type - trace output type
* alglib_trace_file - file descriptor (to be used by ALGLIB code which
* sends messages to trace log
* alglib_fclose_trace - whether we have to call fclose() when disabling or
* changing trace output
* alglib_trace_tags - string buffer used to store tags + two additional
* characters (leading and trailing commas) + null
* terminator
*/
#define ALGLIB_TRACE_NONE 0
#define ALGLIB_TRACE_FILE 1
#define ALGLIB_TRACE_TAGS_LEN 2048
#define ALGLIB_TRACE_BUFFER_LEN (ALGLIB_TRACE_TAGS_LEN+2+1)
static ae_int_t alglib_trace_type = ALGLIB_TRACE_NONE;
FILE *alglib_trace_file = NULL;
static ae_bool alglib_fclose_trace = ae_false;
static char alglib_trace_tags[ALGLIB_TRACE_BUFFER_LEN];
/*
* Fields for memory allocation over static array
*/
#if AE_MALLOC==AE_BASIC_STATIC_MALLOC
#if AE_THREADING!=AE_SERIAL_UNSAFE
#error Basis static malloc is thread-unsafe; define AE_THREADING=AE_SERIAL_UNSAFE to prove that you know it
#endif
static ae_int_t sm_page_size = 0;
static ae_int_t sm_page_cnt = 0;
static ae_int_t *sm_page_tbl = NULL;
static unsigned char *sm_mem = NULL;
#endif
/*
* These declarations are used to ensure that
* sizeof(ae_bool)=1, sizeof(ae_int32_t)==4, sizeof(ae_int64_t)==8, sizeof(ae_int_t)==sizeof(void*).
* they will lead to syntax error otherwise (array size will be negative).
*
* you can remove them, if you want - they are not used anywhere.
*
*/
static char _ae_bool_must_be_8_bits_wide [1-2*((int)(sizeof(ae_bool))-1)*((int)(sizeof(ae_bool))-1)];
static char _ae_int32_t_must_be_32_bits_wide[1-2*((int)(sizeof(ae_int32_t))-4)*((int)(sizeof(ae_int32_t))-4)];
static char _ae_int64_t_must_be_64_bits_wide[1-2*((int)(sizeof(ae_int64_t))-8)*((int)(sizeof(ae_int64_t))-8)];
static char _ae_uint64_t_must_be_64_bits_wide[1-2*((int)(sizeof(ae_uint64_t))-8)*((int)(sizeof(ae_uint64_t))-8)];
static char _ae_int_t_must_be_pointer_sized [1-2*((int)(sizeof(ae_int_t))-(int)sizeof(void*))*((int)(sizeof(ae_int_t))-(int)(sizeof(void*)))];
/*
* This variable is used to prevent some tricky optimizations which may degrade multithreaded performance.
* It is touched once in the ae_init_pool() function from smp.c in order to prevent optimizations.
*
*/
static volatile ae_int_t ae_never_change_it = 1;
/*************************************************************************
This function should never be called. It is here to prevent spurious
compiler warnings about unused variables (in fact: used).
*************************************************************************/
void ae_never_call_it()
{
ae_touch_ptr((void*)_ae_bool_must_be_8_bits_wide);
ae_touch_ptr((void*)_ae_int32_t_must_be_32_bits_wide);
ae_touch_ptr((void*)_ae_int64_t_must_be_64_bits_wide);
ae_touch_ptr((void*)_ae_uint64_t_must_be_64_bits_wide);
ae_touch_ptr((void*)_ae_int_t_must_be_pointer_sized);
}
void ae_set_dbg_flag(ae_int64_t flag_id, ae_int64_t flag_val)
{
if( flag_id==_ALGLIB_USE_ALLOC_COUNTER )
{
_use_alloc_counter = flag_val!=0;
return;
}
if( flag_id==_ALGLIB_USE_DBG_COUNTERS )
{
_use_dbg_counters = flag_val!=0;
return;
}
if( flag_id==_ALGLIB_USE_VENDOR_KERNELS )
{
_use_vendor_kernels = flag_val!=0;
return;
}
if( flag_id==_ALGLIB_DEBUG_WORKSTEALING )
{
debug_workstealing = flag_val!=0;
return;
}
if( flag_id==_ALGLIB_SET_GLOBAL_THREADING )
{
ae_set_global_threading((ae_uint64_t)flag_val);
return;
}
if( flag_id==_ALGLIB_SET_NWORKERS )
{
_alglib_cores_to_use = (ae_int_t)flag_val;
return;
}
}
ae_int64_t ae_get_dbg_value(ae_int64_t id)
{
if( id==_ALGLIB_GET_ALLOC_COUNTER )
return _alloc_counter;
if( id==_ALGLIB_GET_CUMULATIVE_ALLOC_SIZE )
return _dbg_alloc_total;
if( id==_ALGLIB_GET_CUMULATIVE_ALLOC_COUNT )
return _alloc_counter_total;
if( id==_ALGLIB_VENDOR_MEMSTAT )
{
#if defined(AE_MKL)
return ae_mkl_memstat();
#else
return 0;
#endif
}
/* workstealing counters */
if( id==_ALGLIB_WSDBG_NCORES )
#if defined(AE_SMP)
return ae_cores_count();
#else
return 0;
#endif
if( id==_ALGLIB_WSDBG_PUSHROOT_OK )
return dbgws_pushroot_ok;
if( id==_ALGLIB_WSDBG_PUSHROOT_FAILED )
return dbgws_pushroot_failed;
if( id==_ALGLIB_GET_CORES_COUNT )
#if defined(AE_SMP)
return ae_cores_count();
#else
return 0;
#endif
if( id==_ALGLIB_GET_GLOBAL_THREADING )
return (ae_int64_t)ae_get_global_threading();
if( id==_ALGLIB_GET_NWORKERS )
return (ae_int64_t)_alglib_cores_to_use;
/* unknown value */
return 0;
}
/************************************************************************
This function sets default (global) threading model:
* serial execution
* multithreading, if cores_to_use allows it
************************************************************************/
void ae_set_global_threading(ae_uint64_t flg_value)
{
flg_value = flg_value&_ALGLIB_FLG_THREADING_MASK;
AE_CRITICAL_ASSERT(flg_value==_ALGLIB_FLG_THREADING_SERIAL || flg_value==_ALGLIB_FLG_THREADING_PARALLEL);
_alglib_global_threading_flags = (unsigned char)(flg_value>>_ALGLIB_FLG_THREADING_SHIFT);
}
/************************************************************************
This function gets default (global) threading model:
* serial execution
* multithreading, if cores_to_use allows it
************************************************************************/
ae_uint64_t ae_get_global_threading()
{
return ((ae_uint64_t)_alglib_global_threading_flags)<<_ALGLIB_FLG_THREADING_SHIFT;
}
void ae_set_error_flag(ae_bool *p_flag, ae_bool cond, const char *filename, int lineno, const char *xdesc)
{
if( cond )
{
*p_flag = ae_true;
sef_file = filename;
sef_line = lineno;
sef_xdesc= xdesc;
#ifdef ALGLIB_ABORT_ON_ERROR_FLAG
printf("[ALGLIB] aborting on ae_set_error_flag(cond=true)\n");
printf("[ALGLIB] %s:%d\n", filename, lineno);
printf("[ALGLIB] %s\n", xdesc);
fflush(stdout);
if( alglib_trace_file!=NULL ) fflush(alglib_trace_file);
abort();
#endif
}
}
/************************************************************************
This function returns file name for the last call of ae_set_error_flag()
with non-zero cond parameter.
************************************************************************/
const char * ae_get_last_error_file()
{
return sef_file;
}
/************************************************************************
This function returns line number for the last call of ae_set_error_flag()
with non-zero cond parameter.
************************************************************************/
int ae_get_last_error_line()
{
return sef_line;
}
/************************************************************************
This function returns extra description for the last call of ae_set_error_flag()
with non-zero cond parameter.
************************************************************************/
const char * ae_get_last_error_xdesc()
{
return sef_xdesc;
}
ae_int_t ae_misalignment(const void *ptr, size_t alignment)
{
union _u
{
const void *ptr;
ae_int_t iptr;
} u;
u.ptr = ptr;
return (ae_int_t)(u.iptr%alignment);
}
void* ae_align(void *ptr, size_t alignment)
{
char *result = (char*)ptr;
if( (result-(char*)0)%alignment!=0 )
result += alignment - (result-(char*)0)%alignment;
return result;
}
/************************************************************************
This function maps nworkers number (which can be positive, zero or
negative with 0 meaning "all cores", -1 meaning "all cores -1" and so on)
to "effective", strictly positive workers count.
This function is intended to be used by debugging/testing code which
tests different number of worker threads. It is NOT aligned in any way
with ALGLIB multithreading framework (i.e. it can return non-zero worker
count even for single-threaded GPLed ALGLIB).
************************************************************************/
ae_int_t ae_get_effective_workers(ae_int_t nworkers)
{
ae_int_t ncores;
/* determine cores count */
#if defined(AE_NWORKERS)
ncores = AE_NWORKERS;
#elif AE_OS==AE_WINDOWS
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
ncores = (ae_int_t)(sysInfo.dwNumberOfProcessors);
#elif AE_OS==AE_POSIX
{
long r = sysconf(_SC_NPROCESSORS_ONLN);
ncores = r<=0 ? 1 : r;
}
#else
ncores = 1;
#endif
AE_CRITICAL_ASSERT(ncores>=1);
/* map nworkers to its effective value */
if( nworkers>=1 )
return nworkers>ncores ? ncores : nworkers;
return ncores+nworkers>=1 ? ncores+nworkers : 1;
}
/*************************************************************************
This function belongs to the family of "optional atomics", i.e. atomic
functions which either perform atomic changes - or do nothing at all, if
current compiler settings do not allow us to generate atomic code.
All "optional atomics" are synchronized, i.e. either all of them work - or
no one of the works.
This particular function performs atomic addition on pointer-sized value,
which must be pointer-size aligned.
NOTE: this function is not intended to be extremely high performance one,
so use it only when necessary.
*************************************************************************/
void ae_optional_atomic_add_i(ae_int_t *p, ae_int_t v)
{
AE_CRITICAL_ASSERT(ae_misalignment(p,sizeof(void*))==0);
#if AE_OS==AE_WINDOWS
for(;;)
{
/* perform conversion between ae_int_t* and void**
without compiler warnings about indirection levels */
union _u
{
PVOID volatile * volatile ptr;
volatile ae_int_t * volatile iptr;
} u;
u.iptr = p;
/* atomic read for initial value */
PVOID v0 = InterlockedCompareExchangePointer(u.ptr, NULL, NULL);
/* increment cached value and store */
if( InterlockedCompareExchangePointer(u.ptr, (PVOID)(((char*)v0)+v), v0)==v0 )
break;
}
#elif (AE_COMPILER==AE_GNUC) && (AE_CPU==AE_INTEL) && (__GNUC__*100+__GNUC__>=470)
__atomic_add_fetch(p, v, __ATOMIC_RELAXED);
#else
#endif
}
/*************************************************************************
This function belongs to the family of "optional atomics", i.e. atomic
functions which either perform atomic changes - or do nothing at all, if
current compiler settings do not allow us to generate atomic code.
All "optional atomics" are synchronized, i.e. either all of them work - or
no one of the works.
This particular function performs atomic subtraction on pointer-sized
value, which must be pointer-size aligned.
NOTE: this function is not intended to be extremely high performance one,
so use it only when necessary.
*************************************************************************/
void ae_optional_atomic_sub_i(ae_int_t *p, ae_int_t v)
{
AE_CRITICAL_ASSERT(ae_misalignment(p,sizeof(void*))==0);
#if AE_OS==AE_WINDOWS
for(;;)
{
/* perform conversion between ae_int_t* and void**
without compiler warnings about indirection levels */
union _u
{
PVOID volatile * volatile ptr;
volatile ae_int_t * volatile iptr;
} u;
u.iptr = p;
/* atomic read for initial value, convert it to 1-byte pointer */
PVOID v0 = InterlockedCompareExchangePointer(u.ptr, NULL, NULL);
/* increment cached value and store */
if( InterlockedCompareExchangePointer(u.ptr, (PVOID)(((char*)v0)-v), v0)==v0 )
break;
}
#elif (AE_COMPILER==AE_GNUC) && (AE_CPU==AE_INTEL) && (__GNUC__*100+__GNUC__>=470)
__atomic_sub_fetch(p, v, __ATOMIC_RELAXED);
#else
#endif
}
/*************************************************************************
This function cleans up automatically managed memory before caller terminates
ALGLIB executing by ae_break() or by simply stopping calling callback.
For state!=NULL it calls thread_exception_handler() and the ae_state_clear().
For state==NULL it does nothing.
*************************************************************************/
void ae_clean_up_before_breaking(ae_state *state)
{
if( state!=NULL )
{
if( state->thread_exception_handler!=NULL )
state->thread_exception_handler(state);
ae_state_clear(state);
}
}
/*************************************************************************
This function abnormally aborts program, using one of several ways:
* for state!=NULL and state->break_jump being initialized with call to
ae_state_set_break_jump() - it performs longjmp() to return site.
* otherwise, abort() is called
In all cases, for state!=NULL function sets state->last_error and
state->error_msg fields. It also clears state with ae_state_clear().
If state is not NULL and state->thread_exception_handler is set, it is
called prior to handling error and clearing state.
*************************************************************************/
void ae_break(ae_state *state, ae_error_type error_type, const char *msg)
{
if( state!=NULL )
{
if( alglib_trace_type!=ALGLIB_TRACE_NONE )
ae_trace("---!!! CRITICAL ERROR !!!--- exception with message '%s' was generated\n", msg!=NULL ? msg : "");
ae_clean_up_before_breaking(state);
state->last_error = error_type;
state->error_msg = msg;
if( state->break_jump!=NULL )
longjmp(*(state->break_jump), 1);
else
abort();
}
else
abort();
}
#if AE_MALLOC==AE_BASIC_STATIC_MALLOC
void set_memory_pool(void *ptr, size_t size)
{
/*
* Integrity checks
*/
AE_CRITICAL_ASSERT(sm_page_size==0);
AE_CRITICAL_ASSERT(sm_page_cnt==0);
AE_CRITICAL_ASSERT(sm_page_tbl==NULL);
AE_CRITICAL_ASSERT(sm_mem==NULL);
AE_CRITICAL_ASSERT(size>0);
/*
* Align pointer
*/
size -= ae_misalignment(ptr, sizeof(ae_int_t));
ptr = ae_align(ptr, sizeof(ae_int_t));
/*
* Calculate page size and page count, prepare pointers to page table and memory
*/
sm_page_size = 256;
AE_CRITICAL_ASSERT(size>=(sm_page_size+sizeof(ae_int_t))+sm_page_size); /* we expect to have memory for at least one page + table entry + alignment */
sm_page_cnt = (size-sm_page_size)/(sm_page_size+sizeof(ae_int_t));
AE_CRITICAL_ASSERT(sm_page_cnt>0);
sm_page_tbl = (ae_int_t*)ptr;
sm_mem = (unsigned char*)ae_align(sm_page_tbl+sm_page_cnt, sm_page_size);
/*
* Mark all pages as free
*/
memset(sm_page_tbl, 0, sm_page_cnt*sizeof(ae_int_t));
}
void* ae_static_malloc(size_t size, size_t alignment)
{
int rq_pages, i, j, cur_len;
AE_CRITICAL_ASSERT(size>=0);
AE_CRITICAL_ASSERT(sm_page_size>0);
AE_CRITICAL_ASSERT(sm_page_cnt>0);
AE_CRITICAL_ASSERT(sm_page_tbl!=NULL);
AE_CRITICAL_ASSERT(sm_mem!=NULL);
if( size==0 )
return NULL;
if( _force_malloc_failure )
return NULL;
/* check that page alignment and requested alignment match each other */
AE_CRITICAL_ASSERT(alignment<=sm_page_size);
AE_CRITICAL_ASSERT((sm_page_size%alignment)==0);
/* search long enough sequence of pages */
rq_pages = size/sm_page_size;
if( size%sm_page_size )
rq_pages++;
cur_len = 0;
for(i=0; i<sm_page_cnt;)
{
/* determine length of the sequence of free pages */
if( sm_page_tbl[i]==0 )
cur_len++;
else
{
AE_CRITICAL_ASSERT(sm_page_tbl[i]>0);
cur_len=0;
i += sm_page_tbl[i];
continue;
}
/* found it? */
if( cur_len>=rq_pages )
{
/* update counters (if flag is set) */
if( _use_alloc_counter )
{
ae_optional_atomic_add_i(&_alloc_counter, 1);
ae_optional_atomic_add_i(&_alloc_counter_total, 1);
}
if( _use_dbg_counters )
ae_optional_atomic_add_i(&_dbg_alloc_total, size);
/* mark pages and return */
for(j=0; j<rq_pages; j++)
sm_page_tbl[i-j] = -1;
sm_page_tbl[i-(rq_pages-1)] = rq_pages;
return sm_mem+(i-(rq_pages-1))*sm_page_size;
}
/* next element */
i++;
}
return NULL;
}
void ae_static_free(void *block)
{
ae_int_t page_idx, page_cnt, i;
if( block==NULL )
return;
page_idx = (unsigned char*)block-sm_mem;
AE_CRITICAL_ASSERT(page_idx>=0);
AE_CRITICAL_ASSERT((page_idx%sm_page_size)==0);
page_idx = page_idx/sm_page_size;
AE_CRITICAL_ASSERT(page_idx<sm_page_cnt);
page_cnt = sm_page_tbl[page_idx];
AE_CRITICAL_ASSERT(page_cnt>=1);
for(i=0; i<page_cnt; i++)
sm_page_tbl[page_idx+i] = 0;
/* update counters (if flag is set) */
if( _use_alloc_counter )
ae_optional_atomic_sub_i(&_alloc_counter, 1);
}
void memory_pool_stats(ae_int_t *bytes_used, ae_int_t *bytes_free)
{
int i;
AE_CRITICAL_ASSERT(sm_page_size>0);
AE_CRITICAL_ASSERT(sm_page_cnt>0);
AE_CRITICAL_ASSERT(sm_page_tbl!=NULL);
AE_CRITICAL_ASSERT(sm_mem!=NULL);
/* scan page table */
*bytes_used = 0;
*bytes_free = 0;
for(i=0; i<sm_page_cnt;)
{
if( sm_page_tbl[i]==0 )
{
(*bytes_free)++;
i++;
}
else
{
AE_CRITICAL_ASSERT(sm_page_tbl[i]>0);
*bytes_used += sm_page_tbl[i];
i += sm_page_tbl[i];
}
}
*bytes_used *= sm_page_size;
*bytes_free *= sm_page_size;
}
#endif
void* aligned_malloc(size_t size, size_t alignment)
{
#if AE_MALLOC==AE_BASIC_STATIC_MALLOC
return ae_static_malloc(size, alignment);
#else
char *result = NULL;
if( size==0 )
return NULL;
if( _force_malloc_failure )
return NULL;
if( _malloc_failure_after>0 && _alloc_counter_total>=_malloc_failure_after )
return NULL;
/* allocate */
if( alignment<=1 )
{
/* no alignment, just call alloc */
void *block;
void **p; ;
block = malloc(sizeof(void*)+size);
if( block==NULL )
return NULL;
p = (void**)block;
*p = block;
result = (char*)((char*)block+sizeof(void*));
}
else
{
/* align */
void *block;
block = malloc(alignment-1+sizeof(void*)+size);
if( block==NULL )
return NULL;
result = (char*)block+sizeof(void*);
/*if( (result-(char*)0)%alignment!=0 )
result += alignment - (result-(char*)0)%alignment;*/
result = (char*)ae_align(result, alignment);
*((void**)(result-sizeof(void*))) = block;
}
/* update counters (if flag is set) */
if( _use_alloc_counter )
{
ae_optional_atomic_add_i(&_alloc_counter, 1);
ae_optional_atomic_add_i(&_alloc_counter_total, 1);
}
if( _use_dbg_counters )
ae_optional_atomic_add_i(&_dbg_alloc_total, (ae_int64_t)size);
/* return */
return (void*)result;
#endif
}
void* aligned_extract_ptr(void *block)
{
#if AE_MALLOC==AE_BASIC_STATIC_MALLOC
return NULL;
#else
if( block==NULL )
return NULL;
return *((void**)((char*)block-sizeof(void*)));
#endif
}
void aligned_free(void *block)
{
#if AE_MALLOC==AE_BASIC_STATIC_MALLOC
ae_static_free(block);
#else
void *p;
if( block==NULL )
return;
p = aligned_extract_ptr(block);
free(p);
if( _use_alloc_counter )
ae_optional_atomic_sub_i(&_alloc_counter, 1);
#endif
}
void* eternal_malloc(size_t size)
{
if( size==0 )
return NULL;
if( _force_malloc_failure )
return NULL;
return malloc(size);
}
/************************************************************************
Allocate memory with automatic alignment.
Returns NULL when zero size is specified.
Error handling:
* if state is NULL, returns NULL on allocation error
* if state is not NULL, calls ae_break() on allocation error
************************************************************************/
void* ae_malloc(size_t size, ae_state *state)
{
void *result;
if( size==0 )
return NULL;
result = aligned_malloc(size,AE_DATA_ALIGN);
if( result==NULL && state!=NULL)
ae_break(state, ERR_OUT_OF_MEMORY, "ae_malloc(): out of memory");
return result;
}
void ae_free(void *p)
{
if( p!=NULL )
aligned_free(p);
}
/************************************************************************
Sets pointers to the matrix rows.
* dst must be correctly initialized matrix
* dst->data.ptr points to the beginning of memory block allocated for
row pointers.
* dst->ptr - undefined (initialized during algorithm processing)
* storage parameter points to the beginning of actual storage
************************************************************************/
void ae_matrix_update_row_pointers(ae_matrix *dst, void *storage)
{
char *p_base;
void **pp_ptr;
ae_int_t i;
if( dst->rows>0 && dst->cols>0 )
{
p_base = (char*)storage;
pp_ptr = (void**)dst->data.ptr;
dst->ptr.pp_void = pp_ptr;
for(i=0; i<dst->rows; i++, p_base+=dst->stride*ae_sizeof(dst->datatype))
pp_ptr[i] = p_base;
}
else
dst->ptr.pp_void = NULL;
}
/************************************************************************
Returns size of datatype.
Zero for dynamic types like strings or multiple precision types.
************************************************************************/
ae_int_t ae_sizeof(ae_datatype datatype)
{
switch(datatype)
{
case DT_BOOL: return (ae_int_t)sizeof(ae_bool);
case DT_INT: return (ae_int_t)sizeof(ae_int_t);
case DT_REAL: return (ae_int_t)sizeof(double);
case DT_COMPLEX: return 2*(ae_int_t)sizeof(double);
default: return 0;
}
}
/************************************************************************
Checks that n bytes pointed by ptr are zero.
This function is used in the constructors to check that instance fields
on entry are correctly initialized by zeros.
************************************************************************/
ae_bool ae_check_zeros(const void *ptr, ae_int_t n)
{
ae_int_t nu, nr, i;
unsigned long long c = 0x0;
/*
* determine leading and trailing lengths
*/
nu = n/sizeof(unsigned long long);
nr = n%sizeof(unsigned long long);
/*
* handle leading nu long long elements
*/
if( nu>0 )
{
const unsigned long long *p_ull;
p_ull = (const unsigned long long *)ptr;
for(i=0; i<nu; i++)
c |= p_ull[i];
}
/*
* handle trailing nr char elements
*/
if( nr>0 )
{
const unsigned char *p_uc;
p_uc = ((const unsigned char *)ptr)+nu*sizeof(unsigned long long);
for(i=0; i<nr; i++)
c |= p_uc[i];
}
/*
* done
*/
return c==0x0;
}
/************************************************************************
This dummy function is used to prevent compiler messages about unused
locals in automatically generated code.
It makes nothing - just accepts pointer, "touches" it - and that is all.
It performs several tricky operations without side effects which confuse
compiler so it does not compain about unused locals in THIS function.
************************************************************************/
void ae_touch_ptr(void *p)
{