File: conformance_enumerable_thread_specific.cpp

package info (click to toggle)
onetbb 2022.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,440 kB
  • sloc: cpp: 129,228; ansic: 9,745; python: 808; xml: 183; objc: 176; makefile: 66; sh: 66; awk: 41; javascript: 37
file content (1264 lines) | stat: -rw-r--r-- 50,817 bytes parent folder | download | duplicates (6)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
/*
    Copyright (c) 2005-2021 Intel Corporation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#if _MSC_VER
#if __INTEL_COMPILER
    #pragma warning(disable : 2586) // decorated name length exceeded, name was truncated
#else
    // Workaround for vs2015 and warning name was longer than the compiler limit (4096).
    #pragma warning (disable: 4503)
#endif
#endif

#include "common/test.h"
#include "common/utils.h"
#include "common/utils_report.h"
#include "common/utils_concurrency_limit.h"
#include "common/spin_barrier.h"
#include "common/checktype.h"
#include "common/test_comparisons.h"

#include "oneapi/tbb/detail/_utils.h"
#include "oneapi/tbb/enumerable_thread_specific.h"
#include "oneapi/tbb/parallel_for.h"
#include "oneapi/tbb/parallel_reduce.h"
#include "oneapi/tbb/parallel_invoke.h"
#include "oneapi/tbb/blocked_range.h"
#include "oneapi/tbb/tbb_allocator.h"
#include "oneapi/tbb/global_control.h"
#include "oneapi/tbb/cache_aligned_allocator.h"

#include <cstring>
#include <cstdio>
#include <vector>
#include <numeric>
#include <utility>
#include <atomic>

//! \file conformance_enumerable_thread_specific.cpp
//! \brief Test for [tls.enumerable_thread_specific tls.flattened2d] specification

//------------------------------------------------------------------------------------------------------
// Utility types/classes/functions
//------------------------------------------------------------------------------------------------------

//! Minimum number of threads
static int MinThread = 1;

//! Maximum number of threads
static int MaxThread = 4;

static std::atomic<int> construction_counter;
static std::atomic<int> destruction_counter;

const int REPETITIONS = 5;
const int N = 25000;
const int RANGE_MIN = 5000;
const double EXPECTED_SUM = (REPETITIONS + 1) * N;

//! A minimal class that occupies N bytes.
/** Defines default and copy constructor, and allows implicit operator&. Hides operator=. */
template<size_t N = oneapi::tbb::detail::max_nfs_size>
class minimalNComparable: utils::NoAssign {
private:
    int my_value;
    bool is_constructed;
    char pad[N-sizeof(int) - sizeof(bool)];
public:
    minimalNComparable() : utils::NoAssign(), my_value(0) { ++construction_counter; is_constructed = true; }
    minimalNComparable( const minimalNComparable &m ) : utils::NoAssign(), my_value(m.my_value) { ++construction_counter; is_constructed = true; }
    ~minimalNComparable() { ++destruction_counter; CHECK_FAST(is_constructed); is_constructed = false; }
    void set_value( const int i ) { CHECK_FAST(is_constructed); my_value = i; }
    int value( ) const { CHECK_FAST(is_constructed); return my_value; }

    bool operator==( const minimalNComparable& other ) const { return my_value == other.my_value; }
};

static size_t AlignMask = 0;  // set to cache-line-size - 1

template<typename T>
T& check_alignment(T& t, const char *aname) {
    if( !oneapi::tbb::detail::is_aligned(&t, AlignMask)) {
        // TBB_REVAMP_TODO: previously was REPORT_ONCE
        REPORT("alignment error with %s allocator (%x)\n", aname, (int)size_t(&t) & (AlignMask-1));
    }
    return t;
}

template<typename T>
const T& check_alignment(const T& t, const char *aname) {
    if( !oneapi::tbb::detail::is_aligned(&t, AlignMask)) {
        // TBB_REVAMP_TODO: previously was REPORT_ONCE
        REPORT("alignment error with %s allocator (%x)\n", aname, (int)size_t(&t) & (AlignMask-1));
    }
    return t;
}

// Test constructors which throw.  If an ETS constructor throws before completion,
// the already-built objects are un-constructed.  Do not call the destructor if
// this occurs.

static std::atomic<int> gThrowValue;
static int targetThrowValue = 3;

class Thrower {
public:
    Thrower() {
#if TBB_USE_EXCEPTIONS
        if(++gThrowValue == targetThrowValue) {
            throw std::bad_alloc();
        }
#endif
    }
};

// MyThrower field of ThrowingConstructor will throw after a certain number of
// construction calls.  The constructor unwinder wshould unconstruct the instance
// of check_type<int> that was constructed just before.
class ThrowingConstructor {
    CheckType<int> m_checktype;
    Thrower m_throwing_field;
public:
    int m_cnt;
    ThrowingConstructor() : m_checktype(), m_throwing_field() { m_cnt = 0;}

    bool operator==( const ThrowingConstructor& other ) const { return m_cnt == other.m_cnt; }
private:
};

//
// A helper class that simplifies writing the tests since minimalNComparable does not
// define = or + operators.
//

template< typename T >
struct test_helper {
   static inline void init(T &e) { e = static_cast<T>(0); }
   static inline void sum(T &e, const int addend ) { e += static_cast<T>(addend); }
   static inline void sum(T &e, const double addend ) { e += static_cast<T>(addend); }
   static inline void set(T &e, const int value ) { e = static_cast<T>(value); }
   static inline double get(const T &e ) { return static_cast<double>(e); }
};

template<size_t N>
struct test_helper<minimalNComparable<N> > {
   static inline void init(minimalNComparable<N> &sum) { sum.set_value( 0 ); }
   static inline void sum(minimalNComparable<N> &sum, const int addend ) { sum.set_value( sum.value() + addend); }
   static inline void sum(minimalNComparable<N> &sum, const double addend ) { sum.set_value( sum.value() + static_cast<int>(addend)); }
   static inline void sum(minimalNComparable<N> &sum, const minimalNComparable<N> &addend ) { sum.set_value( sum.value() + addend.value()); }
   static inline void set(minimalNComparable<N> &v, const int value ) { v.set_value( static_cast<int>(value) ); }
   static inline double get(const minimalNComparable<N> &sum ) { return static_cast<double>(sum.value()); }
};

