-
Notifications
You must be signed in to change notification settings - Fork 245
/
Copy pathoffline_compiler.cpp
1669 lines (1447 loc) · 73.8 KB
/
offline_compiler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2018-2025 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "offline_compiler.h"
#include "shared/offline_compiler/source/ocloc_api.h"
#include "shared/offline_compiler/source/ocloc_arg_helper.h"
#include "shared/offline_compiler/source/ocloc_fatbinary.h"
#include "shared/offline_compiler/source/ocloc_fcl_facade.h"
#include "shared/offline_compiler/source/ocloc_igc_facade.h"
#include "shared/offline_compiler/source/ocloc_supported_devices_helper.h"
#include "shared/offline_compiler/source/queries.h"
#include "shared/offline_compiler/source/utilities/get_git_version_info.h"
#include "shared/source/compiler_interface/compiler_options.h"
#include "shared/source/compiler_interface/compiler_options_extra.h"
#include "shared/source/compiler_interface/default_cache_config.h"
#include "shared/source/compiler_interface/intermediate_representations.h"
#include "shared/source/compiler_interface/oclc_extensions.h"
#include "shared/source/compiler_interface/tokenized_string.h"
#include "shared/source/debug_settings/debug_settings_manager.h"
#include "shared/source/device_binary_format/device_binary_formats.h"
#include "shared/source/device_binary_format/elf/elf_encoder.h"
#include "shared/source/device_binary_format/elf/ocl_elf.h"
#include "shared/source/helpers/compiler_options_parser.h"
#include "shared/source/helpers/compiler_product_helper.h"
#include "shared/source/helpers/debug_helpers.h"
#include "shared/source/helpers/string.h"
#include "shared/source/helpers/validators.h"
#include "shared/source/release_helper/release_helper.h"
#include "platforms.h"
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <set>
#ifdef _WIN32
#include <direct.h>
#define MakeDirectory _mkdir
#define GetCurrentWorkingDirectory _getcwd
#else
#include <sys/stat.h>
#define MakeDirectory(dir) mkdir(dir, 0777)
#define GetCurrentWorkingDirectory getcwd
#endif
namespace NEO {
std::string convertToPascalCase(const std::string &inString) {
std::string outString;
bool capitalize = true;
for (unsigned int i = 0; i < inString.length(); i++) {
if (isalpha(inString[i]) && capitalize == true) {
outString += toupper(inString[i]);
capitalize = false;
} else if (inString[i] == '_') {
capitalize = true;
} else {
outString += inString[i];
}
}
return outString;
}
std::string getDeprecatedDevices(OclocArgHelper *helper) {
auto acronyms = helper->productConfigHelper->getDeprecatedAcronyms();
return helper->createStringForArgs(acronyms);
}
std::string getSupportedDevices(OclocArgHelper *helper) {
auto devices = helper->productConfigHelper->getAllProductAcronyms();
auto families = helper->productConfigHelper->getFamiliesAcronyms();
auto releases = helper->productConfigHelper->getReleasesAcronyms();
auto familiesAndReleases = helper->getArgsWithoutDuplicate(families, releases);
return helper->createStringForArgs(devices, familiesAndReleases);
}
OfflineCompiler::OfflineCompiler() = default;
OfflineCompiler::~OfflineCompiler() {
pBuildInfo.reset();
delete[] irBinary;
delete[] genBinary;
delete[] debugDataBinary;
}
OfflineCompiler *OfflineCompiler::create(size_t numArgs, const std::vector<std::string> &allArgs, bool dumpFiles, int &retVal, OclocArgHelper *helper) {
retVal = OCLOC_SUCCESS;
auto pOffCompiler = new OfflineCompiler();
if (pOffCompiler) {
pOffCompiler->argHelper = helper;
pOffCompiler->fclFacade = std::make_unique<OclocFclFacade>(helper);
pOffCompiler->igcFacade = std::make_unique<OclocIgcFacade>(helper);
retVal = pOffCompiler->initialize(numArgs, allArgs, dumpFiles);
}
if (retVal != OCLOC_SUCCESS) {
delete pOffCompiler;
pOffCompiler = nullptr;
}
return pOffCompiler;
}
void printQueryHelp(OclocArgHelper *helper) {
helper->printf(OfflineCompiler::queryHelp.data());
}
NameVersionPair::NameVersionPair(ConstStringRef name, unsigned int version) {
this->version = version;
this->name[OCLOC_NAME_VERSION_MAX_NAME_SIZE - 1] = '\0';
strncpy_s(this->name, sizeof(this->name), name.data(), name.size());
};
std::vector<NameVersionPair> OfflineCompiler::getExtensions(ConstStringRef product, bool needVersions, OclocArgHelper *helper) {
std::vector<NameVersionPair> ret;
std::vector<std::string> args;
args.push_back("ocloc");
args.push_back("-device");
args.push_back(product.str());
int retVal = 0;
std::unique_ptr<OfflineCompiler> compiler{OfflineCompiler::create(args.size(), args, true, retVal, helper)};
if (nullptr == compiler) {
return {};
}
auto extensionsStr = compiler->compilerProductHelper->getDeviceExtensions(compiler->hwInfo, compiler->releaseHelper.get());
auto extensions = NEO::CompilerOptions::tokenize(extensionsStr, ' ');
ret.reserve(extensions.size());
for (const auto &ext : extensions) {
unsigned int version = 0;
if (needVersions) {
version = NEO::getOclCExtensionVersion(ext.str(), CL_MAKE_VERSION(1u, 0, 0));
}
ret.emplace_back(ext, version);
}
return ret;
}
std::vector<NameVersionPair> OfflineCompiler::getOpenCLCVersions(ConstStringRef product, OclocArgHelper *helper) {
std::vector<std::string> args;
args.push_back("ocloc");
args.push_back("-device");
args.push_back(product.str());
int retVal = 0;
std::unique_ptr<OfflineCompiler> compiler{OfflineCompiler::create(args.size(), args, true, retVal, helper)};
if (nullptr == compiler) {
return {};
}
auto deviceOpenCLCVersions = compiler->compilerProductHelper->getDeviceOpenCLCVersions(compiler->getHardwareInfo(), {});
NameVersionPair openClCVersion{"OpenCL C", 0};
std::vector<NameVersionPair> allSupportedVersions;
for (auto &ver : deviceOpenCLCVersions) {
openClCVersion.version = CL_MAKE_VERSION(ver.major, ver.minor, 0);
allSupportedVersions.push_back(openClCVersion);
}
return allSupportedVersions;
}
std::vector<NameVersionPair> OfflineCompiler::getOpenCLCFeatures(ConstStringRef product, OclocArgHelper *helper) {
std::vector<std::string> args;
args.push_back("ocloc");
args.push_back("-device");
args.push_back(product.str());
int retVal = 0;
std::unique_ptr<OfflineCompiler> compiler{OfflineCompiler::create(args.size(), args, true, retVal, helper)};
if (nullptr == compiler) {
return {};
}
OpenClCFeaturesContainer availableFeatures;
NEO::getOpenclCFeaturesList(compiler->getHardwareInfo(), availableFeatures, *compiler->compilerProductHelper, compiler->releaseHelper.get());
std::vector<NameVersionPair> allSupportedFeatures;
for (auto &feature : availableFeatures) {
allSupportedFeatures.push_back({feature.name, feature.version});
}
return allSupportedFeatures;
}
std::vector<NameVersionPair> getCommonNameVersion(const std::vector<std::vector<NameVersionPair>> &perTarget) {
std::vector<NameVersionPair> commonExtensionsVec;
if (perTarget.size() == 1) {
commonExtensionsVec = perTarget[0];
} else {
std::map<std::string, std::map<unsigned int, int>> allExtensions;
for (const auto &targetExt : perTarget) {
for (const auto &ext : targetExt) {
++allExtensions[ext.name][ext.version];
}
}
int numTargets = static_cast<int>(perTarget.size());
for (const auto &extScore : allExtensions) {
for (const auto &version : extScore.second) {
if ((version.second == numTargets)) {
commonExtensionsVec.emplace_back(ConstStringRef(extScore.first), version.first);
}
}
}
}
return commonExtensionsVec;
}
std::vector<NameVersionPair> getCommonExtensions(std::vector<ConstStringRef> products, bool needVersions, OclocArgHelper *helper) {
std::vector<std::vector<NameVersionPair>> perTarget;
for (const auto &targetProduct : products) {
auto extensions = OfflineCompiler::getExtensions(targetProduct, needVersions, helper);
perTarget.push_back(extensions);
}
auto commonExtensions = getCommonNameVersion(perTarget);
return commonExtensions;
}
std::vector<NameVersionPair> getCommonOpenCLCVersions(std::vector<ConstStringRef> products, OclocArgHelper *helper) {
std::vector<std::vector<NameVersionPair>> perTarget;
for (const auto &targetProduct : products) {
auto versions = OfflineCompiler::getOpenCLCVersions(targetProduct, helper);
perTarget.push_back(versions);
}
return getCommonNameVersion(perTarget);
}
std::vector<NameVersionPair> getCommonOpenCLCFeatures(std::vector<ConstStringRef> products, OclocArgHelper *helper) {
std::vector<std::vector<NameVersionPair>> perTarget;
for (const auto &targetProduct : products) {
auto features = OfflineCompiler::getOpenCLCFeatures(targetProduct, helper);
perTarget.push_back(features);
}
return getCommonNameVersion(perTarget);
}
std::string formatNameVersionString(std::vector<NameVersionPair> extensions, bool needVersions) {
std::vector<std::string> formatedExtensions;
formatedExtensions.reserve(extensions.size());
for (const auto &ext : extensions) {
formatedExtensions.push_back({});
auto it = formatedExtensions.rbegin();
bool needsQuoutes = (nullptr != strchr(ext.name, ' '));
it->reserve(strnlen_s(ext.name, sizeof(ext.name)) + (needsQuoutes ? 2 : 0) + (needVersions ? 16 : 0));
if (needsQuoutes) {
it->append("\"");
}
it->append(ext.name);
if (needsQuoutes) {
it->append("\"");
}
if (needVersions) {
it->append(":");
it->append(std::to_string(CL_VERSION_MAJOR(ext.version)));
it->append(".");
it->append(std::to_string(CL_VERSION_MINOR(ext.version)));
it->append(".");
it->append(std::to_string(CL_VERSION_PATCH(ext.version)));
}
}
return ConstStringRef(" ").join(formatedExtensions);
}
int OfflineCompiler::query(size_t numArgs, const std::vector<std::string> &allArgs, OclocArgHelper *helper) {
if (allArgs.size() < 3) {
helper->printf("Error: Invalid command line. Expected ocloc query <argument>. See ocloc query --help\n");
return OCLOC_INVALID_COMMAND_LINE;
}
Ocloc::SupportedDevicesMode supportedDevicesMode = Ocloc::SupportedDevicesMode::concat;
std::vector<ConstStringRef> targetProducts;
std::vector<Queries::QueryType> queries;
auto argIt = allArgs.begin() + 2;
std::string deviceArg = "*";
while (argIt != allArgs.end()) {
if ("-device" == *argIt) {
if (argIt + 1 == allArgs.end()) {
helper->printf("Error: Invalid command line : -device must be followed by device name\n");
}
++argIt;
deviceArg = *argIt;
} else if (Queries::queryNeoRevision == *argIt) {
queries.push_back(Queries::QueryType::neoRevision);
} else if (Queries::queryOCLDriverVersion == *argIt) {
queries.push_back(Queries::QueryType::oclDriverVersion);
} else if (Queries::queryIgcRevision == *argIt) {
queries.push_back(Queries::QueryType::igcRevision);
} else if (Queries::queryOCLDeviceExtensions == *argIt) {
queries.push_back(Queries::QueryType::oclDeviceExtensions);
} else if (Queries::queryOCLDeviceExtensionsWithVersion == *argIt) {
queries.push_back(Queries::QueryType::oclDeviceExtensionsWithVersion);
} else if (Queries::queryOCLDeviceProfile == *argIt) {
queries.push_back(Queries::QueryType::oclDeviceProfile);
} else if (Queries::queryOCLDeviceOpenCLCAllVersions == *argIt) {
queries.push_back(Queries::QueryType::oclDeviceOpenCLCAllVersions);
} else if (Queries::queryOCLDeviceOpenCLCFeatures == *argIt) {
queries.push_back(Queries::QueryType::oclDeviceOpenCLCFeatures);
} else if (Queries::querySupportedDevices == *argIt) {
queries.push_back(Queries::QueryType::supportedDevices);
if (argIt + 1 != allArgs.end()) {
auto newMode = Ocloc::parseSupportedDevicesMode(*(argIt + 1));
if (newMode != Ocloc::SupportedDevicesMode::unknown) {
supportedDevicesMode = newMode;
++argIt;
}
}
} else if ("--help" == *argIt) {
printQueryHelp(helper);
return 0;
} else {
helper->printf("Error: Invalid command line.\nUnknown argument %s\n", argIt->c_str());
return OCLOC_INVALID_COMMAND_LINE;
}
++argIt;
}
if (NEO::requestedFatBinary(deviceArg, helper)) {
targetProducts = NEO::getTargetProductsForFatbinary(deviceArg, helper);
} else {
targetProducts.push_back(deviceArg);
}
for (const auto &queryType : queries) {
switch (queryType) {
default:
helper->printf("Error: Invalid command line. See ocloc query --help\n");
break;
case Queries::QueryType::neoRevision: {
auto revision = NEO::getRevision();
helper->saveOutput(Queries::queryNeoRevision.str(), revision.c_str(), revision.size() + 1);
helper->printf("%s\n", revision.c_str());
} break;
case Queries::QueryType::oclDriverVersion: {
auto driverVersion = NEO::getOclDriverVersion();
helper->saveOutput(Queries::queryOCLDriverVersion.str(), driverVersion.c_str(), driverVersion.size() + 1);
helper->printf("%s\n", driverVersion.c_str());
} break;
case Queries::QueryType::igcRevision: {
auto igcFacade = std::make_unique<OclocIgcFacade>(helper);
NEO::HardwareInfo hwInfo{};
auto initResult = igcFacade->initialize(hwInfo);
if (initResult == OCLOC_SUCCESS) {
auto igcRev = igcFacade->getIgcRevision();
helper->saveOutput(Queries::queryIgcRevision.str(), igcRev, strlen(igcRev) + 1);
helper->printf("%s\n", igcRev);
}
} break;
case Queries::QueryType::oclDeviceExtensions: {
auto commonExtensionsVec = getCommonExtensions(targetProducts, false, helper);
auto commonExtString = formatNameVersionString(commonExtensionsVec, false);
helper->saveOutput(Queries::queryOCLDeviceExtensions.str(), commonExtString.c_str(), commonExtString.size());
helper->printf("%s\n", commonExtString.c_str());
} break;
case Queries::QueryType::oclDeviceExtensionsWithVersion: {
auto commonExtensionsVec = getCommonExtensions(targetProducts, true, helper);
auto commonExtString = formatNameVersionString(commonExtensionsVec, true);
helper->saveOutput(Queries::queryOCLDeviceExtensionsWithVersion.str(), commonExtensionsVec.data(), commonExtensionsVec.size() * sizeof(NameVersionPair));
helper->printf("%s\n", commonExtString.c_str());
} break;
case Queries::QueryType::oclDeviceProfile: {
ConstStringRef profile{"FULL_PROFILE\n"};
helper->saveOutput(Queries::queryOCLDeviceProfile.str(), profile.data(), profile.size());
helper->printf("%s\n", profile.data());
} break;
case Queries::QueryType::oclDeviceOpenCLCAllVersions: {
auto commonVersionsVec = getCommonOpenCLCVersions(targetProducts, helper);
auto commonVersionsString = formatNameVersionString(commonVersionsVec, true);
helper->saveOutput(Queries::queryOCLDeviceOpenCLCAllVersions.str(), commonVersionsVec.data(), commonVersionsVec.size() * sizeof(NameVersionPair));
helper->printf("%s\n", commonVersionsString.c_str());
} break;
case Queries::QueryType::oclDeviceOpenCLCFeatures: {
auto commonFeaturesVec = getCommonOpenCLCFeatures(targetProducts, helper);
auto commonFeaturesString = formatNameVersionString(commonFeaturesVec, true);
helper->saveOutput(Queries::queryOCLDeviceOpenCLCFeatures.str(), commonFeaturesVec.data(), commonFeaturesVec.size() * sizeof(NameVersionPair));
helper->printf("%s\n", commonFeaturesString.c_str());
} break;
case Queries::QueryType::supportedDevices: {
querySupportedDevices(supportedDevicesMode, helper);
} break;
}
}
return OCLOC_SUCCESS;
}
void printAcronymIdsHelp(OclocArgHelper *helper) {
helper->printf(OfflineCompiler::idsHelp.data(), getSupportedDevices(helper).c_str());
}
int OfflineCompiler::queryAcronymIds(size_t numArgs, const std::vector<std::string> &allArgs, OclocArgHelper *helper) {
const size_t numArgRequested = 3u;
auto retVal = OCLOC_SUCCESS;
if (numArgs != numArgRequested) {
helper->printf("Error: Invalid command line. Expected ocloc ids <acronym>.\n");
retVal = OCLOC_INVALID_COMMAND_LINE;
return retVal;
} else if ((ConstStringRef("-h") == allArgs[2] || ConstStringRef("--help") == allArgs[2])) {
printAcronymIdsHelp(helper);
return retVal;
}
std::string queryAcronym = allArgs[2];
ProductConfigHelper::adjustDeviceName(queryAcronym);
auto &enabledDevices = helper->productConfigHelper->getDeviceAotInfo();
std::vector<std::string> matchedVersions{};
auto family = helper->productConfigHelper->getFamilyFromDeviceName(queryAcronym);
auto release = helper->productConfigHelper->getReleaseFromDeviceName(queryAcronym);
auto product = helper->productConfigHelper->getProductConfigFromDeviceName(queryAcronym);
if (family != AOT::UNKNOWN_FAMILY) {
for (const auto &device : enabledDevices) {
if (device.family == family) {
matchedVersions.push_back(ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig));
}
}
} else if (release != AOT::UNKNOWN_RELEASE) {
for (const auto &device : enabledDevices) {
if (device.release == release) {
matchedVersions.push_back(ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig));
}
}
} else if (product != AOT::UNKNOWN_ISA) {
for (const auto &device : enabledDevices) {
if (device.aotConfig.value == product) {
matchedVersions.push_back(ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig));
}
}
} else {
bool isMatched{false};
if (auto hwInfoDepAcr = getHwInfoForDeprecatedAcronym(queryAcronym); hwInfoDepAcr) {
if (auto compilerProductHelper = NEO::CompilerProductHelper::create(hwInfoDepAcr->platform.eProductFamily); compilerProductHelper) {
matchedVersions.push_back(ProductConfigHelper::parseMajorMinorRevisionValue(compilerProductHelper->getDefaultHwIpVersion()));
isMatched = true;
}
}
if (!isMatched) {
helper->printf("Error: Invalid command line. Unknown acronym %s.\n", allArgs[2].c_str());
retVal = OCLOC_INVALID_COMMAND_LINE;
return retVal;
}
}
std::ostringstream os;
for (const auto &prefix : matchedVersions) {
if (os.tellp())
os << "\n";
os << prefix;
}
helper->printf("Matched ids:\n%s\n", os.str().c_str());
return retVal;
}
int OfflineCompiler::querySupportedDevices(Ocloc::SupportedDevicesMode mode, OclocArgHelper *helper) {
auto enabledDevices = helper->productConfigHelper->getDeviceAotInfo();
Ocloc::SupportedDevicesHelper supportedDevicesHelper(mode, helper->productConfigHelper.get());
auto supportedDevicesData = supportedDevicesHelper.collectSupportedDevicesData(enabledDevices);
std::string output;
if (mode == Ocloc::SupportedDevicesMode::merge) {
output = supportedDevicesHelper.mergeAndSerializeWithFormerData(supportedDevicesData);
} else {
output = supportedDevicesHelper.concatAndSerializeWithFormerData(supportedDevicesData);
}
helper->saveOutput(supportedDevicesHelper.getCurrentOclocOutputFilename(), output.data(), output.size());
return 0;
}
struct OfflineCompiler::BuildInfo {
std::unique_ptr<CIF::Builtins::BufferLatest, CIF::RAII::ReleaseHelper<CIF::Builtins::BufferLatest>> fclOptions;
std::unique_ptr<CIF::Builtins::BufferLatest, CIF::RAII::ReleaseHelper<CIF::Builtins::BufferLatest>> fclInternalOptions;
std::unique_ptr<IGC::OclTranslationOutputTagOCL, CIF::RAII::ReleaseHelper<IGC::OclTranslationOutputTagOCL>> fclOutput;
IGC::CodeType::CodeType_t intermediateRepresentation;
};
int OfflineCompiler::buildIrBinary() {
int retVal = OCLOC_SUCCESS;
pBuildInfo->intermediateRepresentation = preferredIntermediateRepresentation;
if (inputFileLlvm) {
pBuildInfo->intermediateRepresentation = useLlvmText ? IGC::CodeType::llvmLl : IGC::CodeType::llvmBc;
}
isSpirV = pBuildInfo->intermediateRepresentation == IGC::CodeType::spirV;
if (allowCaching) {
const std::string igcRevision = igcFacade->getIgcRevision();
const auto igcLibSize = igcFacade->getIgcLibSize();
const auto igcLibMTime = igcFacade->getIgcLibMTime();
irHash = cache->getCachedFileName(getHardwareInfo(),
sourceCode,
options,
internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), igcRevision, igcLibSize, igcLibMTime);
irBinary = cache->loadCachedBinary(irHash, irBinarySize).release();
if (irBinary) {
return retVal;
}
}
UNRECOVERABLE_IF(!fclFacade->isInitialized());
// sourceCode.size() returns the number of characters without null terminated char
CIF::RAII::UPtr_t<CIF::Builtins::BufferLatest> fclSrc = nullptr;
pBuildInfo->fclOptions = fclFacade->createConstBuffer(options.c_str(), options.size());
pBuildInfo->fclInternalOptions = fclFacade->createConstBuffer(internalOptions.c_str(), internalOptions.size());
auto err = fclFacade->createConstBuffer(nullptr, 0);
auto srcType = IGC::CodeType::undefined;
std::vector<uint8_t> tempSrcStorage;
if (this->argHelper->hasHeaders()) {
srcType = IGC::CodeType::elf;
NEO::Elf::ElfEncoder<> elfEncoder(true, true, 1U);
elfEncoder.getElfFileHeader().type = NEO::Elf::ET_OPENCL_SOURCE;
elfEncoder.appendSection(NEO::Elf::SHT_OPENCL_SOURCE, "CLMain", sourceCode);
for (const auto &header : this->argHelper->getHeaders()) {
ArrayRef<const uint8_t> headerData(header.data, header.length);
ConstStringRef headerName = header.name;
elfEncoder.appendSection(NEO::Elf::SHT_OPENCL_HEADER, headerName, headerData);
}
tempSrcStorage = elfEncoder.encode();
fclSrc = fclFacade->createConstBuffer(tempSrcStorage.data(), tempSrcStorage.size());
} else {
srcType = IGC::CodeType::oclC;
fclSrc = fclFacade->createConstBuffer(sourceCode.c_str(), sourceCode.size() + 1);
}
auto fclTranslationCtx = fclFacade->createTranslationContext(srcType, pBuildInfo->intermediateRepresentation, err.get());
if (true == NEO::areNotNullptr(err->GetMemory<char>())) {
updateBuildLog(err->GetMemory<char>(), err->GetSizeRaw());
retVal = OCLOC_BUILD_PROGRAM_FAILURE;
return retVal;
}
if (false == NEO::areNotNullptr(fclSrc.get(), pBuildInfo->fclOptions.get(), pBuildInfo->fclInternalOptions.get(),
fclTranslationCtx.get())) {
retVal = OCLOC_OUT_OF_HOST_MEMORY;
return retVal;
}
pBuildInfo->fclOutput = fclTranslationCtx->Translate(fclSrc.get(), pBuildInfo->fclOptions.get(),
pBuildInfo->fclInternalOptions.get(), nullptr, 0);
if (pBuildInfo->fclOutput == nullptr) {
retVal = OCLOC_OUT_OF_HOST_MEMORY;
return retVal;
}
UNRECOVERABLE_IF(pBuildInfo->fclOutput->GetBuildLog() == nullptr);
UNRECOVERABLE_IF(pBuildInfo->fclOutput->GetOutput() == nullptr);
if (pBuildInfo->fclOutput->Successful() == false) {
updateBuildLog(pBuildInfo->fclOutput->GetBuildLog()->GetMemory<char>(), pBuildInfo->fclOutput->GetBuildLog()->GetSizeRaw());
retVal = OCLOC_BUILD_PROGRAM_FAILURE;
return retVal;
}
storeBinary(irBinary, irBinarySize, pBuildInfo->fclOutput->GetOutput()->GetMemory<char>(), pBuildInfo->fclOutput->GetOutput()->GetSizeRaw());
updateBuildLog(pBuildInfo->fclOutput->GetBuildLog()->GetMemory<char>(), pBuildInfo->fclOutput->GetBuildLog()->GetSizeRaw());
if (allowCaching) {
cache->cacheBinary(irHash, irBinary, static_cast<uint32_t>(irBinarySize));
}
return retVal;
}
std::string OfflineCompiler::validateInputType(const std::string &input, bool isLlvm, bool isSpirv) {
auto asBitcode = ArrayRef<const uint8_t>::fromAny(input.data(), input.size());
if (isSpirv) {
if (NEO::isSpirVBitcode(asBitcode)) {
return "";
}
return "Warning : file does not look like spirv bitcode (wrong magic numbers)";
}
if (isLlvm) {
if (NEO::isLlvmBitcode(asBitcode)) {
return "";
}
return "Warning : file does not look like llvm bitcode (wrong magic numbers)";
}
if (NEO::isSpirVBitcode(asBitcode)) {
return "Warning : file looks like spirv bitcode (based on magic numbers) - please make sure proper CLI flags are present";
}
if (NEO::isLlvmBitcode(asBitcode)) {
return "Warning : file looks like llvm bitcode (based on magic numbers) - please make sure proper CLI flags are present";
}
return "";
}
int OfflineCompiler::buildSourceCode() {
int retVal = OCLOC_SUCCESS;
if (sourceCode.empty()) {
return OCLOC_INVALID_PROGRAM;
}
auto inputTypeWarnings = validateInputType(sourceCode, inputFileLlvm, inputFileSpirV);
this->argHelper->printf(inputTypeWarnings.c_str());
bool inputIsIntermediateRepresentation = inputFileLlvm || inputFileSpirV;
if (inputIsIntermediateRepresentation) {
storeBinary(irBinary, irBinarySize, sourceCode.c_str(), sourceCode.size());
auto asBitcode = ArrayRef<const uint8_t>::fromAny(irBinary, irBinarySize);
isSpirV = NEO::isSpirVBitcode(asBitcode);
pBuildInfo->intermediateRepresentation = isSpirV ? IGC::CodeType::spirV : IGC::CodeType::llvmBc;
} else {
retVal = buildIrBinary();
if (retVal != OCLOC_SUCCESS)
return retVal;
}
const std::string igcRevision = igcFacade->getIgcRevision();
const auto igcLibSize = igcFacade->getIgcLibSize();
const auto igcLibMTime = igcFacade->getIgcLibMTime();
const bool generateDebugInfo = CompilerOptions::contains(options, CompilerOptions::generateDebugInfo);
if (allowCaching) {
genHash = cache->getCachedFileName(getHardwareInfo(), ArrayRef<const char>(irBinary, irBinarySize), options, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), igcRevision, igcLibSize, igcLibMTime);
if (generateDebugInfo) {
dbgHash = cache->getCachedFileName(getHardwareInfo(), irHash, options, internalOptions, ArrayRef<const char>(), ArrayRef<const char>(), igcRevision, igcLibSize, igcLibMTime);
}
genBinary = cache->loadCachedBinary(genHash, genBinarySize).release();
if (genBinary) {
bool isZebin = isDeviceBinaryFormat<DeviceBinaryFormat::zebin>(ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(genBinary), genBinarySize));
if (!generateDebugInfo || isZebin) {
return retVal;
}
debugDataBinary = cache->loadCachedBinary(dbgHash, debugDataBinarySize).release();
if (debugDataBinary) {
return retVal;
}
}
delete[] genBinary;
genBinary = nullptr;
genBinarySize = 0;
}
UNRECOVERABLE_IF(!igcFacade->isInitialized());
auto igcTranslationCtx = igcFacade->createTranslationContext(pBuildInfo->intermediateRepresentation, IGC::CodeType::oclGenBin);
auto igcSrc = igcFacade->createConstBuffer(irBinary, irBinarySize);
auto igcOptions = igcFacade->createConstBuffer(options.c_str(), options.size());
auto igcInternalOptions = igcFacade->createConstBuffer(internalOptions.c_str(), internalOptions.size());
auto igcOutput = igcTranslationCtx->Translate(igcSrc.get(), igcOptions.get(), igcInternalOptions.get(), nullptr, 0);
if (igcOutput == nullptr) {
return OCLOC_OUT_OF_HOST_MEMORY;
}
UNRECOVERABLE_IF(igcOutput->GetBuildLog() == nullptr);
UNRECOVERABLE_IF(igcOutput->GetOutput() == nullptr);
updateBuildLog(igcOutput->GetBuildLog()->GetMemory<char>(), igcOutput->GetBuildLog()->GetSizeRaw());
if (igcOutput->GetOutput()->GetSizeRaw() != 0) {
storeBinary(genBinary, genBinarySize, igcOutput->GetOutput()->GetMemory<char>(), igcOutput->GetOutput()->GetSizeRaw());
}
if (igcOutput->GetDebugData()->GetSizeRaw() != 0) {
storeBinary(debugDataBinary, debugDataBinarySize, igcOutput->GetDebugData()->GetMemory<char>(), igcOutput->GetDebugData()->GetSizeRaw());
}
if (allowCaching) {
cache->cacheBinary(genHash, genBinary, static_cast<uint32_t>(genBinarySize));
cache->cacheBinary(dbgHash, debugDataBinary, static_cast<uint32_t>(debugDataBinarySize));
}
retVal = igcOutput->Successful() ? OCLOC_SUCCESS : OCLOC_BUILD_PROGRAM_FAILURE;
return retVal;
}
int OfflineCompiler::build() {
if (inputFile.empty()) {
argHelper->printf("Error: Input file name missing.\n");
return OCLOC_INVALID_COMMAND_LINE;
} else if (!argHelper->fileExists(inputFile)) {
argHelper->printf("Error: Input file %s missing.\n", inputFile.c_str());
return OCLOC_INVALID_FILE;
}
const char *source = nullptr;
std::unique_ptr<char[]> sourceFromFile;
size_t sourceFromFileSize = 0;
sourceFromFile = argHelper->loadDataFromFile(inputFile, sourceFromFileSize);
if (sourceFromFileSize == 0) {
return OCLOC_INVALID_FILE;
}
if (inputFileLlvm || inputFileSpirV) {
// use the binary input "as is"
sourceCode.assign(sourceFromFile.get(), sourceFromFileSize);
} else {
// for text input, we also accept files used as runtime builtins
source = strstr((const char *)sourceFromFile.get(), "R\"===(");
sourceCode = (source != nullptr) ? getStringWithinDelimiters(sourceFromFile.get()) : sourceFromFile.get();
}
if ((inputFileSpirV == false) && (inputFileLlvm == false)) {
const auto fclInitializationResult = fclFacade->initialize(hwInfo);
if (fclInitializationResult != OCLOC_SUCCESS) {
argHelper->printf("Error! FCL initialization failure. Error code = %d\n", fclInitializationResult);
return fclInitializationResult;
}
preferredIntermediateRepresentation = fclFacade->getPreferredIntermediateRepresentation();
} else {
if (!isQuiet()) {
argHelper->printf("Compilation from IR - skipping loading of FCL\n");
}
preferredIntermediateRepresentation = IGC::CodeType::spirV;
}
const auto igcInitializationResult = igcFacade->initialize(hwInfo);
if (igcInitializationResult != OCLOC_SUCCESS) {
argHelper->printf("Error! IGC initialization failure. Error code = %d\n", igcInitializationResult);
return igcInitializationResult;
}
int retVal = OCLOC_SUCCESS;
if (isOnlySpirV()) {
retVal = buildIrBinary();
} else {
retVal = buildSourceCode();
}
generateElfBinary();
if (dumpFiles) {
writeOutAllFiles();
}
return retVal;
}
void OfflineCompiler::updateBuildLog(const char *pErrorString, const size_t errorStringSize) {
if (pErrorString != nullptr) {
std::string log(pErrorString, pErrorString + errorStringSize);
ConstStringRef errorString(log);
const bool warningFound = errorString.containsCaseInsensitive("warning");
if (!isQuiet() || !warningFound) {
if (buildLog.empty()) {
buildLog.assign(errorString.data());
} else {
buildLog.append("\n");
buildLog.append(errorString.data());
}
}
}
}
std::string &OfflineCompiler::getBuildLog() {
return buildLog;
}
const HardwareInfo *getHwInfoForDeprecatedAcronym(const std::string &deviceName) {
std::vector<PRODUCT_FAMILY> allSupportedProduct{ALL_SUPPORTED_PRODUCT_FAMILIES};
auto deviceNameLowered = deviceName;
std::transform(deviceNameLowered.begin(), deviceNameLowered.end(), deviceNameLowered.begin(), ::tolower);
for (const auto &product : allSupportedProduct) {
if (0 == strcmp(deviceNameLowered.c_str(), hardwarePrefix[product])) {
return hardwareInfoTable[product];
}
}
return nullptr;
}
int OfflineCompiler::initHardwareInfoForDeprecatedAcronyms(const std::string &deviceName, std::unique_ptr<NEO::CompilerProductHelper> &compilerProductHelper, std::unique_ptr<NEO::ReleaseHelper> &releaseHelper) {
auto foundHwInfo = getHwInfoForDeprecatedAcronym(deviceName);
if (nullptr == foundHwInfo) {
return OCLOC_INVALID_DEVICE;
}
hwInfo = *foundHwInfo;
if (revisionId != -1) {
hwInfo.platform.usRevId = revisionId;
}
compilerProductHelper = NEO::CompilerProductHelper::create(hwInfo.platform.eProductFamily);
auto defaultIpVersion = compilerProductHelper->getDefaultHwIpVersion();
auto productConfig = compilerProductHelper->matchRevisionIdWithProductConfig(defaultIpVersion, revisionId);
hwInfo.ipVersion = argHelper->productConfigHelper->isSupportedProductConfig(productConfig) ? productConfig : defaultIpVersion;
uint64_t config = hwInfoConfig ? hwInfoConfig : compilerProductHelper->getHwInfoConfig(hwInfo);
setHwInfoValuesFromConfig(config, hwInfo);
releaseHelper = NEO::ReleaseHelper::create(hwInfo.ipVersion);
hardwareInfoBaseSetup[hwInfo.platform.eProductFamily](&hwInfo, true, releaseHelper.get());
UNRECOVERABLE_IF(compilerProductHelper == nullptr);
productFamilyName = hardwarePrefix[hwInfo.platform.eProductFamily];
return OCLOC_SUCCESS;
}
bool OfflineCompiler::isArgumentDeviceId(const std::string &argument) const {
const char hexPrefixLength = 2;
return argument.substr(0, hexPrefixLength) == "0x" && std::all_of(argument.begin() + hexPrefixLength, argument.end(), (::isxdigit));
}
int OfflineCompiler::initHardwareInfoForProductConfig(std::string deviceName) {
uint32_t productConfig = AOT::UNKNOWN_ISA;
ProductConfigHelper::adjustDeviceName(deviceName);
if (isArgumentDeviceId(deviceName)) {
auto deviceID = static_cast<unsigned short>(std::stoi(deviceName, 0, 16));
productConfig = argHelper->getProductConfigAndSetHwInfoBasedOnDeviceAndRevId(hwInfo, deviceID, revisionId, compilerProductHelper, releaseHelper);
if (productConfig == AOT::UNKNOWN_ISA) {
return OCLOC_INVALID_DEVICE;
}
auto product = argHelper->productConfigHelper->getAcronymForProductConfig(productConfig);
argHelper->printf("Auto-detected target based on %s device id: %s\n", deviceName.c_str(), product.c_str());
} else if (revisionId == -1) {
productConfig = argHelper->productConfigHelper->getProductConfigFromDeviceName(deviceName);
if (!argHelper->setHwInfoForProductConfig(productConfig, hwInfo, compilerProductHelper, releaseHelper)) {
return OCLOC_INVALID_DEVICE;
}
} else {
return OCLOC_INVALID_DEVICE;
}
argHelper->setHwInfoForHwInfoConfig(hwInfo, hwInfoConfig, compilerProductHelper, releaseHelper);
deviceConfig = hwInfo.ipVersion.value;
productFamilyName = hardwarePrefix[hwInfo.platform.eProductFamily];
return OCLOC_SUCCESS;
}
int OfflineCompiler::initHardwareInfo(std::string deviceName) {
int retVal = OCLOC_INVALID_DEVICE;
if (deviceName.empty()) {
return retVal;
}
retVal = initHardwareInfoForProductConfig(deviceName);
if (retVal == OCLOC_SUCCESS) {
return retVal;
}
retVal = initHardwareInfoForDeprecatedAcronyms(deviceName, compilerProductHelper, releaseHelper);
if (retVal != OCLOC_SUCCESS) {
argHelper->printf("Could not determine device target: %s.\n", deviceName.c_str());
}
return retVal;
}
std::string OfflineCompiler::getStringWithinDelimiters(const std::string &src) {
size_t start = src.find("R\"===(");
size_t stop = src.find(")===\"");
DEBUG_BREAK_IF(std::string::npos == start);
DEBUG_BREAK_IF(std::string::npos == stop);
start += strlen("R\"===(");
size_t size = stop - start;
std::string dst(src, start, size + 1);
dst[size] = '\0'; // put null char at the end
return dst;
}
int OfflineCompiler::initialize(size_t numArgs, const std::vector<std::string> &allArgs, bool dumpFiles) {
this->dumpFiles = dumpFiles;
int retVal = OCLOC_SUCCESS;
this->pBuildInfo = std::make_unique<BuildInfo>();
retVal = parseCommandLine(numArgs, allArgs);
if (showHelp) {
printUsage();
return retVal;
} else if (retVal != OCLOC_SUCCESS) {
return retVal;
}
if (options.empty()) {
// try to read options from file if not provided by commandline
size_t extStart = inputFile.find_last_of('.');
if (extStart != std::string::npos) {
std::string oclocOptionsFileName = inputFile.substr(0, extStart);
oclocOptionsFileName.append("_ocloc_options.txt");
std::string oclocOptionsFromFile;
bool oclocOptionsRead = readOptionsFromFile(oclocOptionsFromFile, oclocOptionsFileName, argHelper);
if (oclocOptionsRead) {
if (!isQuiet()) {
argHelper->printf("Building with ocloc options:\n%s\n", oclocOptionsFromFile.c_str());
}
std::istringstream iss(allArgs[0] + " " + oclocOptionsFromFile);
std::vector<std::string> tokens{
std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
retVal = parseCommandLine(tokens.size(), tokens);
if (retVal != OCLOC_SUCCESS) {
argHelper->printf("Failed with ocloc options from file:\n%s\n", oclocOptionsFromFile.c_str());
return retVal;
}
}
std::string optionsFileName = inputFile.substr(0, extStart);
optionsFileName.append("_options.txt");
bool optionsRead = readOptionsFromFile(options, optionsFileName, argHelper);
if (optionsRead) {
optionsReadFromFile = std::string(options);
}
if (optionsRead && !isQuiet()) {
argHelper->printf("Building with options:\n%s\n", options.c_str());
}
std::string internalOptionsFileName = inputFile.substr(0, extStart);
internalOptionsFileName.append("_internal_options.txt");
std::string internalOptionsFromFile;
bool internalOptionsRead = readOptionsFromFile(internalOptionsFromFile, internalOptionsFileName, argHelper);
if (internalOptionsRead) {
internalOptionsReadFromFile = std::string(internalOptionsFromFile);
}
if (internalOptionsRead && !isQuiet()) {
argHelper->printf("Building with internal options:\n%s\n", internalOptionsFromFile.c_str());
}
CompilerOptions::concatenateAppend(internalOptions, internalOptionsFromFile);
}
}
retVal = deviceName.empty() ? OCLOC_SUCCESS : initHardwareInfo(deviceName.c_str());
if (retVal != OCLOC_SUCCESS) {
argHelper->printf("Error: Cannot get HW Info for device %s.\n", deviceName.c_str());
return retVal;
}
if (formatToEnforce.empty() &&
compilerProductHelper &&
compilerProductHelper->oclocEnforceZebinFormat()) {
formatToEnforce = "zebin";
}
if (!formatToEnforce.empty()) {
enforceFormat(formatToEnforce);
}
if (CompilerOptions::contains(options, CompilerOptions::generateDebugInfo.str())) {
if (false == inputFileSpirV && false == CompilerOptions::contains(options, CompilerOptions::generateSourcePath) && false == CompilerOptions::contains(options, CompilerOptions::useCMCompiler)) {
auto sourcePathStringOption = CompilerOptions::generateSourcePath.str();
sourcePathStringOption.append(" ");
sourcePathStringOption.append(CompilerOptions::wrapInQuotes(inputFile));
options = CompilerOptions::concatenate(options, sourcePathStringOption);
}
}
if (deviceName.empty()) {
std::string emptyDeviceOptions = "-ocl-version=300 -cl-ext=-all,+cl_khr_3d_image_writes,"
"+__opencl_c_3d_image_writes,+__opencl_c_images";
internalOptions = CompilerOptions::concatenate(emptyDeviceOptions, internalOptions);
CompilerOptions::concatenateAppend(internalOptions, CompilerOptions::enableImageSupport);
} else {
appendExtensionsToInternalOptions(hwInfo, options, internalOptions);
appendExtraInternalOptions(internalOptions);
}
parseDebugSettings();
if (allowCaching) {
auto cacheConfig = NEO::getDefaultCompilerCacheConfig();
if (cacheConfig.cacheDir.empty() && !cacheDir.empty()) {
cacheConfig.cacheDir = cacheDir;
}
cache = std::make_unique<CompilerCache>(cacheConfig);
createDir(cacheConfig.cacheDir);
}
return retVal;
}
int OfflineCompiler::parseCommandLine(size_t numArgs, const std::vector<std::string> &argv) {
int retVal = OCLOC_SUCCESS;
bool compile32 = false;
bool compile64 = false;
std::set<std::string> deviceAcronymsFromDeviceOptions;
for (uint32_t argIndex = 1; argIndex < argv.size(); argIndex++) {
const auto &currArg = argv[argIndex];
const bool hasMoreArgs = (argIndex + 1 < numArgs);
const bool hasAtLeast2MoreArgs = (argIndex + 2 < numArgs);
if ("compile" == currArg) {
// skip it
} else if (("-file" == currArg) && hasMoreArgs) {
inputFile = argv[argIndex + 1];
argIndex++;
} else if (("-output" == currArg) && hasMoreArgs) {