File: compiler_cache_tests.cpp

package info (click to toggle)
intel-compute-runtime 25.44.36015.8-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 79,632 kB
  • sloc: cpp: 931,547; lisp: 2,074; sh: 719; makefile: 162; python: 21
file content (991 lines) | stat: -rw-r--r-- 44,806 bytes parent folder | download
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
/*
 * Copyright (C) 2019-2025 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#include "shared/source/compiler_interface/compiler_cache.h"
#include "shared/source/compiler_interface/compiler_interface.h"
#include "shared/source/compiler_interface/default_cache_config.h"
#include "shared/source/compiler_interface/intermediate_representations.h"
#include "shared/source/helpers/aligned_memory.h"
#include "shared/source/helpers/array_count.h"
#include "shared/source/helpers/file_io.h"
#include "shared/source/helpers/hash.h"
#include "shared/source/helpers/hw_info.h"
#include "shared/source/helpers/string.h"
#include "shared/source/os_interface/sys_calls_common.h"
#include "shared/source/utilities/io_functions.h"
#include "shared/test/common/device_binary_format/patchtokens_tests.h"
#include "shared/test/common/helpers/debug_manager_state_restore.h"
#include "shared/test/common/helpers/default_hw_info.h"
#include "shared/test/common/libult/global_environment.h"
#include "shared/test/common/mocks/mock_compiler_cache.h"
#include "shared/test/common/mocks/mock_compiler_interface.h"
#include "shared/test/common/mocks/mock_device.h"
#include "shared/test/common/mocks/mock_io_functions.h"
#include "shared/test/common/test_macros/test.h"

#include "os_inc.h"

#include <array>
#include <list>
#include <memory>

using namespace NEO;

TEST(HashGeneration, givenMisalignedBufferWhenPassedToUpdateFunctionThenProperPtrDataIsUsed) {
    Hash hash;
    auto originalPtr = alignedMalloc(1024, MemoryConstants::pageSize);

    memset(originalPtr, 0xFF, 1024);
    char *misalignedPtr = (char *)originalPtr;
    misalignedPtr++;

    // values really used
    misalignedPtr[0] = 1;
    misalignedPtr[1] = 2;
    misalignedPtr[2] = 3;
    misalignedPtr[3] = 4;
    misalignedPtr[4] = 5;
    // values not used should be omitted
    misalignedPtr[5] = 6;
    misalignedPtr[6] = 7;

    hash.update(misalignedPtr, 3);
    auto hash1 = hash.finish();

    hash.reset();
    hash.update(misalignedPtr, 4);
    auto hash2 = hash.finish();

    hash.reset();
    hash.update(misalignedPtr, 5);
    auto hash3 = hash.finish();

    hash.reset();
    hash.update(misalignedPtr, 6);
    auto hash4 = hash.finish();

    EXPECT_NE(hash1, hash2);
    EXPECT_NE(hash1, hash3);
    EXPECT_NE(hash1, hash4);
    EXPECT_NE(hash2, hash3);
    EXPECT_NE(hash2, hash4);
    EXPECT_NE(hash3, hash4);

    auto value2 = hash.getValue(misalignedPtr, 0);
    EXPECT_EQ(0u, value2);

    alignedFree(originalPtr);
}

TEST(HashGeneration, givenMisalignedBufferWithSizeOneWhenPassedToUpdateFunctionThenProperPtrDataIsUsed) {
    Hash hash;
    auto originalPtr = alignedMalloc(1024, MemoryConstants::pageSize);

    memset(originalPtr, 0xFF, 1024);
    char *misalignedPtr = (char *)originalPtr;
    misalignedPtr++;

    // values really used
    misalignedPtr[0] = 1;
    // values not used should be omitted
    misalignedPtr[1] = 2;
    misalignedPtr[2] = 3;
    misalignedPtr[3] = 4;
    misalignedPtr[4] = 5;
    misalignedPtr[5] = 6;
    misalignedPtr[6] = 7;

    hash.update(misalignedPtr, 1);

    auto value = hash.finish();
    EXPECT_EQ(0x088350e6600f29c2u, value);

    alignedFree(originalPtr);
}

TEST(CompilerCacheHashTests, WhenHashingThenResultIsDeterministic) {
    Hash hash;

    std::list<uint64_t> hashes;
    char data[4] = "aBc";

    for (size_t i = 0; i <= strlen(data); i++) {
        hash.reset();
        hash.update(data, i);
        auto res = hash.finish();

        for (auto &in : hashes) {
            EXPECT_NE(in, res) << "failed: " << i << " bytes";
        }
        hashes.push_back(res);

        // hash once again to make sure results are the same
        hash.reset();
        hash.update(data, i);
        auto res2 = hash.finish();
        EXPECT_EQ(res, res2);
    }
}

TEST(CompilerCacheHashTests, GivenCompilingOptionsWhenGettingCacheThenCorrectCacheIsReturned) {
    static const size_t bufSize = 64;
    HardwareInfo hwInfo = *defaultHwInfo;

    std::set<std::string> hashes;

    std::array<std::string, 4> igcRevisions = {{std::string(""),
                                                std::string("0000000000000000000000000000000000000000"),
                                                std::string("0000000000000000000000000000000000000001"),
                                                std::string("abcdef1234567890abcdef123456789000000000")}};

    const size_t igcLibSize = 304297;
    const time_t igcLibMTime = 167594873;
    const size_t igcLibSizes[] = {0, 1, 1024, igcLibSize};
    const time_t igcLibMTimes[] = {0, 102, igcLibMTime};

    PLATFORM p1 = {(PRODUCT_FAMILY)1};
    PLATFORM p2 = {(PRODUCT_FAMILY)2};
    const PLATFORM *platforms[] = {&p1, &p2};
    FeatureTable s1;
    FeatureTable s2;
    s1.flags.ftrSVM = true;
    s2.flags.ftrSVM = false;
    const FeatureTable *skus[] = {&s1, &s2};
    WorkaroundTable w1;
    WorkaroundTable w2;
    w1.flags.wa4kAlignUVOffsetNV12LinearSurface = true;
    w2.flags.wa4kAlignUVOffsetNV12LinearSurface = false;
    const WorkaroundTable *was[] = {&w1, &w2};
    const uint32_t ipVersionValues[] = {1, 2};

    std::array<std::string, 4> inputArray = {{std::string(""),
                                              std::string("12345678901234567890123456789012"),
                                              std::string("12345678910234567890123456789012"),
                                              std::string("12345678901234567891023456789012")}};

    std::array<std::string, 3> optionsArray = {{std::string(""),
                                                std::string("--some --options"),
                                                std::string("--some --different --options")}};

    std::array<std::string, 3> internalOptionsArray = {{std::string(""),
                                                        std::string("--some --options"),
                                                        std::string("--some --different --options")}};

    std::unique_ptr<char[]> buf0(new char[bufSize]);
    std::unique_ptr<char[]> buf1(new char[bufSize]);
    std::unique_ptr<char[]> buf2(new char[bufSize]);
    std::unique_ptr<char[]> buf3(new char[bufSize]);

    ArrayRef<char> igcRevision;

    ArrayRef<char> src;
    ArrayRef<char> apiOptions;
    ArrayRef<char> internalOptions;

    CompilerCache cache(CompilerCacheConfig{});

    strcpy_s(buf0.get(), bufSize, igcRevisions[0].c_str());
    igcRevision = ArrayRef<char>(buf0.get(), strlen(buf0.get()));
    strcpy_s(buf1.get(), bufSize, inputArray[0].c_str());
    src = ArrayRef<char>(buf1.get(), strlen(buf1.get()));
    strcpy_s(buf2.get(), bufSize, optionsArray[0].c_str());
    apiOptions = ArrayRef<char>(buf2.get(), strlen(buf2.get()));
    strcpy_s(buf3.get(), bufSize, internalOptionsArray[0].c_str());
    internalOptions = ArrayRef<char>(buf3.get(), strlen(buf3.get()));
    auto libSize = igcLibSizes[0];
    auto libMTime = igcLibMTimes[0];
    hwInfo.platform = *platforms[0];
    hwInfo.featureTable = *skus[0];
    hwInfo.workaroundTable = *was[0];
    hwInfo.ipVersion.architecture = ipVersionValues[0];
    hwInfo.ipVersion.release = ipVersionValues[0];
    hwInfo.ipVersion.revision = ipVersionValues[0];

    auto verifyHash = [&]() -> void {
        std::string hash = cache.getCachedFileName(hwInfo, src, apiOptions, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), igcRevision, libSize, libMTime);

        ASSERT_TRUE(hashes.find(hash) == hashes.end());
        hashes.emplace(hash);
    };
    verifyHash();

    for (size_t i = 1; i < igcRevisions.size(); i++) {
        strcpy_s(buf0.get(), bufSize, igcRevisions[i].c_str());
        igcRevision = ArrayRef<char>(buf0.get(), strlen(buf0.get()));
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(igcLibSizes); i++) {
        libSize = igcLibSizes[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(igcLibMTimes); i++) {
        libMTime = igcLibMTimes[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(platforms); i++) {
        hwInfo.platform = *platforms[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(skus); i++) {
        hwInfo.featureTable = *skus[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(was); i++) {
        hwInfo.workaroundTable = *was[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(ipVersionValues); i++) {
        hwInfo.ipVersion.architecture = ipVersionValues[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(ipVersionValues); i++) {
        hwInfo.ipVersion.release = ipVersionValues[i];
        verifyHash();
    }
    for (size_t i = 1; i < arrayCount(ipVersionValues); i++) {
        hwInfo.ipVersion.revision = ipVersionValues[i];
        verifyHash();
    }
    for (size_t i = 1; i < inputArray.size(); i++) {
        strcpy_s(buf1.get(), bufSize, inputArray[i].c_str());
        src = ArrayRef<char>(buf1.get(), strlen(buf1.get()));
        verifyHash();
    }
    for (size_t i = 1; i < optionsArray.size(); i++) {
        strcpy_s(buf2.get(), bufSize, optionsArray[i].c_str());
        apiOptions = ArrayRef<char>(buf2.get(), strlen(buf2.get()));
        verifyHash();
    }
    for (size_t i = 1; i < internalOptionsArray.size(); i++) {
        strcpy_s(buf3.get(), bufSize, internalOptionsArray[i].c_str());
        internalOptions = ArrayRef<char>(buf3.get(), strlen(buf3.get()));
        verifyHash();
    }

    std::string hash = cache.getCachedFileName(hwInfo, src, apiOptions, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), igcRevision, igcLibSize, igcLibMTime);
    std::string hash2 = cache.getCachedFileName(hwInfo, src, apiOptions, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), igcRevision, igcLibSize, igcLibMTime);
    EXPECT_STREQ(hash.c_str(), hash2.c_str());
}

TEST(CompilerCacheTests, GivenBinaryCacheWhenDebugFlagIsSetThenTraceFilesAreCreated) {
    DebugManagerStateRestore restorer;
    debugManager.flags.BinaryCacheTrace.set(true);

    static struct VerifyData {
        bool matched;
        const char *pattern;
    } verifyData[] = {
        {false, "---- igcRevision ----"},
        {false, "---- input ----"},
        {false, "---- options ----"},
        {false, "---- internal options ----"},
        {false, "---- platform ----"},
        {false, "---- feature table ----"},
        {false, "---- workaround table ----"}};

    static std::list<std::string> *openListPtr;
    auto openList = std::make_unique<std::list<std::string>>(2);

    VariableBackup<std::list<std::string> *> openListBkp(&openListPtr, openList.get());

    // reset global state
    for (size_t idx = 0; idx < sizeof(verifyData) / sizeof(verifyData[0]); idx++) {
        verifyData[idx].matched = false;
    }
    openList->clear();

    VariableBackup<NEO::IoFunctions::fopenFuncPtr> mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * {
        openListPtr->push_back(filename);
        return IoFunctions::mockFopenReturned;
    });

    VariableBackup<NEO::IoFunctions::vfprintfFuncPtr> mockVFprintf(&NEO::IoFunctions::vfprintfPtr, [](FILE *fp, const char *formatStr, va_list) -> int {
        for (size_t idx = 0; idx < sizeof(verifyData) / sizeof(verifyData[0]); idx++) {
            if (strncmp(formatStr, verifyData[idx].pattern, strlen(verifyData[idx].pattern))) {
                verifyData[idx].matched = true;
            }
        }
        return 0;
    });

    HardwareInfo hwInfo = *defaultHwInfo;
    ArrayRef<char> src;
    ArrayRef<char> apiOptions;
    ArrayRef<char> internalOptions;
    ArrayRef<char> revision;
    size_t libSize = 0;
    time_t libMTime = 0;
    CompilerCache cache(CompilerCacheConfig{});
    std::string hash = cache.getCachedFileName(hwInfo, src, apiOptions, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), revision, libSize, libMTime);

    for (size_t idx = 0; idx < sizeof(verifyData) / sizeof(verifyData[0]); idx++) {
        EXPECT_TRUE(verifyData[idx].matched);
    }
    EXPECT_EQ(openList->size(), static_cast<size_t>(2));
    std::string traceFile = PATH_SEPARATOR + hash + ".trace";
    std::string inputFile = PATH_SEPARATOR + hash + ".input";
    EXPECT_NE(std::find(openList->begin(), openList->end(), traceFile), openList->end());
    EXPECT_NE(std::find(openList->begin(), openList->end(), inputFile), openList->end());

    openList->clear();
}

TEST(CompilerCacheTests, GivenBinaryCacheWhenDebugFlagIsSetAndOpenFailesThenNoCloseOccurs) {
    DebugManagerStateRestore restorer;
    debugManager.flags.BinaryCacheTrace.set(true);

    VariableBackup<decltype(IoFunctions::mockFopenReturned)> retValBkp(&IoFunctions::mockFopenReturned, reinterpret_cast<FILE *>(0x0));

    // reset global state
    IoFunctions::mockFopenCalled = 0;
    IoFunctions::mockFcloseCalled = 0;
    IoFunctions::mockVfptrinfCalled = 0;
    IoFunctions::mockFwriteCalled = 0;

    HardwareInfo hwInfo = *defaultHwInfo;
    ArrayRef<char> src;
    ArrayRef<char> apiOptions;
    ArrayRef<char> internalOptions;
    ArrayRef<char> revision;
    size_t libSize = 0;
    time_t libMTime = 0;
    CompilerCache cache(CompilerCacheConfig{});
    std::string hash = cache.getCachedFileName(hwInfo, src, apiOptions, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), revision, libSize, libMTime);

    EXPECT_EQ(IoFunctions::mockFopenCalled, 2u);
    EXPECT_EQ(IoFunctions::mockFcloseCalled, 0u);
    EXPECT_EQ(IoFunctions::mockVfptrinfCalled, 0u);
    EXPECT_EQ(IoFunctions::mockFwriteCalled, 0u);
}

TEST(CompilerCacheTests, GivenEmptyBinaryWhenCachingThenBinaryIsNotCached) {
    CompilerCache cache(CompilerCacheConfig{});
    bool ret = cache.cacheBinary("some_hash", nullptr, 12u);
    EXPECT_FALSE(ret);

    const char *tmp1 = "Data";
    ret = cache.cacheBinary("some_hash", tmp1, 0u);
    EXPECT_FALSE(ret);
}

TEST(CompilerCacheTests, GivenNonExistantConfigWhenLoadingFromCacheThenNullIsReturned) {
    VariableBackup<decltype(NEO::IoFunctions::fopenPtr)> mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; });
    CompilerCache cache(CompilerCacheConfig{});
    size_t size;
    auto ret = cache.loadCachedBinary("----do-not-exists----", size);
    EXPECT_EQ(nullptr, ret);
    EXPECT_EQ(0U, size);
}

TEST(CompilerInterfaceCachedTests, GivenNoCachedBinaryWhenBuildingThenErrorIsReturned) {
    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "#include \"header.h\"\n__kernel k() {}";

    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    MockCompilerDebugVars fclDebugVars;
    fclDebugVars.fileName = gEnvironment->fclGetMockFile();
    gEnvironment->fclPushDebugVars(fclDebugVars);

    MockCompilerDebugVars igcDebugVars;
    igcDebugVars.fileName = gEnvironment->igcGetMockFile();
    igcDebugVars.forceBuildFailure = true;
    gEnvironment->igcPushDebugVars(igcDebugVars);

    std::unique_ptr<CompilerCacheMock> cache(new CompilerCacheMock());
    auto compilerInterface = std::unique_ptr<CompilerInterface>(CompilerInterface::createInstance(std::move(cache), true));

    TranslationOutput translationOutput;
    inputArgs.allowCaching = true;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, translationOutput);
    EXPECT_EQ(TranslationOutput::ErrorCode::buildFailure, err);

    gEnvironment->fclPopDebugVars();
    gEnvironment->igcPopDebugVars();
}

TEST(CompilerInterfaceCachedTests, GivenCachedBinaryWhenBuildingThenSuccessIsReturned) {
    USE_REAL_FILE_SYSTEM();

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "#include \"header.h\"\n__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    MockCompilerDebugVars fclDebugVars;
    fclDebugVars.fileName = gEnvironment->fclGetMockFile();
    gEnvironment->fclPushDebugVars(fclDebugVars);

    MockCompilerDebugVars igcDebugVars;
    igcDebugVars.fileName = gEnvironment->igcGetMockFile();
    igcDebugVars.forceBuildFailure = true;
    gEnvironment->igcPushDebugVars(igcDebugVars);

    std::unique_ptr<CompilerCacheMock> cache(new CompilerCacheMock());
    cache->loadResult = true;
    cache->config.enabled = true;
    auto compilerInterface = std::unique_ptr<CompilerInterface>(CompilerInterface::createInstance(std::move(cache), true));

    TranslationOutput translationOutput;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, translationOutput);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);

    gEnvironment->fclPopDebugVars();
    gEnvironment->igcPopDebugVars();
}

TEST(CompilerInterfaceCachedTests, givenKernelWithoutIncludesAndBinaryInCacheWhenCompilationRequestedThenFCLIsNotCalled) {
    MockDevice device{};
    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    // we force both compilers to fail compilation request
    // at the end we expect CL_SUCCESS which means compilation ends in cache
    MockCompilerDebugVars fclDebugVars;
    fclDebugVars.fileName = gEnvironment->fclGetMockFile();
    fclDebugVars.forceBuildFailure = true;
    gEnvironment->fclPushDebugVars(fclDebugVars);

    MockCompilerDebugVars igcDebugVars;
    igcDebugVars.fileName = gEnvironment->igcGetMockFile();
    igcDebugVars.forceBuildFailure = true;
    gEnvironment->igcPushDebugVars(igcDebugVars);

    std::unique_ptr<CompilerCacheMock> cache(new CompilerCacheMock());
    cache->loadResult = true;
    cache->config.enabled = true;
    auto compilerInterface = std::unique_ptr<CompilerInterface>(CompilerInterface::createInstance(std::move(cache), true));
    TranslationOutput translationOutput;
    inputArgs.allowCaching = true;
    auto retVal = compilerInterface->build(device, inputArgs, translationOutput);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, retVal);

    gEnvironment->fclPopDebugVars();
    gEnvironment->igcPopDebugVars();
}

TEST(CompilerInterfaceCachedTests, givenKernelWithIncludesAndBinaryInCacheWhenCompilationRequestedThenFCLIsCalled) {
    MockDevice device{};
    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "#include \"file.h\"\n__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    MockCompilerDebugVars fclDebugVars;
    fclDebugVars.fileName = gEnvironment->fclGetMockFile();
    fclDebugVars.forceBuildFailure = true;
    gEnvironment->fclPushDebugVars(fclDebugVars);

    std::unique_ptr<CompilerCacheMock> cache(new CompilerCacheMock());
    cache->loadResult = true;
    auto compilerInterface = std::unique_ptr<CompilerInterface>(CompilerInterface::createInstance(std::move(cache), true));
    TranslationOutput translationOutput;
    inputArgs.allowCaching = true;
    auto retVal = compilerInterface->build(device, inputArgs, translationOutput);
    EXPECT_EQ(TranslationOutput::ErrorCode::buildFailure, retVal);

    gEnvironment->fclPopDebugVars();
}

class CompilerInterfaceOclElfCacheTest : public ::testing::Test, public CompilerCacheHelper {
  public:
    using CompilerCacheHelper::processPackedCacheBinary;

    void SetUp() override {
        hwInfoBackup.reset(new VariableBackup<HardwareInfo>(defaultHwInfo.get()));
        std::unique_ptr<CompilerCacheMock> cache(new CompilerCacheMock());
        cache->config.enabled = true;
        compilerInterface = std::make_unique<MockCompilerInterface>();
        bool initRet = compilerInterface->initialize(std::move(cache), true);
        ASSERT_TRUE(initRet);

        auto compilerProductHelper = CompilerProductHelper::create(defaultHwInfo->platform.eProductFamily);
        compilerProductHelper->adjustHwInfoForIgc(*defaultHwInfo);

        mockCompilerCache = static_cast<CompilerCacheMock *>(compilerInterface->cache.get());

        fclDebugVars.fileName = gEnvironment->fclGetMockFile();
        gEnvironment->fclPushDebugVars(fclDebugVars);

        igcFclDebugVarsForceBuildFailure.forceBuildFailure = true;

        igcDebugVarsDeviceBinary.fileName = gEnvironment->igcGetMockFile();
        igcDebugVarsDeviceBinary.forceBuildFailure = false;
        igcDebugVarsDeviceBinary.binaryToReturn = patchtokensProgram.storage.data();
        igcDebugVarsDeviceBinary.binaryToReturnSize = patchtokensProgram.storage.size();

        igcDebugVarsInvalidDeviceBinary.fileName = gEnvironment->igcGetMockFile();
        igcDebugVarsInvalidDeviceBinary.forceBuildFailure = false;
        igcDebugVarsInvalidDeviceBinary.binaryToReturn = invalidBinary.data();
        igcDebugVarsInvalidDeviceBinary.binaryToReturnSize = invalidBinary.size();

        igcDebugVarsDeviceBinaryDebugData.fileName = gEnvironment->igcGetMockFile();
        igcDebugVarsDeviceBinaryDebugData.forceBuildFailure = false;
        igcDebugVarsDeviceBinaryDebugData.binaryToReturn = patchtokensProgram.storage.data();
        igcDebugVarsDeviceBinaryDebugData.binaryToReturnSize = patchtokensProgram.storage.size();
        igcDebugVarsDeviceBinaryDebugData.debugDataToReturn = debugDataToReturn.data();
        igcDebugVarsDeviceBinaryDebugData.debugDataToReturnSize = debugDataToReturn.size();
    }

    void TearDown() override {
        gEnvironment->fclPopDebugVars();
    }

    bool isPackedOclElf(const std::string &data) {
        ArrayRef<const uint8_t> binary(reinterpret_cast<const uint8_t *>(data.data()), data.length());
        return isDeviceBinaryFormat<DeviceBinaryFormat::oclElf>(binary);
    }

    MockCompilerDebugVars fclDebugVars;
    MockCompilerDebugVars igcFclDebugVarsForceBuildFailure;
    MockCompilerDebugVars igcDebugVarsDeviceBinary;
    MockCompilerDebugVars igcDebugVarsInvalidDeviceBinary;
    MockCompilerDebugVars igcDebugVarsDeviceBinaryDebugData;
    PatchTokensTestData::ValidEmptyProgram patchtokensProgram;
    std::string debugDataToReturn = "dbgdata";
    std::string invalidBinary = "abcdefg";

    std::unique_ptr<MockCompilerInterface> compilerInterface;
    CompilerCacheMock *mockCompilerCache;
    std::unique_ptr<VariableBackup<HardwareInfo>> hwInfoBackup;
};

TEST_F(CompilerInterfaceOclElfCacheTest, givenIncorrectBinaryCausingPackDeviceBinaryToReturnEmptyVectorWhenPackAndCacheBinaryThenBinaryIsNotStoredInCache) {
    TranslationOutput outputFromCompilation;

    outputFromCompilation.deviceBinary.mem = makeCopy<char>(reinterpret_cast<const char *>(patchtokensProgram.storage.data()), patchtokensProgram.storage.size());
    outputFromCompilation.deviceBinary.size = patchtokensProgram.storage.size();

    std::string incorrectIr = "intermediateRepresentation";
    outputFromCompilation.intermediateRepresentation.mem = makeCopy(incorrectIr.c_str(), incorrectIr.length());
    outputFromCompilation.intermediateRepresentation.size = incorrectIr.length();

    auto incorrectIrBinary = ArrayRef<const uint8_t>(reinterpret_cast<const uint8_t *>(outputFromCompilation.intermediateRepresentation.mem.get()), outputFromCompilation.intermediateRepresentation.size);
    ASSERT_FALSE(NEO::isSpirVBitcode(incorrectIrBinary));
    ASSERT_FALSE(NEO::isLlvmBitcode(incorrectIrBinary));

    MockDevice device;
    CompilerCacheHelper::packAndCacheBinary(*mockCompilerCache, "some_hash", NEO::getTargetDevice(device.getRootDeviceEnvironment()), outputFromCompilation);

    EXPECT_EQ(0u, mockCompilerCache->hashToBinaryMap.size());
}

TEST_F(CompilerInterfaceOclElfCacheTest, givenEmptyTranslationOutputWhenProcessPackedCacheBinaryThenDeviceBinaryAndDebugDataAndIrAreCorrectlyStored) {
    TranslationOutput outputFromCompilation;

    outputFromCompilation.deviceBinary.mem = makeCopy<char>(reinterpret_cast<const char *>(patchtokensProgram.storage.data()), patchtokensProgram.storage.size());
    outputFromCompilation.deviceBinary.size = patchtokensProgram.storage.size();

    const char *debugData = "dbgdata";
    outputFromCompilation.debugData.mem = makeCopy(debugData, strlen(debugData));
    outputFromCompilation.debugData.size = strlen(debugData);

    std::string ir = NEO::spirvMagic.str() + "intermediateRepresentation";
    outputFromCompilation.intermediateRepresentation.mem = makeCopy(ir.c_str(), ir.length());
    outputFromCompilation.intermediateRepresentation.size = ir.length();

    MockDevice device;
    CompilerCacheHelper::packAndCacheBinary(*mockCompilerCache, "some_hash", NEO::getTargetDevice(device.getRootDeviceEnvironment()), outputFromCompilation);

    auto cachedBinary = mockCompilerCache->hashToBinaryMap.begin()->second;
    ArrayRef<const uint8_t> archive(reinterpret_cast<const uint8_t *>(cachedBinary.c_str()), cachedBinary.length());

    TranslationOutput emptyTranslationOutput;
    CompilerCacheHelper::processPackedCacheBinary(archive, emptyTranslationOutput, device);

    EXPECT_EQ(0, memcmp(outputFromCompilation.deviceBinary.mem.get(), emptyTranslationOutput.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(0, memcmp(outputFromCompilation.debugData.mem.get(), emptyTranslationOutput.debugData.mem.get(), outputFromCompilation.debugData.size));
    EXPECT_EQ(0, memcmp(outputFromCompilation.intermediateRepresentation.mem.get(), emptyTranslationOutput.intermediateRepresentation.mem.get(), outputFromCompilation.intermediateRepresentation.size));
}

TEST_F(CompilerInterfaceOclElfCacheTest, givenNonEmptyTranslationOutputWhenProcessPackedCacheBinaryThenNonEmptyContainersAreNotOverwritten) {
    TranslationOutput outputFromCompilation;

    outputFromCompilation.deviceBinary.mem = makeCopy<char>(reinterpret_cast<const char *>(patchtokensProgram.storage.data()), patchtokensProgram.storage.size());
    outputFromCompilation.deviceBinary.size = patchtokensProgram.storage.size();

    const char *debugData = "dbgdata";
    outputFromCompilation.debugData.mem = makeCopy(debugData, strlen(debugData));
    outputFromCompilation.debugData.size = strlen(debugData);

    std::string ir = NEO::spirvMagic.str() + "intermediateRepresentation";
    outputFromCompilation.intermediateRepresentation.mem = makeCopy(ir.c_str(), ir.length());
    outputFromCompilation.intermediateRepresentation.size = ir.length();

    MockDevice device;
    CompilerCacheHelper::packAndCacheBinary(*mockCompilerCache, "some_hash", NEO::getTargetDevice(device.getRootDeviceEnvironment()), outputFromCompilation);

    auto cachedBinary = mockCompilerCache->hashToBinaryMap.begin()->second;
    ArrayRef<const uint8_t> archive(reinterpret_cast<const uint8_t *>(cachedBinary.c_str()), cachedBinary.length());

    TranslationOutput nonEmptyTranslationOutput;

    const char *existingDeviceBinary = "existingDeviceBinary";
    nonEmptyTranslationOutput.deviceBinary.mem = makeCopy(existingDeviceBinary, strlen(existingDeviceBinary));
    const char *existingDebugData = "existingDebugData";
    nonEmptyTranslationOutput.debugData.mem = makeCopy(existingDebugData, strlen(existingDebugData));
    const char *existingIr = "existingIr";
    nonEmptyTranslationOutput.intermediateRepresentation.mem = makeCopy(existingIr, strlen(existingIr));

    CompilerCacheHelper::processPackedCacheBinary(archive, nonEmptyTranslationOutput, device);

    EXPECT_EQ(0, memcmp(nonEmptyTranslationOutput.deviceBinary.mem.get(), existingDeviceBinary, strlen(existingDeviceBinary)));
    EXPECT_EQ(0, memcmp(nonEmptyTranslationOutput.debugData.mem.get(), existingDebugData, strlen(existingDebugData)));
    EXPECT_EQ(0, memcmp(nonEmptyTranslationOutput.intermediateRepresentation.mem.get(), existingIr, strlen(existingIr)));
}

TEST_F(CompilerInterfaceOclElfCacheTest, GivenKernelWithIncludesWhenBuildingThenPackBinaryOnCacheSaveAndUnpackBinaryOnLoadFromCache) {
    USE_REAL_FILE_SYSTEM();

    gEnvironment->igcPushDebugVars(igcDebugVarsDeviceBinary);

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "#include \"header.h\"\n__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    TranslationOutput outputFromCompilation;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, outputFromCompilation);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCompilation.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(nullptr, outputFromCompilation.debugData.mem.get());

    EXPECT_EQ(1u, mockCompilerCache->hashToBinaryMap.size());
    EXPECT_TRUE(isPackedOclElf(mockCompilerCache->hashToBinaryMap.begin()->second));

    gEnvironment->igcPopDebugVars();

    // we force igc to fail compilation request
    // at the end we expect CL_SUCCESS which means compilation ends in cache
    gEnvironment->igcPushDebugVars(igcFclDebugVarsForceBuildFailure);

    TranslationOutput outputFromCache;
    err = compilerInterface->build(device, inputArgs, outputFromCache);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);

    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCache.deviceBinary.mem.get(), outputFromCache.deviceBinary.size));
    EXPECT_EQ(nullptr, outputFromCache.debugData.mem.get());

    gEnvironment->igcPopDebugVars();
}

TEST_F(CompilerInterfaceOclElfCacheTest, GivenKernelWithIncludesWhenLoadedCacheDoesNotUnpackCorrectlyThenDoNotEndInCacheAndContinueCompilation) {
    USE_REAL_FILE_SYSTEM();

    gEnvironment->igcPushDebugVars(igcDebugVarsInvalidDeviceBinary);

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "#include \"header.h\"\n__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    TranslationOutput outputFromCompilation;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, outputFromCompilation);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(invalidBinary.data(), outputFromCompilation.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(nullptr, outputFromCompilation.debugData.mem.get());

    gEnvironment->igcPopDebugVars();

    // we force igc to fail compilation request
    // at the end we expect buildFailure which means compilation does not end with loaded cache but continues in igc
    gEnvironment->igcPushDebugVars(igcFclDebugVarsForceBuildFailure);

    TranslationOutput outputFromCache;
    err = compilerInterface->build(device, inputArgs, outputFromCache);
    EXPECT_EQ(TranslationOutput::ErrorCode::buildFailure, err);

    EXPECT_EQ(nullptr, outputFromCache.deviceBinary.mem.get());
    EXPECT_EQ(nullptr, outputFromCache.debugData.mem.get());

    gEnvironment->igcPopDebugVars();
}

TEST_F(CompilerInterfaceOclElfCacheTest, GivenKernelWithIncludesAndDebugDataWhenBuildingThenPackBinaryOnCacheSaveAndUnpackBinaryOnLoadFromCache) {
    USE_REAL_FILE_SYSTEM();

    gEnvironment->igcPushDebugVars(igcDebugVarsDeviceBinaryDebugData);

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "#include \"header.h\"\n__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    TranslationOutput outputFromCompilation;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, outputFromCompilation);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCompilation.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(0, std::strncmp(debugDataToReturn.c_str(), outputFromCompilation.debugData.mem.get(), debugDataToReturn.size()));

    EXPECT_EQ(1u, mockCompilerCache->hashToBinaryMap.size());
    EXPECT_TRUE(isPackedOclElf(mockCompilerCache->hashToBinaryMap.begin()->second));

    gEnvironment->igcPopDebugVars();

    // we force igc to fail compilation request
    // at the end we expect CL_SUCCESS which means compilation ends in cache
    gEnvironment->igcPushDebugVars(igcFclDebugVarsForceBuildFailure);

    TranslationOutput outputFromCache;
    err = compilerInterface->build(device, inputArgs, outputFromCache);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);

    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCache.deviceBinary.mem.get(), outputFromCache.deviceBinary.size));
    EXPECT_EQ(0, std::strncmp(debugDataToReturn.c_str(), outputFromCache.debugData.mem.get(), debugDataToReturn.size()));

    gEnvironment->igcPopDebugVars();
}

TEST_F(CompilerInterfaceOclElfCacheTest, GivenBinaryWhenBuildingThenPackBinaryOnCacheSaveAndUnpackBinaryOnLoadFromCache) {
    USE_REAL_FILE_SYSTEM();

    gEnvironment->igcPushDebugVars(igcDebugVarsDeviceBinary);

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    TranslationOutput outputFromCompilation;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, outputFromCompilation);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCompilation.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(nullptr, outputFromCompilation.debugData.mem.get());

    EXPECT_EQ(1u, mockCompilerCache->hashToBinaryMap.size());
    EXPECT_TRUE(isPackedOclElf(mockCompilerCache->hashToBinaryMap.begin()->second));

    gEnvironment->igcPopDebugVars();

    // we force fcl to fail compilation request
    // at the end we expect CL_SUCCESS which means compilation ends in cache
    gEnvironment->fclPushDebugVars(igcFclDebugVarsForceBuildFailure);

    TranslationOutput outputFromCache;
    err = compilerInterface->build(device, inputArgs, outputFromCache);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);

    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCache.deviceBinary.mem.get(), outputFromCache.deviceBinary.size));
    EXPECT_EQ(nullptr, outputFromCache.debugData.mem.get());

    gEnvironment->fclPopDebugVars();
}

TEST_F(CompilerInterfaceOclElfCacheTest, GivenBinaryWhenLoadedCacheDoesNotUnpackCorrectlyThenDoNotEndInCacheAndContinueCompilation) {
    USE_REAL_FILE_SYSTEM();

    gEnvironment->igcPushDebugVars(igcDebugVarsInvalidDeviceBinary);

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    TranslationOutput outputFromCompilation;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, outputFromCompilation);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(invalidBinary.data(), outputFromCompilation.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(nullptr, outputFromCompilation.debugData.mem.get());

    gEnvironment->igcPopDebugVars();

    // we force fcl to fail compilation request
    // at the end we expect buildFailure which means compilation does not end with loaded cache but continues in fcl
    gEnvironment->fclPushDebugVars(igcFclDebugVarsForceBuildFailure);

    TranslationOutput outputFromCache;
    err = compilerInterface->build(device, inputArgs, outputFromCache);
    EXPECT_EQ(TranslationOutput::ErrorCode::buildFailure, err);

    gEnvironment->fclPopDebugVars();
}

TEST_F(CompilerInterfaceOclElfCacheTest, GivenBinaryAndDebugDataWhenBuildingThenPackBinaryOnCacheSaveAndUnpackBinaryOnLoadFromCache) {
    USE_REAL_FILE_SYSTEM();

    gEnvironment->igcPushDebugVars(igcDebugVarsDeviceBinaryDebugData);

    TranslationInput inputArgs{IGC::CodeType::oclC, IGC::CodeType::oclGenBin};

    auto src = "__kernel k() {}";
    inputArgs.src = ArrayRef<const char>(src, strlen(src));

    TranslationOutput outputFromCompilation;
    MockDevice device;
    auto err = compilerInterface->build(device, inputArgs, outputFromCompilation);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCompilation.deviceBinary.mem.get(), outputFromCompilation.deviceBinary.size));
    EXPECT_EQ(0, std::strncmp(debugDataToReturn.c_str(), outputFromCompilation.debugData.mem.get(), debugDataToReturn.size()));

    EXPECT_EQ(1u, mockCompilerCache->hashToBinaryMap.size());
    EXPECT_TRUE(isPackedOclElf(mockCompilerCache->hashToBinaryMap.begin()->second));

    gEnvironment->igcPopDebugVars();

    // we force fcl to fail compilation request
    // at the end we expect CL_SUCCESS which means compilation ends in cache
    gEnvironment->fclPushDebugVars(igcFclDebugVarsForceBuildFailure);

    TranslationOutput outputFromCache;
    err = compilerInterface->build(device, inputArgs, outputFromCache);
    EXPECT_EQ(TranslationOutput::ErrorCode::success, err);
    EXPECT_EQ(0, memcmp(patchtokensProgram.storage.data(), outputFromCache.deviceBinary.mem.get(), outputFromCache.deviceBinary.size));
    EXPECT_EQ(0, std::strncmp(debugDataToReturn.c_str(), outputFromCache.debugData.mem.get(), debugDataToReturn.size()));

    gEnvironment->fclPopDebugVars();
}

class CompilerCacheHelperWhitelistedTest : public ::testing::Test, public CompilerCacheHelper {
  public:
    using CompilerCacheHelper::whitelistedIncludes;

    bool isValidIncludeFormat(std::string_view entry) {
        size_t spacePos = entry.find(' ');
        if (spacePos == std::string_view::npos) {
            return false;
        }

        std::string_view firstWord = entry.substr(0, spacePos);
        if (firstWord != "#include") {
            return false;
        }

        std::string_view secondPart = entry.substr(spacePos + 1);
        if (secondPart.empty()) {
            return false;
        }

        return true;
    }
};

TEST_F(CompilerCacheHelperWhitelistedTest, GivenWhitelistedIncludesWhenCheckingFormatThenExpectValidIncludeFormat) {
    for (const auto &entry : whitelistedIncludes) {
        EXPECT_TRUE(isValidIncludeFormat(entry))
            << "Invalid format in whitelisted include: " << entry;
    }
}

TEST_F(CompilerCacheHelperWhitelistedTest, GivenWhitelistedIncludesWhenCheckingContentsThenExpectCorrectEntries) {
    std::vector<std::string_view> expectedEntries{
        "#include <cm/cm.h>",
        "#include <cm/cmtl.h>"};

    for (const auto &expectedEntry : expectedEntries) {
        auto it = std::find(whitelistedIncludes.begin(), whitelistedIncludes.end(), expectedEntry);
        EXPECT_NE(it, whitelistedIncludes.end())
            << "Expected entry '" << expectedEntry << "' not found in whitelistedIncludes.";
    }

    EXPECT_EQ(whitelistedIncludes.size(), expectedEntries.size())
        << "whitelistedIncludes contains unexpected entries.";
}

class CompilerCacheHelperMockedWhitelistedIncludesTests : public ::testing::Test, public CompilerCacheHelper {
  public:
    using CompilerCacheHelper::whitelistedIncludes;

    CompilerCacheHelperMockedWhitelistedIncludesTests() : backup(&whitelistedIncludes, {"#include <whitelisted>"}) {}

    void SetUp() override {}
    void TearDown() override {}

    VariableBackup<decltype(whitelistedIncludes)> backup;
};

TEST_F(CompilerCacheHelperMockedWhitelistedIncludesTests, GivenSourceWithWhitelistedIncludeWhenCheckingWhitelistedIncludesThenReturnsTrue) {
    const StackVec<const char *, 6> sources = {
        "__kernel void k() {}",                                                 // no includes
        "#include <whitelisted>\n__kernel void k() {}",                         // whitelisted include
        "",                                                                     // empty source
        "    #include <whitelisted>\n__kernel void k() {}",                     // leading spaces
        "\t#include <whitelisted>\n__kernel void k() {}",                       // leading tabs
        "#include <whitelisted>\n#include <whitelisted>\n__kernel void k() {}", // multiple whitelisted
        "\n#include <whitelisted>\n__kernel void k() {}",                       // leading newline
        "\r\n#include <whitelisted>\n__kernel void k() {}"                      // leading carriage return + newline
    };

    for (const auto &source : sources) {
        ArrayRef<const char> sourceRef(source, strlen(source));
        EXPECT_TRUE(CompilerCacheHelper::validateIncludes(sourceRef, CompilerCacheHelper::whitelistedIncludes))
            << "Failed for source: " << source;
    }
}

TEST_F(CompilerCacheHelperMockedWhitelistedIncludesTests, GivenSourceWithNonWhitelistedIncludeWhenCheckingWhitelistedIncludesThenReturnsFalse) {
    const StackVec<const char *, 3> sources = {
        "#include <unknown/unknown.h>\n__kernel void k() {}",                         // non-whitelisted include
        "#include <whitelisted>\n#include <unknown/unknown.h>\n__kernel void k() {}", // mixed includes - first whitelisted, second non-whitelisted
        "#include <unknown/unknown.h>\n#include <whitelisted>\n__kernel void k() {}"  // mixed includes - first non-whitelisted, second whitelisted
    };

    for (const auto &source : sources) {
        ArrayRef<const char> sourceRef(source, strlen(source));
        EXPECT_FALSE(CompilerCacheHelper::validateIncludes(sourceRef, CompilerCacheHelper::whitelistedIncludes))
            << "Failed for source: " << source;
    }
}

TEST_F(CompilerCacheHelperMockedWhitelistedIncludesTests, GivenDisabledOrNullCacheWhenGettingCachingModeThenReturnsCachingModeNone) {
    CompilerCache cache(CompilerCacheConfig{false, "", "", 0});
    const StackVec<std::pair<const char *, IGC::CodeType::CodeType_t>, 3> testCases = {
        {"#include <whitelisted>\n__kernel void k() {}", IGC::CodeType::oclC},      // disabled cache
        {"__kernel void k() {}", IGC::CodeType::oclC},                              // disabled cache, no includes
        {"#include <unknown/unknown.h>\n__kernel void k() {}", IGC::CodeType::oclC} // disabled cache, non-whitelisted include
    };

    for (const auto &testCase : testCases) {
        ArrayRef<const char> sourceRef(testCase.first, strlen(testCase.first));
        EXPECT_EQ(CachingMode::none, CompilerCacheHelper::getCachingMode(&cache, testCase.second, sourceRef))
            << "Failed for source: " << testCase.first;
    }

    EXPECT_EQ(CachingMode::none, CompilerCacheHelper::getCachingMode(nullptr, IGC::CodeType::oclC, ArrayRef<const char>()))
        << "Failed for nullptr CompilerCache";
}

TEST_F(CompilerCacheHelperMockedWhitelistedIncludesTests, GivenEnabledCacheAndOclCWithWhitelistedIncludesWhenGettingCachingModeThenReturnsCachingModeDirect) {
    CompilerCache cache(CompilerCacheConfig{true, "", "", 0});
    const StackVec<std::pair<const char *, IGC::CodeType::CodeType_t>, 2> testCases = {
        {"__kernel void k() {}", IGC::CodeType::oclC},                        // no includes
        {"#include <whitelisted>\n__kernel void k() {}", IGC::CodeType::oclC} // only whitelisted include
    };

    for (const auto &testCase : testCases) {
        ArrayRef<const char> sourceRef(testCase.first, strlen(testCase.first));
        EXPECT_EQ(CachingMode::direct, CompilerCacheHelper::getCachingMode(&cache, testCase.second, sourceRef))
            << "Failed for source: " << testCase.first;
    }
}

TEST_F(CompilerCacheHelperMockedWhitelistedIncludesTests, GivenEnabledCacheAndNonWhitelistedIncludesOrNonOclCWhenGettingCachingModeThenReturnsCachingModePreProcess) {
    CompilerCache cache(CompilerCacheConfig{true, "", "", 0});
    const StackVec<std::pair<const char *, IGC::CodeType::CodeType_t>, 6> testCases = {
        {"#include <unknown/unknown.h>\n__kernel void k() {}", IGC::CodeType::oclC},                         // non-whitelisted include
        {"#include <whitelisted>\n#include <unknown/unknown.h>\n__kernel void k() {}", IGC::CodeType::oclC}, // mixed includes
        {"#include <unknown/unknown.h>\n#include <whitelisted>\n__kernel void k() {}", IGC::CodeType::oclC}, // mixed includes different order
        {"__kernel void k() {}", IGC::CodeType::spirV},                                                      // non-oclC type
        {"#include <whitelisted>\n__kernel void k() {}", IGC::CodeType::spirV},                              // non-oclC type with whitelisted include
        {"#include <unknown/unknown.h>\n__kernel void k() {}", IGC::CodeType::spirV}                         // non-oclC type with non-whitelisted include
    };

    for (const auto &testCase : testCases) {
        ArrayRef<const char> sourceRef(testCase.first, strlen(testCase.first));
        EXPECT_EQ(CachingMode::preProcess, CompilerCacheHelper::getCachingMode(&cache, testCase.second, sourceRef))
            << "Failed for source: " << testCase.first;
    }
}