template<>
struct test_helper<ThrowingConstructor> {
   static inline void init(ThrowingConstructor &sum) { sum.m_cnt = 0; }
   static inline void sum(ThrowingConstructor &sum, const int addend ) { sum.m_cnt += addend; }
   static inline void sum(ThrowingConstructor &sum, const double addend ) { sum.m_cnt += static_cast<int>(addend); }
   static inline void sum(ThrowingConstructor &sum, const ThrowingConstructor &addend ) { sum.m_cnt += addend.m_cnt; }
   static inline void set(ThrowingConstructor &v, const int value ) { v.m_cnt = static_cast<int>(value); }
   static inline double get(const ThrowingConstructor &sum ) { return static_cast<double>(sum.m_cnt); }
};

//! Tag class used to make certain constructors hard to invoke accidentally.
struct SecretTagType {} SecretTag;

//// functors and routines for initialization and combine

//! Counts instances of FunctorFinit
static std::atomic<int> FinitCounter;

template <typename T, int Value>
struct FunctorFinit {
    FunctorFinit( const FunctorFinit& ) {++FinitCounter;}
    FunctorFinit( SecretTagType ) {++FinitCounter;}
    ~FunctorFinit() {--FinitCounter;}
    T operator()() { return Value; }
};

template <int Value>
struct FunctorFinit<ThrowingConstructor,Value> {
    FunctorFinit( const FunctorFinit& ) {++FinitCounter;}
    FunctorFinit( SecretTagType ) {++FinitCounter;}
    ~FunctorFinit() {--FinitCounter;}
    ThrowingConstructor operator()() { ThrowingConstructor temp; temp.m_cnt = Value; return temp; }
};

template <size_t N, int Value>
struct FunctorFinit<minimalNComparable<N>,Value> {
    FunctorFinit( const FunctorFinit& ) {++FinitCounter;}
    FunctorFinit( SecretTagType ) {++FinitCounter;}
    ~FunctorFinit() {--FinitCounter;}
    minimalNComparable<N> operator()() {
        minimalNComparable<N> result;
        result.set_value( Value );
        return result;
    }
};

// Addition

template <typename T>
struct FunctorAddCombineRef {
    T operator()(const T& left, const T& right) const {
        return left+right;
    }
};

template <size_t N>
struct FunctorAddCombineRef<minimalNComparable<N> > {
    minimalNComparable<N> operator()(const minimalNComparable<N>& left, const minimalNComparable<N>& right) const {
        minimalNComparable<N> result;
        result.set_value( left.value() + right.value() );
        return result;
    }
};

template <>
struct FunctorAddCombineRef<ThrowingConstructor> {
    ThrowingConstructor operator()(const ThrowingConstructor& left, const ThrowingConstructor& right) const {
        ThrowingConstructor result;
        result.m_cnt = ( left.m_cnt + right.m_cnt );
        return result;
    }
};

template <typename T>
struct FunctorAddCombine {
    T operator()(T left, T right ) const {
        return FunctorAddCombineRef<T>()( left, right );
    }
};

template <typename T>
T FunctionAddByRef( const T &left, const T &right) {
    return FunctorAddCombineRef<T>()( left, right );
}

template <typename T>
T FunctionAdd( T left, T right) { return FunctionAddByRef(left,right); }

template <typename T>
class Accumulator {
public:
    Accumulator(T& result) : my_result(result) {}
    Accumulator(const Accumulator& other) : my_result(other.my_result) {}
    Accumulator& operator=(const Accumulator& other) {
        test_helper<T>::set(my_result, test_helper<T>::get(other));
        return *this;
    }
    void operator()(const T& new_bit) { test_helper<T>::sum(my_result, new_bit); }
private:
    T& my_result;
};

template <typename T>
class ClearingAccumulator {
public:
    ClearingAccumulator(T& result) : my_result(result) {}
    ClearingAccumulator(const ClearingAccumulator& other) : my_result(other.my_result) {}
    ClearingAccumulator& operator=(const ClearingAccumulator& other) {
        test_helper<T>::set(my_result, test_helper<T>::get(other));
        return *this;
    }
    void operator()(T& new_bit) {
        test_helper<T>::sum(my_result, new_bit);
        test_helper<T>::init(new_bit);
    }
    static void AssertClean(const T& thread_local_value) {
        T zero;
        test_helper<T>::init(zero);
        REQUIRE_MESSAGE(test_helper<T>::get(thread_local_value)==test_helper<T>::get(zero),
               "combine_each does not allow to modify thread local values?");
    }
private:
    T& my_result;
};

//// end functors and routines

//------------------------------------------------------------------------------------------------------
// Tests for tests cases
//------------------------------------------------------------------------------------------------------

template <typename T, template<class> class Allocator>
class parallel_scalar_body: utils::NoAssign {
    typedef oneapi::tbb::enumerable_thread_specific<T, Allocator<T> > ets_type;
    ets_type &sums;
    const char* allocator_name;

public:

    parallel_scalar_body ( ets_type &_sums, const char *alloc_name ) : sums(_sums), allocator_name(alloc_name) { }

    void operator()( const oneapi::tbb::blocked_range<int> &r ) const {
        for (int i = r.begin(); i != r.end(); ++i)
            test_helper<T>::sum( check_alignment(sums.local(),allocator_name), 1 );
    }

};

