-
Notifications
You must be signed in to change notification settings - Fork 700
/
SYCL.cpp
1621 lines (1519 loc) · 67.4 KB
/
SYCL.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
//===--- SYCL.cpp - SYCL Tool and ToolChain Implementations -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "SYCL.h"
#include "CommonArgs.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/InputInfo.h"
#include "clang/Driver/Options.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#include <sstream>
using namespace clang::driver;
using namespace clang::driver::toolchains;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;
SYCLInstallationDetector::SYCLInstallationDetector(const Driver &D)
: D(D), InstallationCandidates() {
InstallationCandidates.emplace_back(D.Dir + "/..");
}
void SYCLInstallationDetector::getSYCLDeviceLibPath(
llvm::SmallVector<llvm::SmallString<128>, 4> &DeviceLibPaths) const {
for (const auto &IC : InstallationCandidates) {
llvm::SmallString<128> InstallLibPath(IC.str());
InstallLibPath.append("/lib");
DeviceLibPaths.emplace_back(InstallLibPath);
}
DeviceLibPaths.emplace_back(D.SysRoot + "/lib");
}
void SYCLInstallationDetector::print(llvm::raw_ostream &OS) const {
if (!InstallationCandidates.size())
return;
OS << "SYCL Installation Candidates: \n";
for (const auto &IC : InstallationCandidates) {
OS << IC << "\n";
}
}
static void addFPGATimingDiagnostic(std::unique_ptr<Command> &Cmd,
Compilation &C) {
const char *Msg = C.getArgs().MakeArgString(
"The FPGA image generated during this compile contains timing violations "
"and may produce functional errors if used. Refer to the Intel oneAPI "
"DPC++ FPGA Optimization Guide section on Timing Failures for more "
"information.");
Cmd->addDiagForErrorCode(/*ErrorCode*/ 42, Msg);
Cmd->addExitForErrorCode(/*ErrorCode*/ 42, false);
}
void SYCL::constructLLVMForeachCommand(Compilation &C, const JobAction &JA,
std::unique_ptr<Command> InputCommand,
const InputInfoList &InputFiles,
const InputInfo &Output, const Tool *T,
StringRef Increment, StringRef Ext,
StringRef ParallelJobs) {
// Construct llvm-foreach command.
// The llvm-foreach command looks like this:
// llvm-foreach --in-file-list=a.list --in-replace='{}' -- echo '{}'
ArgStringList ForeachArgs;
std::string OutputFileName(T->getToolChain().getInputFilename(Output));
ForeachArgs.push_back(C.getArgs().MakeArgString("--out-ext=" + Ext));
for (auto &I : InputFiles) {
std::string Filename(T->getToolChain().getInputFilename(I));
ForeachArgs.push_back(
C.getArgs().MakeArgString("--in-file-list=" + Filename));
ForeachArgs.push_back(
C.getArgs().MakeArgString("--in-replace=" + Filename));
}
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-file-list=" + OutputFileName));
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-replace=" + OutputFileName));
if (!Increment.empty())
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-increment=" + Increment));
if (!ParallelJobs.empty())
ForeachArgs.push_back(C.getArgs().MakeArgString("--jobs=" + ParallelJobs));
if (C.getDriver().isSaveTempsEnabled()) {
SmallString<128> OutputDirName;
if (C.getDriver().isSaveTempsObj()) {
OutputDirName =
T->getToolChain().GetFilePath(OutputFileName.c_str()).c_str();
llvm::sys::path::remove_filename(OutputDirName);
}
// Use the current dir if the `GetFilePath` returned en empty string, which
// is the case when the `OutputFileName` does not contain any directory
// information, or if in CWD mode. This is necessary for `llvm-foreach`, as
// it would disregard the parameter without it. Otherwise append separator.
if (OutputDirName.empty())
llvm::sys::path::native(OutputDirName = "./");
else
OutputDirName.append(llvm::sys::path::get_separator());
ForeachArgs.push_back(
C.getArgs().MakeArgString("--out-dir=" + OutputDirName));
}
// If fsycl-dump-device-code is passed, put the PTX files
// into the path provided in fsycl-dump-device-code.
if (T->getToolChain().getTriple().isNVPTX() &&
C.getDriver().isDumpDeviceCodeEnabled() && Ext.equals("s")) {
SmallString<128> OutputDir;
Arg *DumpDeviceCodeArg =
C.getArgs().getLastArg(options::OPT_fsycl_dump_device_code_EQ);
OutputDir = (DumpDeviceCodeArg ? DumpDeviceCodeArg->getValue() : "");
// If the output directory path is empty, put the PTX files in the
// current directory.
if (OutputDir.empty())
llvm::sys::path::native(OutputDir = "./");
else
OutputDir.append(llvm::sys::path::get_separator());
ForeachArgs.push_back(C.getArgs().MakeArgString("--out-dir=" + OutputDir));
}
ForeachArgs.push_back(C.getArgs().MakeArgString("--"));
ForeachArgs.push_back(
C.getArgs().MakeArgString(InputCommand->getExecutable()));
for (auto &Arg : InputCommand->getArguments())
ForeachArgs.push_back(Arg);
SmallString<128> ForeachPath(C.getDriver().Dir);
llvm::sys::path::append(ForeachPath, "llvm-foreach");
const char *Foreach = C.getArgs().MakeArgString(ForeachPath);
auto Cmd = std::make_unique<Command>(JA, *T, ResponseFileSupport::None(),
Foreach, ForeachArgs, std::nullopt);
// FIXME: Add the FPGA specific timing diagnostic to the foreach call.
// The foreach call obscures the return codes from the tool it is calling
// to the compiler itself.
addFPGATimingDiagnostic(Cmd, C);
C.addCommand(std::move(Cmd));
}
bool SYCL::shouldDoPerObjectFileLinking(const Compilation &C) {
return !C.getArgs().hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
/*default=*/true);
}
// Return whether to use native bfloat16 library.
static bool selectBfloatLibs(const llvm::Triple &Triple, const Compilation &C,
bool &UseNative) {
const llvm::opt::ArgList &Args = C.getArgs();
bool NeedLibs = false;
// spir64 target is actually JIT compilation, so we defer selection of
// bfloat16 libraries to runtime. For AOT we need libraries, but skip
// for Nvidia.
NeedLibs =
Triple.getSubArch() != llvm::Triple::NoSubArch && !Triple.isNVPTX();
UseNative = false;
if (NeedLibs && Triple.getSubArch() == llvm::Triple::SPIRSubArch_gen &&
C.hasOffloadToolChain<Action::OFK_SYCL>()) {
ArgStringList TargArgs;
auto ToolChains = C.getOffloadToolChains<Action::OFK_SYCL>();
// Match up the toolchain with the incoming Triple so we are grabbing the
// expected arguments to scrutinize.
for (auto TI = ToolChains.first, TE = ToolChains.second; TI != TE; ++TI) {
llvm::Triple SYCLTriple = TI->second->getTriple();
if (SYCLTriple == Triple) {
const toolchains::SYCLToolChain *SYCLTC =
static_cast<const toolchains::SYCLToolChain *>(TI->second);
SYCLTC->TranslateBackendTargetArgs(Triple, Args, TargArgs);
break;
}
}
auto checkBF = [](StringRef Device) {
return Device.starts_with("pvc") || Device.starts_with("ats");
};
std::string Params;
for (const auto &Arg : TargArgs) {
Params += " ";
Params += Arg;
}
size_t DevicesPos = Params.find("-device ");
UseNative = false;
if (DevicesPos != std::string::npos) {
UseNative = true;
std::istringstream Devices(Params.substr(DevicesPos + 8));
for (std::string S; std::getline(Devices, S, ',');)
UseNative &= checkBF(S);
}
}
return NeedLibs;
}
SmallVector<std::string, 8>
SYCL::getDeviceLibraries(const Compilation &C, const llvm::Triple &TargetTriple,
bool IsSpirvAOT) {
SmallVector<std::string, 8> LibraryList;
const llvm::opt::ArgList &Args = C.getArgs();
struct DeviceLibOptInfo {
StringRef DeviceLibName;
StringRef DeviceLibOption;
};
bool NoDeviceLibs = false;
// Currently, all SYCL device libraries will be linked by default. Linkage
// of "internal" libraries cannot be affected via -fno-sycl-device-lib.
llvm::StringMap<bool> DeviceLibLinkInfo = {
{"libc", true}, {"libm-fp32", true}, {"libm-fp64", true},
{"libimf-fp32", true}, {"libimf-fp64", true}, {"libimf-bf16", true},
{"libm-bfloat16", true}, {"internal", true}};
if (Arg *A = Args.getLastArg(options::OPT_fsycl_device_lib_EQ,
options::OPT_fno_sycl_device_lib_EQ)) {
if (A->getValues().size() == 0)
C.getDriver().Diag(diag::warn_drv_empty_joined_argument)
<< A->getAsString(Args);
else {
if (A->getOption().matches(options::OPT_fno_sycl_device_lib_EQ))
NoDeviceLibs = true;
for (StringRef Val : A->getValues()) {
if (Val == "all") {
for (const auto &K : DeviceLibLinkInfo.keys())
DeviceLibLinkInfo[K] =
true && (!NoDeviceLibs || K.equals("internal"));
break;
}
auto LinkInfoIter = DeviceLibLinkInfo.find(Val);
if (LinkInfoIter == DeviceLibLinkInfo.end() || Val.equals("internal")) {
// TODO: Move the diagnostic to the SYCL section of
// Driver::CreateOffloadingDeviceToolChains() to minimize code
// duplication.
C.getDriver().Diag(diag::err_drv_unsupported_option_argument)
<< A->getSpelling() << Val;
}
DeviceLibLinkInfo[Val] = true && !NoDeviceLibs;
}
}
}
using SYCLDeviceLibsList = SmallVector<DeviceLibOptInfo, 5>;
const SYCLDeviceLibsList SYCLDeviceWrapperLibs = {
{"libsycl-crt", "libc"},
{"libsycl-complex", "libm-fp32"},
{"libsycl-complex-fp64", "libm-fp64"},
{"libsycl-cmath", "libm-fp32"},
{"libsycl-cmath-fp64", "libm-fp64"},
#if defined(_WIN32)
{"libsycl-msvc-math", "libm-fp32"},
#endif
{"libsycl-imf", "libimf-fp32"},
{"libsycl-imf-fp64", "libimf-fp64"},
{"libsycl-imf-bf16", "libimf-bf16"}};
// For AOT compilation, we need to link sycl_device_fallback_libs as
// default too.
const SYCLDeviceLibsList SYCLDeviceFallbackLibs = {
{"libsycl-fallback-cassert", "libc"},
{"libsycl-fallback-cstring", "libc"},
{"libsycl-fallback-complex", "libm-fp32"},
{"libsycl-fallback-complex-fp64", "libm-fp64"},
{"libsycl-fallback-cmath", "libm-fp32"},
{"libsycl-fallback-cmath-fp64", "libm-fp64"},
{"libsycl-fallback-imf", "libimf-fp32"},
{"libsycl-fallback-imf-fp64", "libimf-fp64"},
{"libsycl-fallback-imf-bf16", "libimf-bf16"}};
const SYCLDeviceLibsList SYCLDeviceBfloat16FallbackLib = {
{"libsycl-fallback-bfloat16", "libm-bfloat16"}};
const SYCLDeviceLibsList SYCLDeviceBfloat16NativeLib = {
{"libsycl-native-bfloat16", "libm-bfloat16"}};
// ITT annotation libraries are linked in separately whenever the device
// code instrumentation is enabled.
const SYCLDeviceLibsList SYCLDeviceAnnotationLibs = {
{"libsycl-itt-user-wrappers", "internal"},
{"libsycl-itt-compiler-wrappers", "internal"},
{"libsycl-itt-stubs", "internal"}};
#if !defined(_WIN32)
const SYCLDeviceLibsList SYCLDeviceSanitizerLibs = {
{"libsycl-sanitizer", "internal"}};
#endif
bool IsWindowsMSVCEnv =
C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
bool IsNewOffload = C.getDriver().getUseNewOffloadingDriver();
StringRef LibSuffix = ".bc";
if (TargetTriple.isNVPTX() ||
(TargetTriple.isSPIR() &&
TargetTriple.getSubArch() == llvm::Triple::SPIRSubArch_fpga))
// For NVidia or FPGA, we are unbundling objects.
LibSuffix = IsWindowsMSVCEnv ? ".obj" : ".o";
if (IsNewOffload)
// For new offload model, we use packaged .bc files.
LibSuffix = IsWindowsMSVCEnv ? ".new.obj" : ".new.o";
auto addLibraries = [&](const SYCLDeviceLibsList &LibsList) {
for (const DeviceLibOptInfo &Lib : LibsList) {
if (!DeviceLibLinkInfo[Lib.DeviceLibOption])
continue;
SmallString<128> LibName(Lib.DeviceLibName);
llvm::sys::path::replace_extension(LibName, LibSuffix);
LibraryList.push_back(Args.MakeArgString(LibName));
}
};
addLibraries(SYCLDeviceWrapperLibs);
if (IsSpirvAOT || TargetTriple.isNVPTX())
addLibraries(SYCLDeviceFallbackLibs);
bool NativeBfloatLibs;
bool NeedBfloatLibs = selectBfloatLibs(TargetTriple, C, NativeBfloatLibs);
if (NeedBfloatLibs) {
// Add native or fallback bfloat16 library.
if (NativeBfloatLibs)
addLibraries(SYCLDeviceBfloat16NativeLib);
else
addLibraries(SYCLDeviceBfloat16FallbackLib);
}
if (Args.hasFlag(options::OPT_fsycl_instrument_device_code,
options::OPT_fno_sycl_instrument_device_code, true))
addLibraries(SYCLDeviceAnnotationLibs);
#if !defined(_WIN32)
if (Arg *A = Args.getLastArg(options::OPT_fsanitize_EQ,
options::OPT_fno_sanitize_EQ)) {
if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
A->getValues().size() == 1) {
std::string SanitizeVal = A->getValue();
if (SanitizeVal == "address")
addLibraries(SYCLDeviceSanitizerLibs);
}
} else {
// User can pass -fsanitize=address to device compiler via
// -Xsycl-target-frontend, sanitize device library must be
// linked with user's device image if so.
bool IsDeviceAsanEnabled = false;
auto SyclFEArg = Args.getAllArgValues(options::OPT_Xsycl_frontend);
IsDeviceAsanEnabled = (std::count(SyclFEArg.begin(), SyclFEArg.end(),
"-fsanitize=address") > 0);
if (!IsDeviceAsanEnabled) {
auto SyclFEArgEq = Args.getAllArgValues(options::OPT_Xsycl_frontend_EQ);
IsDeviceAsanEnabled = (std::count(SyclFEArgEq.begin(), SyclFEArgEq.end(),
"-fsanitize=address") > 0);
}
// User can also enable asan for SYCL device via -Xarch_device option.
if (!IsDeviceAsanEnabled) {
auto DeviceArchVals = Args.getAllArgValues(options::OPT_Xarch_device);
for (auto DArchVal : DeviceArchVals) {
if (DArchVal.find("-fsanitize=address") != std::string::npos) {
IsDeviceAsanEnabled = true;
break;
}
}
}
if (IsDeviceAsanEnabled)
addLibraries(SYCLDeviceSanitizerLibs);
}
#endif
return LibraryList;
}
// The list should match pre-built SYCL device library files located in
// compiler package. Once we add or remove any SYCL device library files,
// the list should be updated accordingly.
static llvm::SmallVector<StringRef, 16> SYCLDeviceLibList{
"bfloat16",
"crt",
"cmath",
"cmath-fp64",
"complex",
"complex-fp64",
#if defined(_WIN32)
"msvc-math",
#else
"sanitizer",
#endif
"imf",
"imf-fp64",
"imf-bf16",
"itt-compiler-wrappers",
"itt-stubs",
"itt-user-wrappers",
"fallback-cassert",
"fallback-cstring",
"fallback-cmath",
"fallback-cmath-fp64",
"fallback-complex",
"fallback-complex-fp64",
"fallback-imf",
"fallback-imf-fp64",
"fallback-imf-bf16",
"fallback-bfloat16",
"native-bfloat16"};
const char *SYCL::Linker::constructLLVMLinkCommand(
Compilation &C, const JobAction &JA, const InputInfo &Output,
const ArgList &Args, StringRef SubArchName, StringRef OutputFilePrefix,
const InputInfoList &InputFiles) const {
// Split inputs into libraries which have 'archive' type and other inputs
// which can be either objects or list files. Object files are linked together
// in a usual way, but the libraries/list files need to be linked differently.
// We need to fetch only required symbols from the libraries. With the current
// llvm-link command line interface that can be achieved with two step
// linking: at the first step we will link objects into an intermediate
// partially linked image which on the second step will be linked with the
// libraries with --only-needed option.
ArgStringList Opts;
ArgStringList Objs;
ArgStringList Libs;
// Add the input bc's created by compile step.
// When offloading, the input file(s) could be from unbundled partially
// linked archives. The unbundled information is a list of files and not
// an actual object/archive. Take that list and pass those to the linker
// instead of the original object.
if (JA.isDeviceOffloading(Action::OFK_SYCL)) {
bool IsRDC = !shouldDoPerObjectFileLinking(C);
const bool IsSYCLNativeCPU = isSYCLNativeCPU(this->getToolChain());
auto isNoRDCDeviceCodeLink = [&](const InputInfo &II) {
if (IsRDC)
return false;
if (II.getType() != clang::driver::types::TY_LLVM_BC)
return false;
if (InputFiles.size() != 2)
return false;
return &II == &InputFiles[1];
};
auto isSYCLDeviceLib = [&](const InputInfo &II) {
const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
const bool IsNVPTX = this->getToolChain().getTriple().isNVPTX();
const bool IsFPGA = this->getToolChain().getTriple().isSPIR() &&
this->getToolChain().getTriple().getSubArch() ==
llvm::Triple::SPIRSubArch_fpga;
StringRef LibPostfix = ".bc";
if (IsNVPTX || IsFPGA) {
LibPostfix = ".o";
if (HostTC->getTriple().isWindowsMSVCEnvironment() &&
C.getDriver().IsCLMode())
LibPostfix = ".obj";
}
StringRef NewLibPostfix = ".new.o";
if (HostTC->getTriple().isWindowsMSVCEnvironment() &&
C.getDriver().IsCLMode())
NewLibPostfix = ".new.obj";
std::string FileName = this->getToolChain().getInputFilename(II);
StringRef InputFilename = llvm::sys::path::filename(FileName);
if (IsNVPTX || IsSYCLNativeCPU) {
// Linking SYCL Device libs requires libclc as well as libdevice
if ((InputFilename.find("libspirv") != InputFilename.npos ||
InputFilename.find("libdevice") != InputFilename.npos))
return true;
if (IsNVPTX) {
LibPostfix = ".cubin";
NewLibPostfix = ".new.cubin";
}
}
StringRef LibSyclPrefix("libsycl-");
if (!InputFilename.starts_with(LibSyclPrefix) ||
!InputFilename.ends_with(LibPostfix) ||
InputFilename.ends_with(NewLibPostfix))
return false;
// Skip the prefix "libsycl-"
std::string PureLibName =
InputFilename.substr(LibSyclPrefix.size()).str();
if (isNoRDCDeviceCodeLink(II)) {
// Skip the final - until the . because we linked all device libs into a
// single BC in a previous action so we have a temp file name.
auto FinalDashPos = PureLibName.find_last_of('-');
auto DotPos = PureLibName.find_last_of('.');
assert((FinalDashPos != std::string::npos &&
DotPos != std::string::npos) &&
"Unexpected filename");
PureLibName =
PureLibName.substr(0, FinalDashPos) + PureLibName.substr(DotPos);
}
for (const auto &L : SYCLDeviceLibList) {
std::string DeviceLibName(L);
DeviceLibName.append(LibPostfix);
if (StringRef(PureLibName).equals(DeviceLibName) ||
(IsNVPTX && StringRef(PureLibName).starts_with(L)))
return true;
}
return false;
};
size_t InputFileNum = InputFiles.size();
bool LinkSYCLDeviceLibs = (InputFileNum >= 2);
LinkSYCLDeviceLibs = LinkSYCLDeviceLibs && !isSYCLDeviceLib(InputFiles[0]);
for (size_t Idx = 1; Idx < InputFileNum; ++Idx)
LinkSYCLDeviceLibs =
LinkSYCLDeviceLibs && isSYCLDeviceLib(InputFiles[Idx]);
if (LinkSYCLDeviceLibs) {
Opts.push_back("-only-needed");
}
// Go through the Inputs to the link. When a listfile is encountered, we
// know it is an unbundled generated list.
for (const auto &II : InputFiles) {
std::string FileName = getToolChain().getInputFilename(II);
if (II.getType() == types::TY_Tempfilelist) {
if (IsRDC) {
// Pass the unbundled list with '@' to be processed.
Libs.push_back(C.getArgs().MakeArgString("@" + FileName));
} else {
assert(InputFiles.size() == 2 &&
"Unexpected inputs for no-RDC with temp file list");
// If we're in no-RDC mode and the input is a temp file list,
// we want to link multiple object files each against device libs,
// so we should consider this input as an object and not pass '@'.
Objs.push_back(C.getArgs().MakeArgString(FileName));
}
} else if (II.getType() == types::TY_Archive && !LinkSYCLDeviceLibs) {
Libs.push_back(C.getArgs().MakeArgString(FileName));
} else
Objs.push_back(C.getArgs().MakeArgString(FileName));
}
} else
for (const auto &II : InputFiles)
Objs.push_back(
C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
// Get llvm-link path.
SmallString<128> ExecPath(C.getDriver().Dir);
llvm::sys::path::append(ExecPath, "llvm-link");
const char *Exec = C.getArgs().MakeArgString(ExecPath);
auto AddLinkCommand = [this, &C, &JA, Exec](const char *Output,
const ArgStringList &Inputs,
const ArgStringList &Options) {
ArgStringList CmdArgs;
llvm::copy(Options, std::back_inserter(CmdArgs));
llvm::copy(Inputs, std::back_inserter(CmdArgs));
CmdArgs.push_back("-o");
CmdArgs.push_back(Output);
// TODO: temporary workaround for a problem with warnings reported by
// llvm-link when driver links LLVM modules with empty modules
CmdArgs.push_back("--suppress-warnings");
C.addCommand(std::make_unique<Command>(JA, *this,
ResponseFileSupport::AtFileUTF8(),
Exec, CmdArgs, std::nullopt));
};
// Add an intermediate output file.
const char *OutputFileName =
C.getArgs().MakeArgString(getToolChain().getInputFilename(Output));
if (Libs.empty())
AddLinkCommand(OutputFileName, Objs, Opts);
else {
assert(Opts.empty() && "unexpected options");
// Linker will be invoked twice if inputs contain libraries. First time we
// will link input objects into an intermediate temporary file, and on the
// second invocation intermediate temporary object will be linked with the
// libraries, but now only required symbols will be added to the final
// output.
std::string TempFile =
C.getDriver().GetTemporaryPath(OutputFilePrefix.str() + "-link", "bc");
const char *LinkOutput = C.addTempFile(C.getArgs().MakeArgString(TempFile));
AddLinkCommand(LinkOutput, Objs, {});
// Now invoke linker for the second time to link required symbols from the
// input libraries.
ArgStringList LinkInputs{LinkOutput};
llvm::copy(Libs, std::back_inserter(LinkInputs));
AddLinkCommand(OutputFileName, LinkInputs, {"--only-needed"});
}
return OutputFileName;
}
void SYCL::Linker::constructLlcCommand(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const char *InputFileName) const {
// Construct llc command.
// The output is an object file.
ArgStringList LlcArgs{"-filetype=obj", "-o", Output.getFilename(),
InputFileName};
SmallString<128> LlcPath(C.getDriver().Dir);
llvm::sys::path::append(LlcPath, "llc");
const char *Llc = C.getArgs().MakeArgString(LlcPath);
C.addCommand(std::make_unique<Command>(JA, *this,
ResponseFileSupport::AtFileUTF8(), Llc,
LlcArgs, std::nullopt));
}
// For SYCL the inputs of the linker job are SPIR-V binaries and output is
// a single SPIR-V binary. Input can also be bitcode when specified by
// the user.
void SYCL::Linker::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
assert((getToolChain().getTriple().isSPIROrSPIRV() ||
getToolChain().getTriple().isNVPTX() ||
getToolChain().getTriple().isAMDGCN() || isSYCLNativeCPU(Args)) &&
"Unsupported target");
std::string SubArchName =
std::string(getToolChain().getTriple().getArchName());
// Prefix for temporary file name.
std::string Prefix = std::string(llvm::sys::path::stem(SubArchName));
// For CUDA, we want to link all BC files before resuming the normal
// compilation path
if (getToolChain().getTriple().isNVPTX() ||
getToolChain().getTriple().isAMDGCN()) {
InputInfoList NvptxInputs;
for (const auto &II : Inputs) {
if (!II.isFilename())
continue;
NvptxInputs.push_back(II);
}
constructLLVMLinkCommand(C, JA, Output, Args, SubArchName, Prefix,
NvptxInputs);
return;
}
InputInfoList SpirvInputs;
for (const auto &II : Inputs) {
if (!II.isFilename())
continue;
SpirvInputs.push_back(II);
}
constructLLVMLinkCommand(C, JA, Output, Args, SubArchName, Prefix,
SpirvInputs);
}
static const char *makeExeName(Compilation &C, StringRef Name) {
llvm::SmallString<8> ExeName(Name);
const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
if (HostTC->getTriple().isWindowsMSVCEnvironment())
ExeName.append(".exe");
return C.getArgs().MakeArgString(ExeName);
}
void SYCL::fpga::BackendCompiler::constructOpenCLAOTCommand(
Compilation &C, const JobAction &JA, const InputInfo &Output,
const InputInfoList &Inputs, const ArgList &Args) const {
// Construct opencl-aot command. This is used for FPGA AOT compilations
// when performing emulation. Input file will be a SPIR-V binary which
// will be compiled to an aocx file.
InputInfoList ForeachInputs;
InputInfoList FPGADepFiles;
ArgStringList CmdArgs{"-device=fpga_fast_emu"};
for (const auto &II : Inputs) {
if (II.getType() == types::TY_TempAOCOfilelist ||
II.getType() == types::TY_FPGA_Dependencies ||
II.getType() == types::TY_FPGA_Dependencies_List)
continue;
if (II.getType() == types::TY_Tempfilelist)
ForeachInputs.push_back(II);
CmdArgs.push_back(
C.getArgs().MakeArgString("-spv=" + Twine(II.getFilename())));
}
CmdArgs.push_back(
C.getArgs().MakeArgString("-ir=" + Twine(Output.getFilename())));
StringRef ForeachExt = "aocx";
if (Arg *A = Args.getLastArg(options::OPT_fsycl_link_EQ))
if (A->getValue() == StringRef("early"))
ForeachExt = "aocr";
// Add any implied arguments before user defined arguments.
const toolchains::SYCLToolChain &TC =
static_cast<const toolchains::SYCLToolChain &>(getToolChain());
const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
llvm::Triple CPUTriple("spir64_x86_64");
TC.AddImpliedTargetArgs(CPUTriple, Args, CmdArgs, JA, *HostTC);
// Add the target args passed in
TC.TranslateBackendTargetArgs(CPUTriple, Args, CmdArgs);
TC.TranslateLinkerTargetArgs(CPUTriple, Args, CmdArgs);
SmallString<128> ExecPath(
getToolChain().GetProgramPath(makeExeName(C, "opencl-aot")));
const char *Exec = C.getArgs().MakeArgString(ExecPath);
auto Cmd = std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
Exec, CmdArgs, std::nullopt);
if (!ForeachInputs.empty()) {
StringRef ParallelJobs =
Args.getLastArgValue(options::OPT_fsycl_max_parallel_jobs_EQ);
constructLLVMForeachCommand(C, JA, std::move(Cmd), ForeachInputs, Output,
this, "", ForeachExt, ParallelJobs);
} else
C.addCommand(std::move(Cmd));
}
void SYCL::fpga::BackendCompiler::ConstructJob(
Compilation &C, const JobAction &JA, const InputInfo &Output,
const InputInfoList &Inputs, const ArgList &Args,
const char *LinkingOutput) const {
assert(getToolChain().getTriple().isSPIROrSPIRV() && "Unsupported target");
// Grab the -Xsycl-target* options.
const toolchains::SYCLToolChain &TC =
static_cast<const toolchains::SYCLToolChain &>(getToolChain());
ArgStringList TargetArgs;
TC.TranslateBackendTargetArgs(TC.getTriple(), Args, TargetArgs);
// When performing emulation compilations for FPGA AOT, we want to use
// opencl-aot instead of aoc.
if (C.getDriver().IsFPGAEmulationMode()) {
constructOpenCLAOTCommand(C, JA, Output, Inputs, Args);
return;
}
InputInfoList ForeachInputs;
InputInfoList FPGADepFiles;
StringRef CreatedReportName;
ArgStringList CmdArgs{"-o", Output.getFilename()};
for (const auto &II : Inputs) {
std::string Filename(II.getFilename());
if (II.getType() == types::TY_Tempfilelist)
ForeachInputs.push_back(II);
if (II.getType() == types::TY_TempAOCOfilelist)
// Add any FPGA library lists. These come in as special tempfile lists.
CmdArgs.push_back(Args.MakeArgString(Twine("-library-list=") + Filename));
else if (II.getType() == types::TY_FPGA_Dependencies ||
II.getType() == types::TY_FPGA_Dependencies_List)
FPGADepFiles.push_back(II);
else
CmdArgs.push_back(C.getArgs().MakeArgString(Filename));
// Check for any AOCR input, if found use that as the project report name
StringRef Ext(llvm::sys::path::extension(Filename));
if (Ext.empty())
continue;
if (getToolChain().LookupTypeForExtension(Ext.drop_front()) ==
types::TY_FPGA_AOCR) {
// Keep the base of the .aocr file name. Input file is a temporary,
// so we are stripping off the additional naming information for a
// cleaner name. The suffix being stripped from the name is the
// added temporary string and the extension.
StringRef SuffixFormat("-XXXXXX.aocr");
SmallString<128> NameBase(
Filename.substr(0, Filename.length() - SuffixFormat.size()));
NameBase.append(".prj");
CreatedReportName =
Args.MakeArgString(llvm::sys::path::filename(NameBase));
}
}
CmdArgs.push_back("-sycl");
StringRef ForeachExt = "aocx";
if (Arg *A = Args.getLastArg(options::OPT_fsycl_link_EQ))
if (A->getValue() == StringRef("early")) {
CmdArgs.push_back("-rtl");
ForeachExt = "aocr";
}
for (auto *A : Args) {
// Any input file is assumed to have a dependency file associated and
// the report folder can also be named based on the first input.
if (A->getOption().getKind() != Option::InputClass)
continue;
SmallString<128> ArgName(A->getSpelling());
StringRef Ext(llvm::sys::path::extension(ArgName));
if (Ext.empty())
continue;
types::ID Ty = getToolChain().LookupTypeForExtension(Ext.drop_front());
if (Ty == types::TY_INVALID)
continue;
if (types::isSrcFile(Ty) || Ty == types::TY_Object) {
// The project report is created in CWD, so strip off any directory
// information if provided with the input file.
StringRef TrimmedArgName = llvm::sys::path::filename(ArgName);
if (types::isSrcFile(Ty)) {
SmallString<128> DepName(
C.getDriver().getFPGATempDepFile(std::string(TrimmedArgName)));
if (!DepName.empty())
FPGADepFiles.push_back(InputInfo(types::TY_Dependencies,
Args.MakeArgString(DepName),
Args.MakeArgString(DepName)));
}
if (CreatedReportName.empty()) {
// Project report should be saved into CWD, so strip off any
// directory information if provided with the input file.
llvm::sys::path::replace_extension(ArgName, "prj");
CreatedReportName = Args.MakeArgString(ArgName);
}
}
}
// Add any dependency files.
if (!FPGADepFiles.empty()) {
SmallString<128> DepOpt("-dep-files=");
for (unsigned I = 0; I < FPGADepFiles.size(); ++I) {
if (I)
DepOpt += ',';
if (FPGADepFiles[I].getType() == types::TY_FPGA_Dependencies_List)
DepOpt += "@";
DepOpt += FPGADepFiles[I].getFilename();
}
CmdArgs.push_back(C.getArgs().MakeArgString(DepOpt));
}
// Depending on output file designations, set the report folder
SmallString<128> ReportOptArg;
if (Arg *FinalOutput = Args.getLastArg(options::OPT_o, options::OPT__SLASH_o,
options::OPT__SLASH_Fe)) {
SmallString<128> FN(FinalOutput->getValue());
// For "-o file.xxx" where the option value has an extension, if the
// extension is one of .a .o .out .lib .obj .exe, the output project
// directory name will be file.proj which omits the extension. Otherwise
// the output project directory name will be file.xxx.prj which keeps
// the original extension.
StringRef Ext = llvm::sys::path::extension(FN);
SmallVector<StringRef, 6> Exts = {".o", ".a", ".out",
".obj", ".lib", ".exe"};
if (std::find(Exts.begin(), Exts.end(), Ext) != Exts.end())
llvm::sys::path::replace_extension(FN, "prj");
else
FN.append(".prj");
const char *FolderName = Args.MakeArgString(FN);
ReportOptArg += FolderName;
} else {
// Default output directory should match default output executable name
ReportOptArg += "a.prj";
}
if (!ReportOptArg.empty())
CmdArgs.push_back(C.getArgs().MakeArgString(
Twine("-output-report-folder=") + ReportOptArg));
// Add any implied arguments before user defined arguments.
const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
TC.AddImpliedTargetArgs(getToolChain().getTriple(), Args, CmdArgs, JA,
*HostTC);
// Add -Xsycl-target* options.
TC.TranslateBackendTargetArgs(getToolChain().getTriple(), Args, CmdArgs);
TC.TranslateLinkerTargetArgs(getToolChain().getTriple(), Args, CmdArgs);
// Look for -reuse-exe=XX option
if (Arg *A = Args.getLastArg(options::OPT_reuse_exe_EQ)) {
Args.ClaimAllArgs(options::OPT_reuse_exe_EQ);
CmdArgs.push_back(Args.MakeArgString(A->getAsString(Args)));
}
SmallString<128> ExecPath(
getToolChain().GetProgramPath(makeExeName(C, "aoc")));
const char *Exec = C.getArgs().MakeArgString(ExecPath);
auto Cmd = std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
Exec, CmdArgs, std::nullopt);
addFPGATimingDiagnostic(Cmd, C);
if (!ForeachInputs.empty()) {
StringRef ParallelJobs =
Args.getLastArgValue(options::OPT_fsycl_max_parallel_jobs_EQ);
constructLLVMForeachCommand(C, JA, std::move(Cmd), ForeachInputs, Output,
this, ReportOptArg, ForeachExt, ParallelJobs);
} else
C.addCommand(std::move(Cmd));
}
static llvm::StringMap<StringRef> GRFModeFlagMap{
{"auto", "-ze-intel-enable-auto-large-GRF-mode"},
{"small", "-ze-intel-128-GRF-per-thread"},
{"large", "-ze-opt-large-register-file"}};
StringRef SYCL::gen::getGenGRFFlag(StringRef GRFMode) {
if (!GRFModeFlagMap.contains(GRFMode))
return "";
return GRFModeFlagMap[GRFMode];
}
void SYCL::gen::BackendCompiler::ConstructJob(Compilation &C,
const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
assert(getToolChain().getTriple().isSPIROrSPIRV() && "Unsupported target");
ArgStringList CmdArgs{"-output", Output.getFilename()};
InputInfoList ForeachInputs;
for (const auto &II : Inputs) {
CmdArgs.push_back("-file");
std::string Filename(II.getFilename());
if (II.getType() == types::TY_Tempfilelist)
ForeachInputs.push_back(II);
CmdArgs.push_back(C.getArgs().MakeArgString(Filename));
}
// The next line prevents ocloc from modifying the image name
CmdArgs.push_back("-output_no_suffix");
CmdArgs.push_back("-spirv_input");
StringRef Device = JA.getOffloadingArch();
// Add -Xsycl-target* options.
const toolchains::SYCLToolChain &TC =
static_cast<const toolchains::SYCLToolChain &>(getToolChain());
const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
TC.AddImpliedTargetArgs(getToolChain().getTriple(), Args, CmdArgs, JA,
*HostTC);
TC.TranslateBackendTargetArgs(getToolChain().getTriple(), Args, CmdArgs,
Device);
TC.TranslateLinkerTargetArgs(getToolChain().getTriple(), Args, CmdArgs);
SmallString<128> ExecPath(
getToolChain().GetProgramPath(makeExeName(C, "ocloc")));
const char *Exec = C.getArgs().MakeArgString(ExecPath);
auto Cmd = std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
Exec, CmdArgs, std::nullopt);
if (!ForeachInputs.empty()) {
StringRef ParallelJobs =
Args.getLastArgValue(options::OPT_fsycl_max_parallel_jobs_EQ);
constructLLVMForeachCommand(C, JA, std::move(Cmd), ForeachInputs, Output,
this, "", "out", ParallelJobs);
} else
C.addCommand(std::move(Cmd));
}
StringRef SYCL::gen::resolveGenDevice(StringRef DeviceName) {
StringRef Device;
Device =
llvm::StringSwitch<StringRef>(DeviceName)
.Cases("intel_gpu_bdw", "intel_gpu_8_0_0", "bdw")
.Cases("intel_gpu_skl", "intel_gpu_9_0_9", "skl")
.Cases("intel_gpu_kbl", "intel_gpu_9_1_9", "kbl")
.Cases("intel_gpu_cfl", "intel_gpu_9_2_9", "cfl")
.Cases("intel_gpu_apl", "intel_gpu_bxt", "intel_gpu_9_3_0", "apl")
.Cases("intel_gpu_glk", "intel_gpu_9_4_0", "glk")
.Cases("intel_gpu_whl", "intel_gpu_9_5_0", "whl")
.Cases("intel_gpu_aml", "intel_gpu_9_6_0", "aml")
.Cases("intel_gpu_cml", "intel_gpu_9_7_0", "cml")
.Cases("intel_gpu_icllp", "intel_gpu_icl", "intel_gpu_11_0_0",
"icllp")
.Cases("intel_gpu_ehl", "intel_gpu_jsl", "intel_gpu_11_2_0", "ehl")
.Cases("intel_gpu_tgllp", "intel_gpu_tgl", "intel_gpu_12_0_0",
"tgllp")
.Cases("intel_gpu_rkl", "intel_gpu_12_1_0", "rkl")
.Cases("intel_gpu_adl_s", "intel_gpu_rpl_s", "intel_gpu_12_2_0",
"adl_s")
.Cases("intel_gpu_adl_p", "intel_gpu_12_3_0", "adl_p")
.Cases("intel_gpu_adl_n", "intel_gpu_12_4_0", "adl_n")
.Cases("intel_gpu_dg1", "intel_gpu_12_10_0", "dg1")
.Cases("intel_gpu_acm_g10", "intel_gpu_dg2_g10", "intel_gpu_12_55_8",
"acm_g10")
.Cases("intel_gpu_acm_g11", "intel_gpu_dg2_g11", "intel_gpu_12_56_5",
"acm_g11")
.Cases("intel_gpu_acm_g12", "intel_gpu_dg2_g12", "intel_gpu_12_57_0",
"acm_g12")
.Cases("intel_gpu_pvc", "intel_gpu_12_60_7", "pvc")
.Cases("intel_gpu_pvc_vg", "intel_gpu_12_61_7", "pvc_vg")
.Cases("intel_gpu_mtl_u", "intel_gpu_mtl_s", "intel_gpu_arl_u",
"intel_gpu_arl_s", "intel_gpu_12_70_4", "mtl_u")
.Cases("intel_gpu_mtl_h", "intel_gpu_12_71_4", "mtl_h")
.Cases("intel_gpu_arl_h", "intel_gpu_12_74_4", "arl_h")
.Cases("intel_gpu_bmg_g21", "intel_gpu_20_1_4", "bmg_g21")
.Cases("intel_gpu_lnl_m", "intel_gpu_20_4_4", "lnl_m")
.Case("nvidia_gpu_sm_50", "sm_50")
.Case("nvidia_gpu_sm_52", "sm_52")
.Case("nvidia_gpu_sm_53", "sm_53")
.Case("nvidia_gpu_sm_60", "sm_60")
.Case("nvidia_gpu_sm_61", "sm_61")
.Case("nvidia_gpu_sm_62", "sm_62")
.Case("nvidia_gpu_sm_70", "sm_70")
.Case("nvidia_gpu_sm_72", "sm_72")
.Case("nvidia_gpu_sm_75", "sm_75")
.Case("nvidia_gpu_sm_80", "sm_80")
.Case("nvidia_gpu_sm_86", "sm_86")
.Case("nvidia_gpu_sm_87", "sm_87")
.Case("nvidia_gpu_sm_89", "sm_89")
.Case("nvidia_gpu_sm_90", "sm_90")
.Case("amd_gpu_gfx700", "gfx700")
.Case("amd_gpu_gfx701", "gfx701")
.Case("amd_gpu_gfx702", "gfx702")
.Case("amd_gpu_gfx801", "gfx801")
.Case("amd_gpu_gfx802", "gfx802")
.Case("amd_gpu_gfx803", "gfx803")
.Case("amd_gpu_gfx805", "gfx805")
.Case("amd_gpu_gfx810", "gfx810")
.Case("amd_gpu_gfx900", "gfx900")
.Case("amd_gpu_gfx902", "gfx902")
.Case("amd_gpu_gfx904", "gfx904")
.Case("amd_gpu_gfx906", "gfx906")
.Case("amd_gpu_gfx908", "gfx908")
.Case("amd_gpu_gfx909", "gfx909")
.Case("amd_gpu_gfx90a", "gfx90a")
.Case("amd_gpu_gfx90c", "gfx90c")
.Case("amd_gpu_gfx940", "gfx940")
.Case("amd_gpu_gfx941", "gfx941")
.Case("amd_gpu_gfx942", "gfx942")
.Case("amd_gpu_gfx1010", "gfx1010")
.Case("amd_gpu_gfx1011", "gfx1011")
.Case("amd_gpu_gfx1012", "gfx1012")
.Case("amd_gpu_gfx1013", "gfx1013")
.Case("amd_gpu_gfx1030", "gfx1030")
.Case("amd_gpu_gfx1031", "gfx1031")
.Case("amd_gpu_gfx1032", "gfx1032")