-
Notifications
You must be signed in to change notification settings - Fork 169
/
Copy pathclang_tb.cpp
2035 lines (1715 loc) · 69.2 KB
/
clang_tb.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
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2023 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "../headers/clang_tb.h"
#include "../headers/common_clang.h"
#include "../headers/RegistryAccess.h"
#include "../headers/resource.h"
#include "common/LLVMWarningsPush.hpp"
#include "llvm/Config/llvm-config.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "common/LLVMWarningsPop.hpp"
#include "iStdLib/utility.h"
#include "secure_mem.h"
#include "secure_string.h"
#include "AdaptorCommon/customApi.hpp"
#include <mutex>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include "3d/common/iStdLib/File.h"
#include "Probe/Assertion.h"
#if defined( _DEBUG ) || defined( _INTERNAL )
#define IGC_DEBUG_VARIABLES
#endif
#if defined(IGC_DEBUG_VARIABLES)
// Code for reading IGC regkeys "ShaderDumpEnable", "DumpToCurrentDir", "ShaderDumpPidDisable".
// Code for shader dump directory name scheme.
// Code is copied from IGC project. This duplication is undesirable in the long term.
// IGC is expected to put this code in single file, without unncessary llvm (and other dependencies).
// Then FCL will just include this single file to avoid code duplication and maintainability issues.
#if defined(_WIN32 )|| defined( _WIN64 )
#include <direct.h>
#include <process.h>
#endif
#if defined __linux__
#include "iStdLib/File.h"
#endif
namespace {
std::string g_shaderOutputFolder;
}
namespace FCL
{
namespace Debug
{
static std::mutex stream_mutex;
void DumpLock()
{
stream_mutex.lock();
}
void DumpUnlock()
{
stream_mutex.unlock();
}
}
#define IGC_REGISTRY_KEY "SOFTWARE\\INTEL\\IGFX\\IGC"
typedef char FCLdebugString[256];
int32_t FCLShDumpEn = 0;
int32_t FCLDumpToCurrDir = 0;
int32_t FCLDumpToCustomDir = 0;
int32_t FCLShDumpPidDis = 0;
int32_t FCLEnableKernelNamesBasedHash = 0;
int32_t FCLEnvKeysRead = 0;
std::string RegKeysFlagsFromOptions = "";
/*****************************************************************************\
FCLReadIGCEnv
\*****************************************************************************/
static bool FCLReadIGCEnv(
const char* pName,
void* pValue,
unsigned int size)
{
if (pName != NULL)
{
const char nameTag[] = "IGC_";
std::string pKey = std::string(nameTag) + std::string(pName);
const char* envVal = getenv(pKey.c_str());
if (envVal != NULL)
{
if (size >= sizeof(unsigned int))
{
// Try integer conversion
char* pStopped = nullptr;
unsigned int *puVal = (unsigned int *)pValue;
*puVal = strtoul(envVal, &pStopped, 0);
if (pStopped == envVal + strlen(envVal))
{
return true;
}
}
// Just return the string
strncpy_s((char*)pValue, size, envVal, size);
return true;
}
}
return false;
}
/*****************************************************************************\
FCLReadIGCRegistry
\*****************************************************************************/
static bool FCLReadIGCRegistry(
const char* pName,
void* pValue,
unsigned int size)
{
// All platforms can retrieve settings from environment
if (FCLReadIGCEnv(pName, pValue, size))
{
return true;
}
#if defined _WIN32
LONG success = ERROR_SUCCESS;
HKEY uscKey;
success = RegOpenKeyExA(
HKEY_LOCAL_MACHINE,
IGC_REGISTRY_KEY,
0,
KEY_READ,
&uscKey);
if (ERROR_SUCCESS == success)
{
DWORD dwSize = size;
success = RegQueryValueExA(
uscKey,
pName,
NULL,
NULL,
(LPBYTE)pValue,
&dwSize);
RegCloseKey(uscKey);
}
return (ERROR_SUCCESS == success);
#endif // defined _WIN32
return false;
}
bool getFCLIGCBinaryKey(const char *keyName)
{
FCLdebugString value = { 0 };
bool isSet = FCLReadIGCRegistry(
keyName,
&value,
sizeof(value));
isSet = isSet;
return(value[0] != 0);
}
void FCLReadKeysFromEnv()
{
if (!FCLEnvKeysRead)
{
FCLShDumpEn = getFCLIGCBinaryKey("ShaderDumpEnable") || (RegKeysFlagsFromOptions.find("ShaderDumpEnable=1") != std::string::npos);
FCLDumpToCurrDir = getFCLIGCBinaryKey("DumpToCurrentDir") || (RegKeysFlagsFromOptions.find("DumpToCurrentDir=1") != std::string::npos);
FCLDumpToCustomDir = getFCLIGCBinaryKey("DumpToCustomDir") || (RegKeysFlagsFromOptions.find("DumpToCustomDir=") != std::string::npos);
FCLShDumpPidDis = getFCLIGCBinaryKey("ShaderDumpPidDisable") || (RegKeysFlagsFromOptions.find("ShaderDumpPidDisable=1") != std::string::npos);
FCLEnableKernelNamesBasedHash = getFCLIGCBinaryKey("EnableKernelNamesBasedHash") || (RegKeysFlagsFromOptions.find("EnableKernelNamesBasedHash=1") != std::string::npos);
FCLEnvKeysRead = 1;
}
}
bool GetFCLShaderDumpEnable()
{
FCLReadKeysFromEnv();
return FCLShDumpEn;
}
bool GetFCLShaderDumpPidDisable()
{
FCLReadKeysFromEnv();
return FCLShDumpPidDis;
}
bool GetFCLDumpToCurrentDir()
{
FCLReadKeysFromEnv();
return FCLDumpToCurrDir;
}
bool GetFCLDumpToCustomDir()
{
FCLReadKeysFromEnv();
return FCLDumpToCustomDir;
}
bool GetFCLEnableKernelNamesBasedHash()
{
FCLReadKeysFromEnv();
return FCLEnableKernelNamesBasedHash;
}
OutputFolderName GetBaseIGCOutputFolder()
{
#if defined(IGC_DEBUG_VARIABLES)
static std::mutex m;
std::lock_guard<std::mutex> lck(m);
static std::string IGCBaseFolder;
if (IGCBaseFolder != "")
{
return IGCBaseFolder.c_str();
}
# if defined(_WIN64) || defined(_WIN32)
if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCurrentDir) && !FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
bool needMkdir = 1;
char dumpPath[256];
sprintf_s(dumpPath, "c:\\Intel\\IGC\\");
if (GetFileAttributesA(dumpPath) != FILE_ATTRIBUTE_DIRECTORY && needMkdir)
{
_mkdir(dumpPath);
}
// Make sure we can write in the dump folder as the app may be sandboxed
if (needMkdir)
{
int tmp_id = _getpid();
std::string testFilename = std::string(dumpPath) + "testfile" + std::to_string(tmp_id);
HANDLE testFile =
CreateFileA(testFilename.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, NULL);
if (testFile == INVALID_HANDLE_VALUE)
{
char temppath[256];
if (GetTempPathA(sizeof(temppath), temppath) != 0)
{
sprintf_s(dumpPath, "%sIGC\\", temppath);
}
}
else
{
CloseHandle(testFile);
}
}
if (GetFileAttributesA(dumpPath) != FILE_ATTRIBUTE_DIRECTORY && needMkdir)
{
_mkdir(dumpPath);
}
IGCBaseFolder = dumpPath;
}
else if (FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
std::string dumpPath = "c:\\Intel\\IGC\\"; // default if something goes wrong
char custom_dir[256];
std::string DumpToCustomDirFlagNameWithEqual = "DumpToCustomDir=";
std::size_t found = RegKeysFlagsFromOptions.find(DumpToCustomDirFlagNameWithEqual);
FCLReadIGCRegistry("DumpToCustomDir", custom_dir, sizeof(custom_dir));
if (strlen(custom_dir) > 0 && (found == std::string::npos))
{
dumpPath = custom_dir;
}
else
{
std::size_t foundComma = RegKeysFlagsFromOptions.find(',', found);
if (foundComma != std::string::npos)
{
std::string token = RegKeysFlagsFromOptions.substr(found + DumpToCustomDirFlagNameWithEqual.size(), foundComma - (found + DumpToCustomDirFlagNameWithEqual.size()));
if (token.size() > 0)
{
dumpPath = token;
}
}
}
char pathBuf[256];
iSTD::CreateAppOutputDir(pathBuf, 256, dumpPath.c_str(), false, false, false);
IGCBaseFolder = pathBuf;
}
#elif defined __linux__
if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
IGCBaseFolder = "/tmp/IntelIGC/";
}
else
{
std::string dumpPath = "/tmp/IntelIGC/"; // default if something goes wrong
const size_t maxLen = 255;
char custom_dir[ maxLen + 1] = { 0 };
std::string DumpToCustomDirFlagNameWithEqual = "DumpToCustomDir=";
std::size_t found = RegKeysFlagsFromOptions.find(DumpToCustomDirFlagNameWithEqual);
FCLReadIGCRegistry("DumpToCustomDir", custom_dir, maxLen);
if (strlen(custom_dir) > 0 && (found == std::string::npos))
{
IGC_ASSERT_MESSAGE(strlen(custom_dir) < maxLen, "custom_dir path too long");
dumpPath = custom_dir;
dumpPath += "/";
}
else
{
std::size_t foundComma = RegKeysFlagsFromOptions.find(',', found);
if (foundComma != std::string::npos)
{
std::string token = RegKeysFlagsFromOptions.substr(found + DumpToCustomDirFlagNameWithEqual.size(), foundComma - (found + DumpToCustomDirFlagNameWithEqual.size()));
if (token.size() > 0)
{
dumpPath = token;
}
}
}
char pathBuf[256];
iSTD::CreateAppOutputDir(pathBuf, 256, dumpPath.c_str(), false, false, false);
IGCBaseFolder = pathBuf;
}
#endif
return IGCBaseFolder.c_str();
#else
return "";
#endif
}
OutputFolderName GetShaderOutputFolder()
{
#if defined(IGC_DEBUG_VARIABLES)
static std::mutex m;
std::lock_guard<std::mutex> lck(m);
if (g_shaderOutputFolder != "")
{
return g_shaderOutputFolder.c_str();
}
# if defined(_WIN64) || defined(_WIN32)
if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCurrentDir) && !FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
char dumpPath[256];
sprintf_s(dumpPath, "%s", GetBaseIGCOutputFolder());
char appPath[MAX_PATH] = { 0 };
// check a process id and make an adequate directory for it:
if (::GetModuleFileNameA(NULL, appPath, sizeof(appPath) - 1))
{
std::string appPathStr = std::string(appPath);
int pos = appPathStr.find_last_of("\\") + 1;
if (FCL_IGC_IS_FLAG_ENABLED(ShaderDumpPidDisable))
{
sprintf_s(dumpPath, "%s%s\\", dumpPath, appPathStr.substr(pos, MAX_PATH).c_str());
}
else
{
sprintf_s(dumpPath, "%s%s_%d\\", dumpPath, appPathStr.substr(pos, MAX_PATH).c_str(), _getpid());
}
}
else
{
sprintf_s(dumpPath, "%sunknownProcess_%d\\", dumpPath, _getpid());
}
if (GetFileAttributesA(dumpPath) != FILE_ATTRIBUTE_DIRECTORY)
{
_mkdir(dumpPath);
}
g_shaderOutputFolder = dumpPath;
}
else if (FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
char pathBuf[256];
iSTD::CreateAppOutputDir(pathBuf, 256, GetBaseIGCOutputFolder(), false, true, !FCL_IGC_IS_FLAG_ENABLED(ShaderDumpPidDisable));
g_shaderOutputFolder = pathBuf;
}
#elif defined __linux__
if (!FCL_IGC_IS_FLAG_ENABLED(DumpToCurrentDir) && g_shaderOutputFolder == "" && !FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
bool needMkdir = true;
char path[MAX_PATH] = { 0 };
bool pidEnabled = !FCL_IGC_IS_FLAG_ENABLED(ShaderDumpPidDisable);
if (needMkdir)
{
iSTD::CreateAppOutputDir(
path,
MAX_PATH,
GetBaseIGCOutputFolder(),
false,
true,
pidEnabled);
}
g_shaderOutputFolder = path;
}
else if (FCL_IGC_IS_FLAG_ENABLED(DumpToCustomDir))
{
char pathBuf[256];
iSTD::CreateAppOutputDir(pathBuf, 256, GetBaseIGCOutputFolder(), false, false, false);
g_shaderOutputFolder = pathBuf;
}
#endif
return g_shaderOutputFolder.c_str();
#else
return "";
#endif
}
} // namespace FCL
/// pk this ends here
#endif
#ifndef WIN32
#include <dlfcn.h>
#include <stdexcept>
#endif
#if defined(_WIN32)
#include <Windows.h>
#include "DriverStore.h"
#endif
using namespace llvm;
using namespace std;
// ElfReader related typedefs
using namespace CLElfLib;
void ElfReaderDP(CElfReader* pElfReader)
{
if (pElfReader)
CElfReader::Delete(pElfReader);
}
typedef unique_ptr<CElfReader, decltype(&ElfReaderDP)> CElfReaderPtr;
// ClangFE related typedefs
using namespace Intel::OpenCL::ClangFE;
void ReleaseDP(IOCLFEBinaryResult* pT)
{
if (pT)
pT->Release();
}
typedef unique_ptr<IOCLFEBinaryResult, decltype(&ReleaseDP) > IOCLFEBinaryResultPtr;
namespace TC
{
constexpr bool is64bit = sizeof(void*) == sizeof(uint64_t);
//Misc utility functions used only in the current module
namespace Utils
{
// Replace \0 in input string with \n. This works around an issue in
// Clang where the error message is not generated for inputs that contain
// a non-ending \0
char* NormalizeString(char* input, uint32_t size)
{
for (uint32_t i = 0; i < size; i++)
{
if (input[i] == '\0')
{
input[i] = '\n';
}
}
input[size - 1] = '\0';
return input;
}
//Translates the ClangFE results to STB Output results
void FillOutputArgs(IOCLFEBinaryResult* pFEBinaryResult, STB_TranslateOutputArgs* pOutputArgs, std::string& exceptString)
{
// fill the result structure
pOutputArgs->ErrorStringSize = (uint32_t)strlen(pFEBinaryResult->GetErrorLog());
if (pOutputArgs->ErrorStringSize > 0)
{
TC::CClangTranslationBlock::SetErrorString(pFEBinaryResult->GetErrorLog(), pOutputArgs);
}
else
{
pOutputArgs->pErrorString = NULL;
}
pOutputArgs->OutputSize = (uint32_t)pFEBinaryResult->GetIRSize();
// we have to copy the result due to unfortunate design of STB_TranslateOutputArg interface
// the better design would be for TranslateXXX calls to be responsible to allocate the outputArgs
// interface entirely, and the client to be responsible to call outputArgs->release() to free it.
// This way the implementation of TranslateXXX could be free to return inherited from outputArgs
// class which could glue the outputArgs with other internal interfaces (like the one returned from
// ::Compile method for example) without any buffer copy
if (pOutputArgs->OutputSize > 0)
{
pOutputArgs->pOutput = (char*)malloc(pFEBinaryResult->GetIRSize());
if (!pOutputArgs->pOutput)
{
//throw std::bad_alloc();
exceptString = "bad_alloc";
return;
}
memcpy_s(pOutputArgs->pOutput,
pFEBinaryResult->GetIRSize(),
pFEBinaryResult->GetIR(),
pFEBinaryResult->GetIRSize());
}
}
}//namespace Utils
struct OCLVersionNumberMapping
{
const char* version;
unsigned int number;
};
// Input parameters to the 3 function
struct TranslateClangArgs
{
TranslateClangArgs() :
pszProgramSource(NULL),
pPCHBuffer(NULL),
uiPCHBufferSize(0),
b32bit(!is64bit)
{
}
// A pointer to main program's source (assumed one nullterminated string)
const char* pszProgramSource;
// array of additional input headers to be passed in memory
std::vector<const char*> inputHeaders;
// array of input headers names corresponding to pInputHeaders
std::vector<const char*> inputHeadersNames;
// optional pointer to the pch buffer
const char* pPCHBuffer;
// size of the pch buffer
size_t uiPCHBufferSize;
// OpenCL application supplied options
std::string options;
// optional extra options string usually supplied by runtime
std::string optionsEx;
// requested OCL version
std::string oclVersion;
// build for 32 bit
bool b32bit;
};
// Initialize static mutex object to be shared with all threads
//llvm::sys::Mutex CClangTranslationBlock::m_Mutex(/* recursive = */ true);
/*****************************************************************************\
Function:
CClangTranslationBlock::Create
Description:
Input:
Output:
\*****************************************************************************/
bool CClangTranslationBlock::Create(
const STB_CreateArgs* pCreateArgs,
STB_TranslateOutputArgs* pOutputArgs,
CClangTranslationBlock* &pTranslationBlock)
{
bool success = true;
pTranslationBlock = new CClangTranslationBlock();
if (pTranslationBlock)
{
success = pTranslationBlock->Initialize(pCreateArgs);
#ifdef _WIN32
if (true == success)
{
// Both Win32 and Win64
// load dependency only on RS
// Load the Common Clang library
CCModuleStruct &CCModule = pTranslationBlock->m_CCModule;
if (GetWinVer() >= OS_WIN_RS)
{
CCModule.pModule = LoadDependency(CCModule.pModuleName);
}
else
{
CCModule.pModule = LoadLibraryA(CCModule.pModuleName);
}
if (NULL != CCModule.pModule)
{
CCModule.pCompile = (CCModuleStruct::PFcnCCCompile)GetProcAddress((HMODULE)CCModule.pModule, "Compile");
success = CCModule.pCompile != NULL;
}
else
{
SetErrorString("Error: Opencl-clang library not found.", pOutputArgs);
success = false;
}
}
#endif
if (!success)
{
CClangTranslationBlock::Delete(pTranslationBlock);
}
}
else
{
success = false;
}
return success;
}
/*****************************************************************************\
Function:
CClangTranslationBlock::Delete
Description:
Input:
Output:
\*****************************************************************************/
void CClangTranslationBlock::Delete(
CClangTranslationBlock* &pTranslationBlock)
{
#ifdef _WIN32
// Unload the Common Clang library
if (pTranslationBlock->m_CCModule.pModule) {
// Both Win32 and Win64
FreeLibrary((HMODULE)pTranslationBlock->m_CCModule.pModule);
}
#endif
delete pTranslationBlock;
pTranslationBlock = NULL;
}
/*****************************************************************************\
Function:
CClangTranslationBlock::SetErrorString
Description:
Given an error string, mallocs memory for the string and sets the
appropriate STB_TranslateOutputArgs fields.
Input:
Output:
\*****************************************************************************/
void CClangTranslationBlock::SetErrorString(const char *pErrorString, STB_TranslateOutputArgs* pOutputArgs)
{
IGC_ASSERT(pErrorString != NULL);
IGC_ASSERT(pOutputArgs != NULL);
size_t strSize = strlen(pErrorString) + 1;
pOutputArgs->ErrorStringSize = strSize;
pOutputArgs->pErrorString = (char*)malloc(strSize);
memcpy_s(pOutputArgs->pErrorString, strSize - 1, pErrorString, strSize - 1);
pOutputArgs->pErrorString[strSize - 1] = '\0';
}
/*****************************************************************************\
Function:
CClangTranslationBlock::GetOclApiVersion
Description:
Parses the given internal options and return the OCL Version to be used
for Clang compilation. If OCL version was not specified in internal options
returns the default OCL version for the device
Input:
Output:
\*****************************************************************************/
std::string CClangTranslationBlock::GetOclApiVersion(const char* pInternalOptions) const
{
static const char* OCL_VERSION_OPT = "-ocl-version=";
static size_t OCL_VERSION_OPT_SIZE = strlen(OCL_VERSION_OPT);
if (pInternalOptions)
{
const char* pszOpt = strstr(pInternalOptions, OCL_VERSION_OPT);
if (NULL != pszOpt)
{
// we are in control of internal option - assertion test the validity
IGC_ASSERT(strlen(pszOpt + OCL_VERSION_OPT_SIZE) >= 3);
return std::string(pszOpt + OCL_VERSION_OPT_SIZE, 3);
}
}
return m_OCL_Ver;
}
/*****************************************************************************\
Function:
EnforceOCLCVersion
Description:
In case the '-force-cl-std' options was specified, check that the user
requested OCL C version isn't higher than the supported OCL version.
exception is thrown otherwise
Input:
Output:
\*****************************************************************************/
unsigned int GetOclCVersionFromOptions(const char* pOptions, const char* pInternalOptions,
const std::string& oclVersion /*OCL runtime API version*/,
std::string& exceptString)
{
exceptString.clear();
if (pOptions == nullptr) {
return 0; // no options (i.e. no options from client application)
}
std::string optName = "-cl-std="; // opt that we are looking for
unsigned int device_version = atoi(oclVersion.c_str());
const char* optSubstring = strstr(pOptions, optName.c_str());
if (optSubstring == nullptr) {
return 0; // -cl-std not specified
}
bool validate = true;
if ((pInternalOptions != nullptr) && (strstr(pInternalOptions, "-force-cl-std") != nullptr)) {
// we're forcing the -cl-std version internally, so no need for validating it
validate = false;
}
const char * optValue = optSubstring + optName.size();
const char * end = optValue + strlen(optValue);
std::string_view opt(optValue, end - optValue);
// parse
unsigned int retVersion = 0;
if (opt.find("CLC++") == 0) {
if (opt == "CLC++" || opt == "CLC++1.0") {
retVersion = 200;
}
else if (opt == "CLC++2021") {
retVersion = 300;
}
else {
const std::string invalidFormatMessage = "Invalid format of -cl-std option, expected -cl-std=CLC++, -cl-std=CLC++1.0, or -cl-std=CLC++2021";
}
}
else
{
const std::string invalidFormatMessage = "Invalid format of -cl-std option, expected -cl-std=CLMAJOR.MINOR";
auto isNumeric = [](char v) { return (v >= '0') && (v <= '9'); };
if (false == ((end - optValue >= 5) && (optValue[0] == 'C') && (optValue[1] == 'L') && isNumeric(optValue[2])
&& (optValue[3] == '.') && isNumeric(optValue[4])
)
) {
exceptString = invalidFormatMessage;
return 0;
}
// subverions
if ((end - optValue >= 7) && (optValue[5] != ' ')) {
if ((optValue[5] == '.') || isNumeric(optValue[6])) {
retVersion += optValue[6] - '0';
}
else if (isNumeric(optValue[5])) {
retVersion += optValue[5] - '0';
}
else {
exceptString = invalidFormatMessage;
return 0;
}
}
retVersion += 100 * (optValue[2] - '0') + 10 * (optValue[4] - '0');
}
if (validate == false) {
return retVersion;
}
if (device_version < retVersion) {
exceptString = "-cl-std OpenCLC version greater than OpenCL (API) version";
return 0;
}
return retVersion;
}
/*****************************************************************************\
Function:
IsBuildingFor32bit
Description:
Return true if clang should generate 32bit code
Input:
Output:
\*****************************************************************************/
bool IsBuildingFor32bit(const char* pInternalOptions)
{
// Detect pointer size from internal option string. Default to using the
// architecture type if the string is unavailable.
if (pInternalOptions != NULL)
{
if (strstr(pInternalOptions, "-m32") != NULL)
{
return true;
}
if (strstr(pInternalOptions, "-m64") != NULL)
{
return false;
}
}
return !is64bit;
}
/*****************************************************************************\
Function:
AreVMETypesDefined
Description:
Returns true if CommonClang used on current OS has VME types defined.
\*****************************************************************************/
bool AreVMETypesDefined()
{
#ifdef VME_TYPES_DEFINED
#if VME_TYPES_DEFINED
return true;
#else
return false;
#endif
#endif
return true;
}
/*****************************************************************************\
Function:
CClangTranslationBlock::GetTranslateClangArgs
Description:
Prepares the arguments for the TranslateClang method for the given text input
Input:
Output:
\*****************************************************************************/
void CClangTranslationBlock::GetTranslateClangArgs(char* pInput,
uint32_t uiInputSize,
const char* pOptions,
const char* pInternalOptions,
TranslateClangArgs* pClangArgs,
std::string& exceptString)
{
pClangArgs->pszProgramSource = Utils::NormalizeString(pInput, uiInputSize);
pClangArgs->pPCHBuffer = NULL;
pClangArgs->uiPCHBufferSize = 0;
pClangArgs->oclVersion = GetOclApiVersion(pInternalOptions);
pClangArgs->b32bit = IsBuildingFor32bit(pInternalOptions);
if (pOptions)
{
pClangArgs->options.assign(pOptions);
}
#if defined(IGC_DEBUG_VARIABLES)
char debugOptions[1024];
if (FCL::FCLReadIGCRegistry("ExtraOCLOptions", debugOptions, sizeof(debugOptions)))
{
if (!pClangArgs->options.empty())
pClangArgs->options += ' ';
pClangArgs->options += debugOptions;
}
#endif
GetOclCVersionFromOptions(pOptions, pInternalOptions, pClangArgs->oclVersion, exceptString);
EnsureProperPCH(pClangArgs, pInternalOptions, exceptString);
}
/*****************************************************************************\
Function:
CClangTranslationBlock::GetTranslateClangArgs
Description:
Parses the given ELF binary to prepare the arguments for the TranslateClang
Input:
Output:
\*****************************************************************************/
void CClangTranslationBlock::GetTranslateClangArgs(CElfReader* pElfReader,
const char* pOptions,
const char* pInternalOptions,
TranslateClangArgs* pClangArgs,
std::string& exceptString)
{
IGC_ASSERT_MESSAGE(pElfReader, "pElfReader is invalid");
const SElf64Header* pHeader = pElfReader->GetElfHeader();
IGC_ASSERT_MESSAGE(pHeader->Type == EH_TYPE_OPENCL_SOURCE, "OPENCL_SOURCE elf type is expected");
// First section should be an OpenCL source code
const SElf64SectionHeader* pSectionHeader = pElfReader->GetSectionHeader(1);
IGC_ASSERT_MESSAGE(NULL != pSectionHeader, "pSectionHeader cannot be NULL");
if (pSectionHeader->Type == SH_TYPE_OPENCL_SOURCE)
{
char *pData = NULL;
size_t uiDataSize = 0;
pElfReader->GetSectionData(1, pData, uiDataSize);
if (pData != NULL)
{
IGC_ASSERT_MESSAGE(pData[uiDataSize - 1] == '\0', "Program source is not null terminated");
pClangArgs->pszProgramSource = pData;
}
}
// Other sections could be runtime supplied header files
for (unsigned i = 2; i < pHeader->NumSectionHeaderEntries; ++i)
{
const SElf64SectionHeader* pSectionHeader = pElfReader->GetSectionHeader(i);
if ((pSectionHeader != NULL) && (pSectionHeader->Type == SH_TYPE_OPENCL_HEADER))
{
char* pData = NULL;
size_t uiDataSize = 0;
pElfReader->GetSectionData(i, pData, uiDataSize);
if (pData != NULL)
{
IGC_ASSERT_MESSAGE(pData[uiDataSize - 1] == '\0', "Header source is not null terminated");
pClangArgs->inputHeaders.push_back(pData);
pClangArgs->inputHeadersNames.push_back(pElfReader->GetSectionName(i));
}
}
}
if (pOptions)
{
pClangArgs->options.assign(pOptions);
}
pClangArgs->oclVersion = GetOclApiVersion(pInternalOptions);
pClangArgs->b32bit = IsBuildingFor32bit(pInternalOptions);
EnsureProperPCH(pClangArgs, pInternalOptions, exceptString);
}
std::string FormatExtensionsString(const std::vector<std::string> &extensions)