template< typename T, template<class> class Allocator>
void run_parallel_scalar_tests_nocombine(const char* /* test_name */, const char *allocator_name) {

    typedef oneapi::tbb::enumerable_thread_specific<T, Allocator<T> > ets_type;

    Checker<T> my_check;

    gThrowValue = 0;
    struct fail_on_exception_guard {
        bool dismiss = false;
        ~fail_on_exception_guard() {
            if (!dismiss) {
                FAIL("The exception is not expected");
            }
        }
    } guard;
    T default_value{};
    guard.dismiss = true;

    gThrowValue = 0;
    {
        // We assume that static_sums zero-initialized or has a default constructor that zeros it.
        ets_type static_sums = ets_type( T() );

        T exemplar;
        test_helper<T>::init(exemplar);

        for (int p = std::max(MinThread, 2); p <= MaxThread; ++p) {
            oneapi::tbb::global_control gc(oneapi::tbb::global_control::max_allowed_parallelism, p);

            T iterator_sum;
            test_helper<T>::init(iterator_sum);

            T finit_ets_sum;
            test_helper<T>::init(finit_ets_sum);

            T const_iterator_sum;
            test_helper<T>::init(const_iterator_sum);

            T range_sum;
            test_helper<T>::init(range_sum);

            T const_range_sum;
            test_helper<T>::init(const_range_sum);

            T cconst_sum;
            test_helper<T>::init(cconst_sum);

            T assign_sum;
            test_helper<T>::init(assign_sum);

            T cassgn_sum;
            test_helper<T>::init(cassgn_sum);
            T non_cassgn_sum;
            test_helper<T>::init(non_cassgn_sum);

            T static_sum;
            test_helper<T>::init(static_sum);

            for (int t = -1; t < REPETITIONS; ++t) {
                static_sums.clear();

                ets_type sums(exemplar);
                FunctorFinit<T,0> my_finit(SecretTag);
                ets_type finit_ets(my_finit);

                REQUIRE( sums.empty());
                oneapi::tbb::parallel_for( oneapi::tbb::blocked_range<int>( 0, N*p, RANGE_MIN ), parallel_scalar_body<T,Allocator>( sums, allocator_name ) );
                REQUIRE( !sums.empty());

                REQUIRE( finit_ets.empty());
                oneapi::tbb::parallel_for( oneapi::tbb::blocked_range<int>( 0, N*p, RANGE_MIN ), parallel_scalar_body<T,Allocator>( finit_ets, allocator_name ) );
                REQUIRE( !finit_ets.empty());

                REQUIRE(static_sums.empty());
                oneapi::tbb::parallel_for( oneapi::tbb::blocked_range<int>( 0, N*p, RANGE_MIN ), parallel_scalar_body<T,Allocator>( static_sums, allocator_name ) );
                REQUIRE( !static_sums.empty());

                // use iterator
                typename ets_type::size_type size = 0;
                for ( typename ets_type::iterator i = sums.begin(); i != sums.end(); ++i ) {
                     ++size;
                     test_helper<T>::sum(iterator_sum, *i);
                }
                REQUIRE( sums.size() == size);

                // use const_iterator
                for ( typename ets_type::const_iterator i = sums.begin(); i != sums.end(); ++i ) {
                     test_helper<T>::sum(const_iterator_sum, *i);
                }

                // use range_type
                typename ets_type::range_type r = sums.range();
                for ( typename ets_type::range_type::const_iterator i = r.begin(); i != r.end(); ++i ) {
                     test_helper<T>::sum(range_sum, *i);
                }

                // use const_range_type
                const ets_type& csums = sums;
                typename ets_type::const_range_type cr = csums.range();
                for ( typename ets_type::const_range_type::iterator i = cr.begin(); i != cr.end(); ++i ) {
                     test_helper<T>::sum(const_range_sum, *i);
                }

                // test copy constructor, with TLS-cached locals
                typedef typename oneapi::tbb::enumerable_thread_specific<T, Allocator<T>, oneapi::tbb::ets_key_per_instance> cached_ets_type;

                cached_ets_type cconst(sums);
                oneapi::tbb::parallel_for( oneapi::tbb::blocked_range<int>(0, N*p, RANGE_MIN), [&]( const oneapi::tbb::blocked_range<int>& ) {
                    bool exists = false;
                    T& ref = cconst.local(exists);
                    CHECK( (exists || ref == default_value) );
                } );
                cached_ets_type cconst_to_assign1 = cconst;
                cached_ets_type cconst_to_assign2;
                cconst_to_assign2 = std::move(cconst_to_assign1);
                REQUIRE(cconst_to_assign2.size() == cconst.size());

                for ( typename cached_ets_type::const_iterator i = cconst.begin(); i != cconst.end(); ++i ) {
                     test_helper<T>::sum(cconst_sum, *i);
                }

                // test assignment
                ets_type assigned;
                assigned = sums;

                for ( typename ets_type::const_iterator i = assigned.begin(); i != assigned.end(); ++i ) {
                     test_helper<T>::sum(assign_sum, *i);
                }

                // test assign to and from cached locals
                cached_ets_type cassgn;
                cassgn = sums;
                for ( typename cached_ets_type::const_iterator i = cassgn.begin(); i != cassgn.end(); ++i ) {
                     test_helper<T>::sum(cassgn_sum, *i);
                }

                ets_type non_cassgn;
                non_cassgn = cassgn;
                for ( typename ets_type::const_iterator i = non_cassgn.begin(); i != non_cassgn.end(); ++i ) {
                     test_helper<T>::sum(non_cassgn_sum, *i);
                }

                // test finit-initialized ets
                for(typename ets_type::const_iterator i = finit_ets.begin(); i != finit_ets.end(); ++i) {
                    test_helper<T>::sum(finit_ets_sum, *i);
                }

                // test static ets
                for(typename ets_type::const_iterator i = static_sums.begin(); i != static_sums.end(); ++i) {
                    test_helper<T>::sum(static_sum, *i);
                }

            }

            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(iterator_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(const_iterator_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(range_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(const_range_sum));

            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(cconst_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(assign_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(cassgn_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(non_cassgn_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(finit_ets_sum));
            REQUIRE(EXPECTED_SUM*p == test_helper<T>::get(static_sum));
        }
    }  // Checker block
}

template< typename T, template<class> class Allocator>
void run_parallel_scalar_tests(const char* test_name, const char* allocator_name) {

    typedef oneapi::tbb::enumerable_thread_specific<T, Allocator<T> > ets_type;
    bool exception_caught = false;

    // We assume that static_sums zero-initialized or has a default constructor that zeros it.
    ets_type static_sums = ets_type( T() );

    T exemplar;
    test_helper<T>::init(exemplar);

    int test_throw_count = 10;
    // the test will be performed repeatedly until it does not throw.  For non-throwing types
    // this means once; for the throwing type test it may loop two or three times.  The
    // value of targetThrowValue will determine when and if the test will throw.
    do {
        targetThrowValue = test_throw_count;  // keep testing until we get no exception
        exception_caught = false;
#if TBB_USE_EXCEPTIONS
        try {
#endif
            run_parallel_scalar_tests_nocombine<T,Allocator>(test_name, allocator_name);
#if TBB_USE_EXCEPTIONS
        }
        catch(...) {}
#endif
        for (int p = std::max(MinThread, 2); p <= MaxThread; ++p) {
            oneapi::tbb::global_control gc(oneapi::tbb::global_control::max_allowed_parallelism, p);

            gThrowValue = 0;

            T combine_sum;
            test_helper<T>::init(combine_sum);

            T combine_ref_sum;
            test_helper<T>::init(combine_ref_sum);

            T accumulator_sum;
            test_helper<T>::init(accumulator_sum);

            T static_sum;
            test_helper<T>::init(static_sum);

            T clearing_accumulator_sum;
            test_helper<T>::init(clearing_accumulator_sum);

            {
                Checker<T> my_check;
#if TBB_USE_EXCEPTIONS
                try
#endif
                {
                    for (int t = -1; t < REPETITIONS; ++t) {
                        static_sums.clear();

                        ets_type sums(exemplar);

                        REQUIRE(sums.empty());
                        oneapi::tbb::parallel_for(oneapi::tbb::blocked_range<int>(0, N * p, RANGE_MIN),
                            parallel_scalar_body<T, Allocator>(sums, allocator_name));
                        REQUIRE(!sums.empty());

                        REQUIRE(static_sums.empty());
                        oneapi::tbb::parallel_for(oneapi::tbb::blocked_range<int>(0, N * p, RANGE_MIN),
                            parallel_scalar_body<T, Allocator>(static_sums, allocator_name));
                        REQUIRE(!static_sums.empty());

                        // Use combine
                        test_helper<T>::sum(combine_sum, sums.combine(FunctionAdd<T>));
                        test_helper<T>::sum(combine_ref_sum, sums.combine(FunctionAddByRef<T>));
                        test_helper<T>::sum(static_sum, static_sums.combine(FunctionAdd<T>));

                        // Accumulate with combine_each
                        sums.combine_each(Accumulator<T>(accumulator_sum));
                        // Accumulate and clear thread-local values
                        sums.combine_each(ClearingAccumulator<T>(clearing_accumulator_sum));
                        // Check that the values were cleared
                        sums.combine_each(ClearingAccumulator<T>::AssertClean);
                    }
                }
#if TBB_USE_EXCEPTIONS
                catch (...) {
                    exception_caught = true;
                }
#endif
            }

            if (!exception_caught) {
                REQUIRE(EXPECTED_SUM * p == test_helper<T>::get(combine_sum));
                REQUIRE(EXPECTED_SUM * p == test_helper<T>::get(combine_ref_sum));
                REQUIRE(EXPECTED_SUM * p == test_helper<T>::get(static_sum));
                REQUIRE(EXPECTED_SUM * p == test_helper<T>::get(accumulator_sum));
                REQUIRE(EXPECTED_SUM * p == test_helper<T>::get(clearing_accumulator_sum));
            }

        }  // MinThread .. MaxThread
        test_throw_count += 10;  // keep testing until we don't get an exception
    } while (exception_caught && test_throw_count < 200);
    REQUIRE_MESSAGE(!exception_caught, "No non-exception test completed");
}

template <typename T, template<class> class Allocator>
class parallel_vector_for_body: utils::NoAssign {
    typedef std::vector<T, oneapi::tbb::tbb_allocator<T> > container_type;
    typedef oneapi::tbb::enumerable_thread_specific< container_type, Allocator<container_type> > ets_type;
    ets_type &locals;
    const char *allocator_name;

public:

    parallel_vector_for_body ( ets_type &_locals, const char *aname ) : locals(_locals), allocator_name(aname) { }

    void operator()( const oneapi::tbb::blocked_range<int> &r ) const {
        T one;
        test_helper<T>::set(one, 1);

        for (int i = r.begin(); i < r.end(); ++i) {
            check_alignment(locals.local(),allocator_name).push_back( one );
        }
    }

};

template <typename R, typename T>
struct parallel_vector_reduce_body {

    T sum;
    size_t count;
    typedef std::vector<T, oneapi::tbb::tbb_allocator<T> > container_type;

    parallel_vector_reduce_body ( ) : count(0) { test_helper<T>::init(sum); }
    parallel_vector_reduce_body ( parallel_vector_reduce_body<R, T> &, oneapi::tbb::split ) : count(0) {  test_helper<T>::init(sum); }

    void operator()( const R &r ) {
        for (typename R::iterator ri = r.begin(); ri != r.end(); ++ri) {
            const container_type &v = *ri;
            ++count;
            for (typename container_type::const_iterator vi = v.begin(); vi != v.end(); ++vi) {
                test_helper<T>::sum(sum, *vi);
            }
        }
    }

    void join( const parallel_vector_reduce_body &b ) {
        test_helper<T>::sum(sum,b.sum);
        count += b.count;
    }

};

template< typename T, template<class> class Allocator>
void run_parallel_vector_tests(const char* /* test_name */, const char *allocator_name) {
    typedef std::vector<T, oneapi::tbb::tbb_allocator<T> > container_type;
    typedef oneapi::tbb::enumerable_thread_specific< container_type, Allocator<container_type> > ets_type;

    for (int p = std::max(MinThread, 2); p <= MaxThread; ++p) {
        oneapi::tbb::global_control gc(oneapi::tbb::global_control::max_allowed_parallelism, p);

        T sum;
        test_helper<T>::init(sum);

        for (int t = -1; t < REPETITIONS; ++t) {
            ets_type vs;

            REQUIRE( vs.empty() );
            oneapi::tbb::parallel_for( oneapi::tbb::blocked_range<int> (0, N*p, RANGE_MIN),
                               parallel_vector_for_body<T,Allocator>( vs, allocator_name ) );
            REQUIRE( !vs.empty() );

            // copy construct
            ets_type vs2(vs); // this causes an assertion failure, related to allocators...

            // assign
            ets_type vs3;
            vs3 = vs;

            parallel_vector_reduce_body< typename ets_type::const_range_type, T > pvrb;
            oneapi::tbb::parallel_reduce ( vs.range(1), pvrb );

            test_helper<T>::sum(sum, pvrb.sum);

            REQUIRE( vs.size() == pvrb.count );
            REQUIRE( vs2.size() == pvrb.count );
            REQUIRE( vs3.size() == pvrb.count );

            oneapi::tbb::flattened2d<ets_type> fvs = flatten2d(vs);
            size_t ccount = fvs.size();
            REQUIRE( ccount == size_t(N*p) );
            size_t elem_cnt = 0;
            typename oneapi::tbb::flattened2d<ets_type>::iterator it;
            auto it2(it);
            it = fvs.begin();
            REQUIRE(it != it2);
            typename oneapi::tbb::flattened2d<ets_type>::iterator it3;
            typename oneapi::tbb::flattened2d<ets_type>::const_iterator cit = fvs.begin();
            it3 = cit;
            REQUIRE(it3 == cit);
            REQUIRE(it3.operator->() == &(*it3));

            for(typename oneapi::tbb::flattened2d<ets_type>::const_iterator i = fvs.begin(); i != fvs.end(); ++i) {
                ++elem_cnt;
            };
            REQUIRE( ccount == elem_cnt );

            elem_cnt = 0;
            for(typename oneapi::tbb::flattened2d<ets_type>::iterator i = fvs.begin(); i != fvs.end(); i++) {
                ++elem_cnt;
            };
            REQUIRE( ccount == elem_cnt );

            // Test the ETS constructor with multiple args
            T minus_one;
            test_helper<T>::set(minus_one, -1);
            // Set ETS to construct "local" vectors pre-occupied with 25 "minus_one"s
            // Cast 25 to size_type to prevent Intel Compiler SFINAE compilation issues with gcc 5.
            ets_type vvs( typename container_type::size_type(25), minus_one, oneapi::tbb::tbb_allocator<T>() );
            REQUIRE( vvs.empty() );
            oneapi::tbb::parallel_for ( oneapi::tbb::blocked_range<int> (0, N*p, RANGE_MIN), parallel_vector_for_body<T,Allocator>( vvs, allocator_name ) );
            REQUIRE( !vvs.empty() );

            parallel_vector_reduce_body< typename ets_type::const_range_type, T > pvrb2;
            oneapi::tbb::parallel_reduce ( vvs.range(1), pvrb2 );
            REQUIRE( pvrb2.count == vvs.size() );
            REQUIRE( test_helper<T>::get(pvrb2.sum) == N*p-pvrb2.count*25 );

            oneapi::tbb::flattened2d<ets_type> fvvs = flatten2d(vvs);
            ccount = fvvs.size();
            REQUIRE( ccount == N*p+pvrb2.count*25 );
        }

        double result_value = test_helper<T>::get(sum);
        REQUIRE( EXPECTED_SUM*p == result_value);
    }
}

template<typename T, template<class> class Allocator>
void run_cross_type_vector_tests(const char* /* test_name */) {
    const char* allocator_name = "default";
    typedef std::vector<T, oneapi::tbb::tbb_allocator<T> > container_type;

    for (int p = std::max(MinThread, 2); p <= MaxThread; ++p) {
        oneapi::tbb::global_control gc(oneapi::tbb::global_control::max_allowed_parallelism, p);

        T sum;
        test_helper<T>::init(sum);

        for (int t = -1; t < REPETITIONS; ++t) {
            typedef typename oneapi::tbb::enumerable_thread_specific< container_type, Allocator<container_type>, oneapi::tbb::ets_no_key > ets_nokey_type;
            typedef typename oneapi::tbb::enumerable_thread_specific< container_type, Allocator<container_type>, oneapi::tbb::ets_key_per_instance > ets_tlskey_type;
            ets_nokey_type vs;

            REQUIRE( vs.empty());
            oneapi::tbb::parallel_for ( oneapi::tbb::blocked_range<int> (0, N*p, RANGE_MIN), parallel_vector_for_body<T, Allocator>( vs, allocator_name ) );
            REQUIRE( !vs.empty());

            // copy construct
            ets_tlskey_type vs2(vs);

            // assign
            ets_nokey_type vs3;
            vs3 = vs2;

            parallel_vector_reduce_body< typename ets_nokey_type::const_range_type, T > pvrb;
            oneapi::tbb::parallel_reduce ( vs3.range(1), pvrb );

            test_helper<T>::sum(sum, pvrb.sum);

            REQUIRE( vs3.size() == pvrb.count);

            oneapi::tbb::flattened2d<ets_nokey_type> fvs = flatten2d(vs3);
            size_t ccount = fvs.size();
            size_t elem_cnt = 0;
            for(typename oneapi::tbb::flattened2d<ets_nokey_type>::const_iterator i = fvs.begin(); i != fvs.end(); ++i) {
                ++elem_cnt;
            };
            REQUIRE(ccount == elem_cnt);

            elem_cnt = 0;
            for(typename oneapi::tbb::flattened2d<ets_nokey_type>::iterator i = fvs.begin(); i != fvs.end(); ++i) {
                ++elem_cnt;
            };
            REQUIRE(ccount == elem_cnt);

            oneapi::tbb::flattened2d<ets_nokey_type> fvs2 = flatten2d(vs3, vs3.begin(), std::next(vs3.begin()));
            REQUIRE(std::distance(fvs2.begin(), fvs2.end()) == vs3.begin()->size());
            const oneapi::tbb::flattened2d<ets_nokey_type>& cfvs2(fvs2);
            REQUIRE(std::distance(cfvs2.begin(), cfvs2.end()) == vs3.begin()->size());
        }

        double result_value = test_helper<T>::get(sum);
        REQUIRE( EXPECTED_SUM*p == result_value);
    }
}

template< typename T >
void run_serial_scalar_tests(const char* /* test_name */) {
    T sum;
    test_helper<T>::init(sum);

    for (int t = -1; t < REPETITIONS; ++t) {
        for (int i = 0; i < N; ++i) {
            test_helper<T>::sum(sum,1);
        }
    }

    double result_value = test_helper<T>::get(sum);
    REQUIRE( EXPECTED_SUM == result_value);
}

template< typename T >
void run_serial_vector_tests(const char* /* test_name */) {
    T sum;
    test_helper<T>::init(sum);
    T one;
    test_helper<T>::set(one, 1);

    for (int t = -1; t < REPETITIONS; ++t) {
        std::vector<T, oneapi::tbb::tbb_allocator<T> > v;
        for (int i = 0; i < N; ++i) {
            v.push_back( one );
        }
        for (typename std::vector<T, oneapi::tbb::tbb_allocator<T> >::const_iterator i = v.begin(); i != v.end(); ++i)
            test_helper<T>::sum(sum, *i);
    }

    double result_value = test_helper<T>::get(sum);
    REQUIRE( EXPECTED_SUM == result_value);
}

const size_t line_size = oneapi::tbb::detail::max_nfs_size;

void run_reference_check() {
    run_serial_scalar_tests<int>("int");
    run_serial_scalar_tests<double>("double");
    run_serial_scalar_tests<minimalNComparable<> >("minimalNComparable<>");
    run_serial_vector_tests<int>("std::vector<int, oneapi::tbb::tbb_allocator<int> >");
    run_serial_vector_tests<double>("std::vector<double, oneapi::tbb::tbb_allocator<double> >");
}

template<template<class>class Allocator>
void run_parallel_tests(const char *allocator_name) {
    run_parallel_scalar_tests<int, Allocator>("int",allocator_name);
    run_parallel_scalar_tests<double, Allocator>("double",allocator_name);
    run_parallel_scalar_tests_nocombine<minimalNComparable<>,Allocator>("minimalNComparable<>",allocator_name);
    run_parallel_scalar_tests<ThrowingConstructor, Allocator>("ThrowingConstructor", allocator_name);
    run_parallel_vector_tests<int, Allocator>("std::vector<int, oneapi::tbb::tbb_allocator<int> >",allocator_name);
    run_parallel_vector_tests<double, Allocator>("std::vector<double, oneapi::tbb::tbb_allocator<double> >",allocator_name);
}

void run_cross_type_tests() {
    // cross-type scalar tests are part of run_parallel_scalar_tests_nocombine
    run_cross_type_vector_tests<int, oneapi::tbb::tbb_allocator>("std::vector<int, oneapi::tbb::tbb_allocator<int> >");
    run_cross_type_vector_tests<double, oneapi::tbb::tbb_allocator>("std::vector<double, oneapi::tbb::tbb_allocator<double> >");
}

template<typename T, template<class> class Allocator, typename Init>
oneapi::tbb::enumerable_thread_specific<T,Allocator<T> > MakeETS( Init init ) {
    return oneapi::tbb::enumerable_thread_specific<T,Allocator<T> >(init);
}
// In some GCC versions, parameter packs in lambdas might cause compile errors
template<typename ETS, typename... P>
struct MakeETS_Functor {
    ETS operator()( typename std::decay<P>::type&&... params ) {
        return ETS(std::move(params)...);
    }
};
template<typename T, template<class> class Allocator, typename... P>
oneapi::tbb::enumerable_thread_specific<T,Allocator<T> > MakeETS( oneapi::tbb::detail::stored_pack<P...> pack ) {
    typedef oneapi::tbb::enumerable_thread_specific<T,Allocator<T> > result_type;
    return oneapi::tbb::detail::call_and_return< result_type >(
        MakeETS_Functor<result_type,P...>(), std::move(pack)
    );
}

template<typename T, template<class> class Allocator, typename InitSrc, typename InitDst, typename Validator>
void ets_copy_assign_test( InitSrc init1, InitDst init2, Validator check, const char *allocator_name ) {
    typedef oneapi::tbb::enumerable_thread_specific<T, Allocator<T> > ets_type;

    // Create the source instance
    const ets_type& cref_binder = MakeETS<T, Allocator>(init1);
    ets_type& source = const_cast<ets_type&>(cref_binder);
    check(check_alignment(source.local(),allocator_name));

    // Test copy construction
    bool existed = false;
    ets_type copy(source);
    check(check_alignment(copy.local(existed),allocator_name));
    REQUIRE_MESSAGE(existed, "Local data not created by ETS copy constructor");
    copy.clear();
    check(check_alignment(copy.local(),allocator_name));

    // Test assignment
    existed = false;
    ets_type assign(init2);
    assign = source;
    check(check_alignment(assign.local(existed),allocator_name));
    REQUIRE_MESSAGE(existed, "Local data not created by ETS assignment");
    assign.clear();
    check(check_alignment(assign.local(),allocator_name));

    // Create the source instance
    ets_type&& rvref_binder = MakeETS<T, Allocator>(init1);
    check(check_alignment(rvref_binder.local(),allocator_name));

    // Test move construction
    existed = false;
    ets_type moved(rvref_binder);
    check(check_alignment(moved.local(existed),allocator_name));
    REQUIRE_MESSAGE(existed, "Local data not created by ETS move constructor");
    moved.clear();
    check(check_alignment(moved.local(),allocator_name));

    // Test assignment
    existed = false;
    ets_type move_assign(init2);
    move_assign = std::move(moved);
    check(check_alignment(move_assign.local(existed),allocator_name));
    REQUIRE_MESSAGE(existed, "Local data not created by ETS move assignment");
    move_assign.clear();
    check(check_alignment(move_assign.local(),allocator_name));
}

template<typename T, int Expected>
struct Validator {
    void operator()( const T& value ) {
        REQUIRE(test_helper<T>::get(value) == Expected);
    }
    void operator()( const std::pair<int,T>& value ) {
        REQUIRE(value.first > 0);
        REQUIRE(test_helper<T>::get(value.second) == Expected*value.first);
    }
};

template <typename T, template<class> class Allocator>
void run_assign_and_copy_constructor_test(const char* /* test_name */, const char *allocator_name) {
    #define EXPECTED 3142

    // test with exemplar initializer
    T src_init;
    test_helper<T>::set(src_init,EXPECTED);
    T other_init;
    test_helper<T>::init(other_init);
    ets_copy_assign_test<T, Allocator>(src_init, other_init, Validator<T,EXPECTED>(), allocator_name);

    // test with function initializer
    FunctorFinit<T,EXPECTED> src_finit(SecretTag);
    FunctorFinit<T,0> other_finit(SecretTag);
    ets_copy_assign_test<T, Allocator>(src_finit, other_finit, Validator<T,EXPECTED>(), allocator_name);

    // test with multi-argument "emplace" initializer
    // The arguments are wrapped into oneapi::tbb::internal::stored_pack to avoid variadic templates in ets_copy_assign_test.
    test_helper<T>::set(src_init,EXPECTED*17);
    ets_copy_assign_test< std::pair<int,T>, Allocator>(oneapi::tbb::detail::save_pack(17,src_init), std::make_pair(-1,T()), Validator<T,EXPECTED>(), allocator_name);
    #undef EXPECTED
}

template< template<class> class Allocator>
void run_assignment_and_copy_constructor_tests(const char* allocator_name) {
    run_assign_and_copy_constructor_test<int, Allocator>("int", allocator_name);
    run_assign_and_copy_constructor_test<double, Allocator>("double", allocator_name);
    // Try class sizes that are close to a cache line in size, in order to check padding calculations.
    run_assign_and_copy_constructor_test<minimalNComparable<line_size-1>, Allocator >("minimalNComparable<line_size-1>", allocator_name);
    run_assign_and_copy_constructor_test<minimalNComparable<line_size>, Allocator >("minimalNComparable<line_size>", allocator_name);
    run_assign_and_copy_constructor_test<minimalNComparable<line_size+1>, Allocator >("minimalNComparable<line_size+1>", allocator_name);
    REQUIRE(FinitCounter==0);
}

// Class with no default constructor
class HasNoDefaultConstructor {
    HasNoDefaultConstructor();
public:
    HasNoDefaultConstructor( SecretTagType ) {}
};
// Initialization functor for HasNoDefaultConstructor
struct HasNoDefaultConstructorFinit {
    HasNoDefaultConstructor operator()() {
        return HasNoDefaultConstructor(SecretTag);
    }
};
// Combine functor for HasNoDefaultConstructor
struct HasNoDefaultConstructorCombine {
    HasNoDefaultConstructor operator()( HasNoDefaultConstructor, HasNoDefaultConstructor ) {
        return HasNoDefaultConstructor(SecretTag);
    }
};

// Class that only has a constructor with multiple parameters and a move constructor
class HasSpecialAndMoveCtor : utils::NoCopy {
    HasSpecialAndMoveCtor();
public:
    HasSpecialAndMoveCtor( SecretTagType, size_t = size_t(0), const char* = "" ) {}
    HasSpecialAndMoveCtor( HasSpecialAndMoveCtor&& ) {}
};

// No-op combine-each functor
template<typename V>
struct EmptyCombineEach {
    void operator()( const V& ) { }
};

//! Test situations where only default constructor or copy constructor is required.
template<template<class> class Allocator>
void TestInstantiation(const char* /* allocator_name */) {
    // Test instantiation is possible when copy constructor is not required.
    oneapi::tbb::enumerable_thread_specific<utils::NoCopy, Allocator<utils::NoCopy> > ets1;
    ets1.local();
    ets1.combine_each(EmptyCombineEach<utils::NoCopy>());

    // Test instantiation when default constructor is not required, because exemplar is provided.
    HasNoDefaultConstructor x(SecretTag);
    oneapi::tbb::enumerable_thread_specific<HasNoDefaultConstructor, Allocator<HasNoDefaultConstructor> > ets2(x);
    ets2.local();
    ets2.combine(HasNoDefaultConstructorCombine());

    // Test instantiation when default constructor is not required, because init function is provided.
    HasNoDefaultConstructorFinit f;
    oneapi::tbb::enumerable_thread_specific<HasNoDefaultConstructor, Allocator<HasNoDefaultConstructor> > ets3(f);
    ets3.local();
    ets3.combine(HasNoDefaultConstructorCombine());

    // Test instantiation with multiple arguments
    oneapi::tbb::enumerable_thread_specific<HasSpecialAndMoveCtor, Allocator<HasSpecialAndMoveCtor> > ets4(SecretTag, 0x42, "meaningless");
    ets4.local();
    ets4.combine_each(EmptyCombineEach<HasSpecialAndMoveCtor>());
    // Test instantiation with one argument that should however use the variadic constructor
    oneapi::tbb::enumerable_thread_specific<HasSpecialAndMoveCtor, Allocator<HasSpecialAndMoveCtor> > ets5(SecretTag);
    ets5.local();
    ets5.combine_each(EmptyCombineEach<HasSpecialAndMoveCtor>());
    // Test that move operations do not impose extra requirements
    // Default allocator is used. If it does not match Allocator, there will be elementwise move
    oneapi::tbb::enumerable_thread_specific<HasSpecialAndMoveCtor> ets6( std::move(ets4) );
    ets6.combine_each(EmptyCombineEach<HasSpecialAndMoveCtor>());
    ets6 = std::move(ets5);
}

void TestMemberTypes() {
    using default_container_type = oneapi::tbb::enumerable_thread_specific<int>;
    static_assert(std::is_same<typename default_container_type::allocator_type, oneapi::tbb::cache_aligned_allocator<int>>::value,
            "Incorrect default template allocator");

    using test_allocator_type = std::allocator<int>;
    using ets_container_type = oneapi::tbb::enumerable_thread_specific<int, test_allocator_type>;

    static_assert(std::is_same<typename ets_container_type::allocator_type, test_allocator_type>::value,
                  "Incorrect container allocator_type member type");

    using value_type = typename ets_container_type::value_type;

    static_assert(std::is_same<typename ets_container_type::value_type, int>::value,
                  "Incorrect container value_type member type");
    static_assert(std::is_same<typename ets_container_type::reference, value_type&>::value,
                  "Incorrect container reference member type");
    static_assert(std::is_same<typename ets_container_type::const_reference, const value_type&>::value,
                  "Incorrect container const_reference member type");

    using allocator_type = typename ets_container_type::allocator_type;
    static_assert(std::is_same<typename ets_container_type::pointer, typename std::allocator_traits<allocator_type>::pointer>::value,
                  "Incorrect container pointer member type");
    static_assert(std::is_same<typename ets_container_type::const_pointer, typename std::allocator_traits<allocator_type>::const_pointer>::value,
                  "Incorrect container const_pointer member type");

    static_assert(std::is_unsigned<typename ets_container_type::size_type>::value,
                  "Incorrect container size_type member type");
    static_assert(std::is_signed<typename ets_container_type::difference_type>::value,
                  "Incorrect container difference_type member type");

    static_assert(utils::is_random_access_iterator<typename ets_container_type::iterator>::value,
                  "Incorrect container iterator member type");
    static_assert(!std::is_const<typename ets_container_type::iterator::value_type>::value,
                  "Incorrect container iterator member type");
    static_assert(utils::is_random_access_iterator<typename ets_container_type::const_iterator>::value,
                  "Incorrect container const_iterator member type");
    static_assert(std::is_const<typename ets_container_type::const_iterator::value_type>::value,
                  "Incorrect container iterator member type");
}

size_t init_tbb_alloc_mask() {
    // TODO: use __TBB_alignof(T) to check for local() results instead of using internal knowledges of ets element padding
    if(oneapi::tbb::tbb_allocator<int>::allocator_type() == oneapi::tbb::tbb_allocator<int>::standard) {
        // scalable allocator is not available.
        return 1;
    }
    else {
        // this value is for large objects, but will be correct for small.
        return 64; // TBB_REVAMP_TODO: enable as estimatedCacheLineSize when tbbmalloc is available;
    }
}

// TODO: rework the test not to depend on oneTBB internals
static const size_t cache_allocator_mask = oneapi::tbb::detail::r1::cache_line_size();
static const size_t tbb_allocator_mask = init_tbb_alloc_mask();

void TestETSIterator() {
    using ets_type = oneapi::tbb::enumerable_thread_specific<int>;
    if (utils::get_platform_max_threads() == 1) {
        ets_type ets;
        ets.local() = 1;
        REQUIRE_MESSAGE(std::next(ets.begin()) == ets.end(), "Incorrect begin or end of the ETS");
        REQUIRE_MESSAGE(std::prev(ets.end()) == ets.begin(), "Incorrect begin or end of the ETS");
    } else {
        std::atomic<std::size_t> sync_counter(0);

        const std::size_t expected_ets_size = 2;
        ets_type ets;
        const ets_type& cets(ets);

        auto fill_ets_body = [&](){
            ets.local() = 42;
            ++sync_counter;
            while(sync_counter != expected_ets_size)
                utils::yield();
        };

        oneapi::tbb::parallel_invoke(fill_ets_body, fill_ets_body);
        REQUIRE_MESSAGE(ets.size() == expected_ets_size, "Incorrect ETS size");

        std::size_t counter = 0;
        auto iter = ets.begin();
        while(iter != ets.end()) {
            ++counter % 2 == 0 ? ++iter : iter++;
        }
        REQUIRE(counter == expected_ets_size);
        while(iter != ets.begin()) {
            --counter % 2 == 0 ? --iter : iter--;
        }
        REQUIRE(counter == 0);
        auto citer = cets.begin();
        while(citer != cets.end()) {
            ++counter % 2 == 0 ? ++citer : citer++;
        }
        REQUIRE(counter == expected_ets_size);
        while(citer != cets.begin()) {
            --counter % 2 == 0 ? --citer : citer--;
        }
        REQUIRE(counter == 0);
        REQUIRE(ets.begin() + expected_ets_size == ets.end());
        REQUIRE(expected_ets_size + ets.begin() == ets.end());
        REQUIRE(ets.end() - expected_ets_size == ets.begin());

        typename ets_type::iterator it;
        it = ets.begin();

        auto it_bkp = it;
        auto it2 = it++;
        REQUIRE(it2 == it_bkp);

        it = ets.begin();
        it += expected_ets_size;
        REQUIRE(it == ets.end());
        it -= expected_ets_size;
        REQUIRE(it == ets.begin());

        for (int i = 0; i < int(expected_ets_size - 1); ++i) {
            REQUIRE(ets.begin()[i] == 42);
            REQUIRE(std::prev(ets.end())[-i] == 42);
        }

        auto iter1 = ets.begin();
        auto iter2 = ets.end();
        REQUIRE(iter1 < iter2);
        REQUIRE(iter1 <= iter2);
        REQUIRE(!(iter1 > iter2));
        REQUIRE(!(iter1 >= iter2));
    }
}

template <bool ExpectEqual, bool ExpectLess, typename Iterator>
void DoETSIteratorComparisons( const Iterator& lhs, const Iterator& rhs ) {
    // TODO: replace with testEqualityAndLessComparisons after adding <=> operator for ETS iterator
    using namespace comparisons_testing;
    testEqualityComparisons<ExpectEqual>(lhs, rhs);
    testTwoWayComparisons<ExpectEqual, ExpectLess>(lhs, rhs);
}

template <typename Iterator, typename ETS>
void TestETSIteratorComparisonsBasic( ETS& ets ) {
    REQUIRE_MESSAGE(!ets.empty(), "Incorrect test setup");
    Iterator it1, it2;
    DoETSIteratorComparisons</*ExpectEqual = */true, /*ExpectLess = */false>(it1, it2);
    it1 = ets.begin();
    it2 = ets.begin();
    DoETSIteratorComparisons</*ExpectEqual = */true, /*ExpectLess = */false>(it1, it2);
    it2 = std::prev(ets.end());
    DoETSIteratorComparisons</*ExpectEqual = */false, /*ExpectLess = */true>(it1, it2);
}

void TestETSIteratorComparisons() {
    using ets_type = oneapi::tbb::enumerable_thread_specific<int>;
    ets_type ets;

    // Fill the ets
    const std::size_t expected_ets_size = 2;
    std::atomic<std::size_t> sync_counter(0);
    auto fill_ets_body = [&](int){
            ets.local() = 42;
            ++sync_counter;
            while(sync_counter != expected_ets_size)
                std::this_thread::yield();
        };

    utils::NativeParallelFor(2, fill_ets_body);

    TestETSIteratorComparisonsBasic<typename ets_type::iterator>(ets);
    const ets_type& cets = ets;
    TestETSIteratorComparisonsBasic<typename ets_type::const_iterator>(cets);
}

//! Test container instantiation
//! \brief \ref interface \ref requirement
TEST_CASE("Instantiation") {
    AlignMask = cache_allocator_mask;
    TestInstantiation<oneapi::tbb::cache_aligned_allocator>("oneapi::tbb::cache_aligned_allocator");
    AlignMask = tbb_allocator_mask;
    TestInstantiation<oneapi::tbb::tbb_allocator>("oneapi::tbb::tbb_allocator");
}

//! Test assignment and copy constructor
//! \brief \ref interface \ref requirement
TEST_CASE("Assignment and copy constructor") {
    AlignMask = cache_allocator_mask;
    run_assignment_and_copy_constructor_tests<oneapi::tbb::cache_aligned_allocator>("oneapi::tbb::cache_aligned_allocator");
    AlignMask = tbb_allocator_mask;
    run_assignment_and_copy_constructor_tests<oneapi::tbb::tbb_allocator>("oneapi::tbb::tbb_allocator");
}

//! Test for basic ETS functionality and requirements
//! \brief \ref interface \ref requirement
TEST_CASE("Basic ETS functionality") {
    const int LOCALS = 10;

    oneapi::tbb::enumerable_thread_specific<int> ets;
    ets.local() = 42;

    utils::SpinBarrier barrier(LOCALS);
    utils::NativeParallelFor(LOCALS, [&](int i) {
        barrier.wait();
        ets.local() = i;
        CHECK(ets.local() == i);
    });
    CHECK(ets.local() == 42);

    int ref_combined{0};
    std::vector<int> sequence(LOCALS);
    std::iota(sequence.begin(), sequence.end(), 0);
    for (int i : sequence) {
        ref_combined += i;
    }
    ref_combined += 42;
    int ets_combined = ets.combine([](int x, int y) {
        return x + y;
    });
    CHECK(ref_combined == ets_combined);
}

//! Test ETS usage in parallel algorithms.
//! Also tests flattened2d and flattend2d
//! \brief \ref interface \ref requirement \ref stress
TEST_CASE("Parallel test") {
    run_reference_check();
    AlignMask = cache_allocator_mask;
    run_parallel_tests<oneapi::tbb::cache_aligned_allocator>("oneapi::tbb::cache_aligned_allocator");
    AlignMask = tbb_allocator_mask;
    run_parallel_tests<oneapi::tbb::tbb_allocator>("oneapi::tbb::tbb_allocator");
    run_cross_type_tests();
}

//! \brief \ref interface \ref requirement
TEST_CASE("Member types") {
    TestMemberTypes();
}

//! \brief \ref interface \ref requirement
TEST_CASE("enumerable_thread_specific iterator") {
    TestETSIterator();
}

//! \brief \ref interface \ref requirement
TEST_CASE("enumerable_thread_specific iterator comparisons") {
    TestETSIteratorComparisons();
}