-
Notifications
You must be signed in to change notification settings - Fork 699
/
Copy pathLLVMIRGen.cpp
4308 lines (3822 loc) · 181 KB
/
LLVMIRGen.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) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "glow/LLVMIRCodeGen/LLVMIRGen.h"
#include "glow/Base/DimType.h"
#include "glow/LLVMIRCodeGen/AllocationsInfo.h"
#include "glow/LLVMIRCodeGen/CommandLine.h"
#include "glow/LLVMIRCodeGen/LLVMBackend.h"
#include "glow/Graph/Graph.h"
#include "glow/IR/IRUtils.h"
#include "glow/IR/Instrs.h"
#include "glow/Quantization/Base/Base.h"
#include "glow/Support/Debug.h"
#include "llvm/Demangle/Demangle.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#define DEBUG_TYPE "llvmirgen"
using namespace glow;
using llvm::cast;
using llvm::dyn_cast;
using llvm::isa;
llvm::cl::opt<bool>
dumpLLVMIR("dump-llvm-ir",
llvm::cl::desc("Dump the LLVM-IR of the jitted code"),
llvm::cl::init(false), llvm::cl::cat(getLLVMBackendCat()));
llvm::cl::opt<bool>
dumpLLVMAsm("dump-llvm-asm",
llvm::cl::desc("Dump the textual assembly of the jitted code"),
llvm::cl::init(false), llvm::cl::cat(getLLVMBackendCat()));
llvm::cl::opt<bool>
emitDebugInfo("g", llvm::cl::desc("Emit debug information for debuggers"),
llvm::cl::init(false), llvm::cl::cat(getLLVMBackendCat()));
/// Limitation of number of arguments for `emitDataParallelKernel`.
constexpr static size_t kArgLimit = 64;
/// Query the TargetMachine to get the pointer size in bits
static unsigned getPointerNumBits(const llvm::TargetMachine &TM) {
return TM.getPointerSize(0) * 8;
}
LLVMIRGen::LLVMIRGen(const IRFunction *F, AllocationsInfo &allocationsInfo,
std::string mainEntryName, llvm::StringRef libjitBC)
: F_(F), ctx_(std::make_unique<llvm::LLVMContext>()),
allocationsInfo_(allocationsInfo), libjitBC_(libjitBC) {
#if LLVM_VERSION_MAJOR >= 15
// This API should fail on LLVM-17, we will need to keep an eye.
ctx_->setOpaquePointers(false);
#endif
// Legalize main entry name.
setMainEntryName(mainEntryName);
}
LLVMIRGen::LLVMIRGen(const IRFunction *F, AllocationsInfo &allocationsInfo,
std::string mainEntryName, llvm::StringRef libjitBC,
llvm::ArrayRef<llvm::MemoryBufferRef> objectRegistry)
: F_(F), ctx_(std::make_unique<llvm::LLVMContext>()),
allocationsInfo_(allocationsInfo), libjitBC_(libjitBC),
objectRegistry_(objectRegistry) {
#if LLVM_VERSION_MAJOR >= 15
// This API should fail on LLVM-17, we will need to keep an eye.
ctx_->setOpaquePointers(false);
#endif
// Legalize main entry name.
setMainEntryName(mainEntryName);
}
/// Mutex to protect LLVM's TargetRegistry.
static std::mutex initTargetMutex;
void LLVMIRGen::initTargetOptions(llvm::TargetOptions &targetOpts,
const LLVMBackendOptions &backendOpts) {
if (backendOpts.getFloatABI().hasValue()) {
targetOpts.FloatABIType = backendOpts.getFloatABI().getValue();
}
if (!backendOpts.getABIName().empty()) {
targetOpts.MCOptions.ABIName = backendOpts.getABIName();
}
}
void LLVMIRGen::initTargetMachine(const LLVMBackendOptions &opts) {
// LLVM's TargetRegistry is not thread safe so we add a critical section.
std::lock_guard<std::mutex> g(initTargetMutex);
llvm::InitializeAllTargets();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmPrinters();
llvm::InitializeAllAsmParsers();
llvm::TargetOptions targetOpts;
// Initialize target options in a backend-specific way.
initTargetOptions(targetOpts, opts);
if (opts.getTarget().empty()) {
TM_.reset(llvm::EngineBuilder()
.setCodeModel(opts.getCodeModel())
.setRelocationModel(opts.getRelocModel())
.setTargetOptions(targetOpts)
.selectTarget(llvm::Triple(), opts.getArch(),
LLVMBackend::getHostCPU(),
LLVMBackend::getHostFeatures()));
} else {
TM_.reset(llvm::EngineBuilder()
.setCodeModel(opts.getCodeModel())
.setRelocationModel(opts.getRelocModel())
.setTargetOptions(targetOpts)
.selectTarget(llvm::Triple(opts.getTarget()), opts.getArch(),
opts.getCPU(), opts.getTargetFeatures()));
}
assert(TM_ && "Could not initialize the target machine");
}
void LLVMIRGen::performBackendOptimizations() { return; }
llvm::StringRef LLVMIRGen::getBundleName() const { return bundleName_; }
void LLVMIRGen::setBundleName(const std::string &name) {
bundleName_ = name.empty() ? "bundle" : legalizeName(name);
}
llvm::StringRef LLVMIRGen::getSavedBundleName() const {
return savedBundleName_;
}
void LLVMIRGen::setSavedBundleName(const std::string &name) {
assert(!name.empty() && "Name cannot be empty");
savedBundleName_ = name;
}
std::string LLVMIRGen::getMainEntryName() const { return mainEntryName_; }
void LLVMIRGen::setMainEntryName(std::string name) {
mainEntryName_ = name.empty() ? "main" : legalizeName(name);
}
llvm::ArrayRef<llvm::MemoryBufferRef> LLVMIRGen::getObjectRegistry() const {
return objectRegistry_;
}
void LLVMIRGen::setObjectRegistry(
llvm::ArrayRef<llvm::MemoryBufferRef> objectRegistry) {
objectRegistry_ = objectRegistry;
}
std::vector<std::string> LLVMIRGen::getBundleObjects() const {
// Default list of object names.
auto bundleObjects = bundleObjects_;
// Add object names enforced from command line interface.
for (auto bundleObject : bundleObjectsOpt) {
bundleObjects.push_back(bundleObject);
}
return bundleObjects;
}
void LLVMIRGen::addBundleObject(llvm::StringRef objectName) {
// Add bundle object if not already added.
auto it =
std::find(bundleObjects_.begin(), bundleObjects_.end(), objectName.str());
if (it == bundleObjects_.end()) {
bundleObjects_.push_back(objectName.str());
}
}
/// Load base addresses of different memory areas so that they can be easily
/// reused during codegen.
void LLVMIRGen::loadBaseAddresses(llvm::IRBuilder<> &builder) {
auto *F = builder.GetInsertBlock()->getParent();
// Load the base addresses at the beginning of the entry function once they
// are set. They won't change after this point and all relative addressing
// computations will simply use them.
auto sizeTTy = builder.getIntNTy(getLibjitSizeTWidth());
baseActivationsAddr_ = builder.CreatePtrToInt(F->args().begin() + 2, sizeTTy);
baseConstantWeightVarsAddr_ =
builder.CreatePtrToInt(F->args().begin(), sizeTTy);
baseMutableWeightVarsAddr_ =
builder.CreatePtrToInt(F->args().begin() + 1, sizeTTy);
offsetsArray_ = F->args().begin() + 3;
}
// Search for the standard library bitcode file on disk and load it into an
// LLVM module. We search for the standard library around the current executable
// and also in the current directory.
std::unique_ptr<llvm::Module>
LLVMIRGen::loadStandardLibrary(llvm::LLVMContext *ctx, llvm::StringRef filename,
llvm::StringRef libjitBC) {
using llvm::sys::path::append;
using llvm::sys::path::parent_path;
llvm::SMDiagnostic error;
// Parse the compiled-in image of libjit and return the resulting Module.
// checking for and reporting errors from parseIR.
auto memBufRef = llvm::MemoryBufferRef(
llvm::StringRef(reinterpret_cast<const char *>(libjitBC.data()),
libjitBC.size()),
"libjit.bc");
std::unique_ptr<llvm::Module> mod(nullptr);
if (shouldUseLLVMModuleLazyLoading()) {
#if LLVM_VERSION_MAJOR >= 9
mod = llvm::getLazyIRModule(llvm::MemoryBuffer::getMemBuffer(memBufRef),
error, *ctx);
#else
LOG(FATAL) << "You need to use LLVM 9 or higher to support lazy loading of "
"LLVM IR modules.";
#endif
} else {
mod = llvm::parseIR(memBufRef, error, *ctx);
}
if (!mod) {
error.print("LLVMIRGen", llvm::errs());
}
return mod;
}
/// Register a diagnostics handler that prevents the compiler from printing to
/// stdout.
static void registerEmptyDiagHandler(llvm::LLVMContext &ctx) {
ctx.setDiagnosticHandlerCallBack(
[](const llvm::DiagnosticInfo &DI, void *Context) {
// Do not emit any warnings or diagnostics when JITting.
});
}
void LLVMIRGen::initCodeGen() {
// Load the jit library as a new module.
llmodule_ = loadStandardLibrary(&getLLVMContext(), "libjit.bc", libjitBC_);
CHECK(llmodule_.get()) << "Unable to load the JIT library.";
// By default, LLVM would emit some diagnostics, remarks, etc. It is fine for
// a static compiler, but not necessary for a JIT. Let's disable it by
// providing a dummy diagnostics handler, that does not emit anything.
// In particular, this allows us to get rid of the annoying "cannot vectorize"
// warnings.
registerEmptyDiagHandler(getLLVMContext());
// Assign the target information to the module.
llmodule_->setDataLayout(getTargetMachine().createDataLayout());
// Initialize the debug information emission.
initDebugInfo();
}
/// \returns the LLVM type corresponding to the type of elements stored in \p
/// val.
llvm::Type *LLVMIRGen::getElementType(llvm::IRBuilder<> &builder,
const Value *val) {
switch (val->getElementType()) {
case ElemKind::Int64ITy:
return builder.getInt64Ty();
case ElemKind::FloatTy:
return builder.getFloatTy();
case ElemKind::Float16Ty:
llvm_unreachable("Not implemented");
case ElemKind::BFloat16Ty:
llvm_unreachable("Not implemented");
case ElemKind::Float64Ty:
return builder.getDoubleTy();
case ElemKind::Int8QTy:
return builder.getInt8Ty();
case ElemKind::UInt8QTy:
llvm_unreachable("Not implemented");
case ElemKind::Int16QTy:
return builder.getInt16Ty();
case ElemKind::Int32QTy:
return builder.getInt32Ty();
case ElemKind::Int64QTy:
return builder.getInt64Ty();
case ElemKind::UInt8ITy:
return builder.getInt8Ty();
case ElemKind::Int32ITy:
return builder.getInt32Ty();
case ElemKind::UInt8FusedQTy:
return builder.getInt8Ty();
case ElemKind::UInt8FusedFP16QTy:
return builder.getInt8Ty();
case ElemKind::UInt4FusedFP16QTy:
return builder.getInt8Ty();
case ElemKind::UInt4FusedQTy:
return builder.getInt8Ty();
case ElemKind::BoolTy:
static_assert(sizeof(bool) == sizeof(int8_t),
"Bool is expected to be the same size as int8.");
return builder.getInt8Ty();
}
return nullptr;
}
void LLVMIRGen::performCodeGen() {
// Create the entry function into the LLVM module.
auto int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
auto dimTPtrTy = llvm::Type::getIntNPtrTy(getLLVMContext(), DIM_T_BITWIDTH);
// The entry point has the following API:
// int entry(uint8_t *baseConstantWeightVars,
// uint8_t *baseInoutWeightVars,
// uint8_t *baseActivations,
// dim_t *offsets);
llvm::Type *retTy =
llvm::Type::getIntNTy(getLLVMContext(), getLibjitIntWidth());
llvm::FunctionType *jitFuncTy = llvm::FunctionType::get(
retTy, {int8PtrTy, int8PtrTy, int8PtrTy, dimTPtrTy}, false);
llvmF_ = llvm::Function::Create(jitFuncTy, llvm::Function::ExternalLinkage,
"main", llmodule_.get());
emittedLLVMFunctions_.emplace_back(llvmF_);
// Setup the entry basic block and initialize the IR builder.
llvm::BasicBlock *entry_bb =
llvm::BasicBlock::Create(getLLVMContext(), "entry", llvmF_);
builder_ = glow::make_unique<llvm::IRBuilder<>>(entry_bb);
// Terminate the function with a return instruction.
auto zero = builder_->getIntN(getLibjitIntWidth(), 0);
auto *ret = builder_->CreateRet(zero);
// Emit all the code before the retrun instruction.
builder_->SetInsertPoint(ret);
if (F_) {
instrNumbering_.reset(new InstructionNumbering(*F_));
}
generateFunctionDebugInfo();
loadBaseAddresses(*builder_);
generateLLVMIRForModule(*builder_);
}
void LLVMIRGen::finishCodeGen() {
if (dumpLLVMIR) {
llvm::outs() << "LLVM module before optimizations:\n";
dump();
}
// Perform verification if no debug info is being emitted.
// Otherwise, the verification is performed later by
// generateDebugInfo, once the debug info emission is finalized.
// Also disable verification when an external compiler is used
// to build the model to avoid IR compatibility issues.
if (!emitDebugInfo && llvmCompiler.empty()) {
// Perform verification, but ignore any debug info errors for now.
// Debug info errors will be checked later by generateDebugInfo.
bool brokenDebugInfo = false;
(void)brokenDebugInfo;
assert(!llvm::verifyModule(getModule(), &llvm::errs(), &brokenDebugInfo) &&
"LLVM module verification error");
}
// Optimize the module.
optimizeLLVMModule(&getModule(), getTargetMachine());
// Generate debug information.
generateModuleDebugInfo();
if (dumpLLVMIR) {
llvm::outs() << "LLVM module after optimizations:\n";
dump();
}
if (dumpLLVMAsm) {
llvm::SmallVector<char, 0> asmBuffer;
llvm::raw_svector_ostream asmStream(asmBuffer);
llvm::legacy::PassManager PM;
#if FACEBOOK_INTERNAL && LLVM_VERSION_MAJOR < 8
getTargetMachine().addPassesToEmitFile(
PM, asmStream, llvm::TargetMachine::CodeGenFileType::CGFT_AssemblyFile);
#elif LLVM_VERSION_MAJOR < 10
getTargetMachine().addPassesToEmitFile(
PM, asmStream, nullptr,
llvm::TargetMachine::CodeGenFileType::CGFT_AssemblyFile);
#else
getTargetMachine().addPassesToEmitFile(PM, asmStream, nullptr,
llvm::CGFT_AssemblyFile);
#endif
PM.run(*llmodule_);
llvm::outs() << asmStream.str();
}
}
llvm::Type *LLVMIRGen::getLLVMPtrType(glow::ElemKind kind) {
llvm::Type *T = nullptr;
switch (kind) {
case ElemKind::FloatTy:
T = llvm::Type::getFloatPtrTy(getLLVMContext());
break;
case ElemKind::Float16Ty:
T = llvm::Type::getInt16PtrTy(getLLVMContext());
break;
case ElemKind::BFloat16Ty:
T = llvm::Type::getInt16PtrTy(getLLVMContext());
break;
case ElemKind::Int8QTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::UInt8QTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::Int16QTy:
T = llvm::Type::getInt16PtrTy(getLLVMContext());
break;
case ElemKind::Int32QTy:
T = llvm::Type::getInt32PtrTy(getLLVMContext());
break;
case ElemKind::Int64QTy:
T = llvm::Type::getInt64PtrTy(getLLVMContext());
break;
case ElemKind::Int64ITy:
T = llvm::Type::getInt64PtrTy(getLLVMContext());
break;
case ElemKind::Int32ITy:
T = llvm::Type::getInt32PtrTy(getLLVMContext());
break;
case ElemKind::UInt8ITy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::UInt8FusedQTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::UInt8FusedFP16QTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::UInt4FusedFP16QTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::UInt4FusedQTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::BoolTy:
T = llvm::Type::getInt8PtrTy(getLLVMContext());
break;
case ElemKind::Float64Ty:
T = llvm::Type::getDoubleTy(getLLVMContext());
break;
default:
LOG(FATAL) << "Unsupported element type: "
<< Type::getElementName(kind).str();
}
return T;
}
llvm::Value *LLVMIRGen::emitValueAddress(llvm::IRBuilder<> &builder,
const glow::Value *val) {
assert(allocationsInfo_.allocatedAddress_.count(val) &&
"Value address was not allocated");
assert(allocationsInfo_.valueNumbers_.count(val));
auto &kindAndValue = allocationsInfo_.valueNumbers_[val];
// Get the required base address.
llvm::Value *baseAddrValue = nullptr;
switch (kindAndValue.first) {
case AllocationsInfo::ValueKind::Activation:
baseAddrValue = baseActivationsAddr_;
break;
case AllocationsInfo::ValueKind::ConstantWeight:
baseAddrValue = baseConstantWeightVarsAddr_;
break;
case AllocationsInfo::ValueKind::MutableWeight:
baseAddrValue = baseMutableWeightVarsAddr_;
break;
}
// Use relative addressing.
// Get offset.
auto sizeTTy = builder.getIntNTy(getLibjitSizeTWidth());
auto dimTTy = builder.getIntNTy(DIM_T_BITWIDTH);
auto valueIdx = llvm::ConstantInt::get(dimTTy, kindAndValue.second);
auto offsetAddr = builder.CreateGEP(dimTTy, offsetsArray_, valueIdx);
auto offsetValue = builder.CreateLoad(dimTTy, offsetAddr);
// Add offset to the base address.
llvm::Value *addr = builder.CreateAdd(
baseAddrValue, builder.CreateZExt(offsetValue, sizeTTy));
return builder.CreateIntToPtr(addr, getLLVMPtrType(val->getElementType()));
}
llvm::Value *
LLVMIRGen::emitConstOffsetsArray(llvm::IRBuilder<> &builder,
const AllocationsInfo &allocationsInfo) {
constexpr const char *offsetsArrayName = "offsetsArray";
auto dimTType = builder.getIntNTy(DIM_T_BITWIDTH);
std::vector<llvm::Constant *> elems(allocationsInfo.valueNumbers_.size());
dim_t maxOffset = 0;
for (auto &I : allocationsInfo.valueNumbers_) {
auto *V = I.first;
auto offset = I.second.second;
elems[offset] = llvm::ConstantInt::get(
dimTType, allocationsInfo.allocatedAddress_.lookup(V));
maxOffset = std::max(maxOffset, (dim_t)offset);
}
elems.resize(maxOffset + 1);
auto *arr = llvm::ConstantArray::get(
llvm::ArrayType::get(dimTType, elems.size()), elems);
// Ensure that the same casted global variable is used for the equivalent
// const arrays. This is important for the later function specialization pass.
// LLVM does not do it automatically for this code pattern involving global
// variables. It also reduces the number of variables.
auto &constArrayVar = constArrayPtrs_[arr];
auto oldG =
getModule().getGlobalVariable(offsetsArrayName, /* allowInternal */ true);
if (constArrayVar && constArrayVar->getType() == dimTType->getPointerTo()) {
return constArrayVar;
}
if (oldG) {
oldG->setName("offsetsArrayOld");
}
auto *M = builder.GetInsertBlock()->getModule();
auto *G = new llvm::GlobalVariable(*M, arr->getType(), true,
llvm::GlobalValue::InternalLinkage, arr,
offsetsArrayName);
constArrayVar = builder.CreateBitCast(G, dimTType->getPointerTo());
if (oldG) {
// Replace the old offsetsArray by the new one and remove the old.
oldG->replaceAllUsesWith(G);
oldG->eraseFromParent();
}
return constArrayVar;
}
llvm::Value *LLVMIRGen::emitConstI32Array(llvm::IRBuilder<> &builder,
llvm::ArrayRef<int32_t> vals) {
std::vector<llvm::Constant *> elems;
for (auto I : vals) {
elems.push_back(builder.getInt32(I));
}
return emitConstArray(builder, elems, builder.getInt32Ty());
}
llvm::Value *LLVMIRGen::emitConstFloatArray(llvm::IRBuilder<> &builder,
llvm::ArrayRef<float> vals) {
std::vector<llvm::Constant *> elems;
for (auto I : vals) {
elems.push_back(llvm::ConstantFP::get(
llvm::Type::getFloatTy(getLLVMContext()), (float)I));
}
return emitConstArray(builder, elems,
llvm::Type::getFloatTy(getLLVMContext()));
}
llvm::Value *LLVMIRGen::emitConstArray(llvm::IRBuilder<> &builder,
llvm::ArrayRef<llvm::Constant *> vals,
llvm::Type *elemTy) {
std::vector<llvm::Constant *> elems;
for (auto I : vals) {
elems.push_back(cast<llvm::Constant>(builder.CreateBitCast(I, elemTy)));
}
auto *arr = llvm::ConstantArray::get(
llvm::ArrayType::get(elemTy, elems.size()), elems);
// Ensure that the same casted global variable is used for the equivalent
// const arrays. This is important for the later function specialization pass.
// LLVM does not do it automatically for this code pattern involving global
// variables. It also reduces the number of variables.
auto &constArrayVar = constArrayPtrs_[arr];
if (constArrayVar && constArrayVar->getType() == elemTy->getPointerTo())
return constArrayVar;
auto *M = builder.GetInsertBlock()->getModule();
auto *G = new llvm::GlobalVariable(*M, arr->getType(), true,
llvm::GlobalValue::InternalLinkage, arr);
constArrayVar = builder.CreateBitCast(G, elemTy->getPointerTo());
return constArrayVar;
}
void LLVMIRGen::emitArrayStore(llvm::IRBuilder<> &builder,
llvm::ArrayRef<llvm::Value *> vals,
llvm::Value *basePtr, unsigned baseIdx) {
for (size_t idx = 0, end = vals.size(); idx < end; ++idx) {
assert(vals[idx]->getType()->getPointerTo() == basePtr->getType() &&
"Mismatch between pointer and value type!");
auto *storeIdx = builder.getInt32(idx + baseIdx);
auto *storeAddr = builder.CreateGEP(
basePtr->getType()->getPointerElementType(), basePtr, storeIdx);
builder.CreateStore(vals[idx], storeAddr);
}
}
llvm::Value *LLVMIRGen::emitValueDims(llvm::IRBuilder<> &builder,
const glow::Value *val) {
auto dims = val->dims();
return emitConstDimTArray(builder, dims);
}
template <class InstructionTy>
llvm::Value *LLVMIRGen::emitConstFloatActivationArgs(llvm::IRBuilder<> &builder,
const InstructionTy *I) {
return emitConstFloatArray(builder, I->getFusedActivationArgs());
}
template <class InstructionTy>
llvm::Value *LLVMIRGen::emitConstQuantActivationArgs(llvm::IRBuilder<> &builder,
const InstructionTy *I) {
auto actArgsF = I->getFusedActivationArgs();
std::vector<int32_t> actArgsQ;
auto *destTy = I->getDest()->getType();
switch (I->getFusedActivation()) {
case FusedActivation::NONE:
case FusedActivation::RELU:
assert(actArgsF.size() == 0 && "Invalid number of activation parameters!");
break;
case FusedActivation::CLIP: {
// For Clip we quantize min/max using the output quantization params.
assert(actArgsF.size() == 2 &&
"Invalid number of parameters for fused Clip activation!");
float minF = actArgsF[0];
float maxF = actArgsF[1];
TensorQuantizationParams TQP{destTy->getScale(), destTy->getOffset()};
int32_t minQ = quantization::quantize<int32_t>(minF, TQP);
int32_t maxQ = quantization::quantize<int32_t>(maxF, TQP);
actArgsQ.push_back(minQ);
actArgsQ.push_back(maxQ);
break;
}
case FusedActivation::SIGMOID:
LOG(FATAL) << "Fused Sigmoid for quantized type not supported!";
break;
case FusedActivation::TANH:
LOG(FATAL) << "Fused Tanh for quantized type not supported!";
break;
case FusedActivation::LEAKY_RELU: {
// For LeakyRelu we transform the alpha parameter into pre/post/scale.
assert(actArgsF.size() == 1 &&
"Invalid number of parameters for fused LeakyRelu activation!");
float alpha = actArgsF[0];
auto alphaScaleParam = quantization::quantizeScaleOffset32To8(alpha, 0);
actArgsQ.push_back(alphaScaleParam.pre);
actArgsQ.push_back(alphaScaleParam.post);
actArgsQ.push_back(alphaScaleParam.scale);
break;
}
default:
LOG(FATAL) << "Unsupported fused activation type!";
}
return emitConstI32Array(builder, actArgsQ);
}
llvm::Value *LLVMIRGen::emitValueSize(llvm::IRBuilder<> &builder,
const glow::Value *val) {
return builder.getIntN(DIM_T_BITWIDTH, val->size());
}
llvm::Value *LLVMIRGen::emitConstF32(llvm::IRBuilder<> &builder, float val) {
return llvm::ConstantFP::get(llvm::Type::getFloatTy(getLLVMContext()), val);
}
llvm::Value *LLVMIRGen::emitConstF64(llvm::IRBuilder<> &builder, double val) {
return llvm::ConstantFP::get(llvm::Type::getDoubleTy(getLLVMContext()), val);
}
llvm::Value *LLVMIRGen::emitConstI64(llvm::IRBuilder<> &builder, int64_t val) {
return builder.getInt64(val);
}
llvm::Value *LLVMIRGen::emitConstI32(llvm::IRBuilder<> &builder, int32_t val) {
return builder.getInt32(val);
}
llvm::Value *LLVMIRGen::emitConstI16(llvm::IRBuilder<> &builder, int16_t val) {
return builder.getInt16(val);
}
llvm::Value *LLVMIRGen::emitConstI8(llvm::IRBuilder<> &builder, int8_t val) {
return builder.getInt8(val);
}
llvm::Value *LLVMIRGen::emitConstI1(llvm::IRBuilder<> &builder, bool val) {
return builder.getInt1(val);
}
llvm::Value *LLVMIRGen::emitConstSizeT(llvm::IRBuilder<> &builder, size_t val) {
return builder.getIntN(getLibjitSizeTWidth(), val);
}
llvm::Value *LLVMIRGen::emitConstDimT(llvm::IRBuilder<> &builder, dim_t val) {
return builder.getIntN(sizeof(dim_t) * 8, val);
}
llvm::Value *LLVMIRGen::emitConst(llvm::IRBuilder<> &builder, float val,
glow::ElemKind kind) {
switch (kind) {
case ElemKind::FloatTy:
return llvm::ConstantFP::get(llvm::Type::getFloatTy(getLLVMContext()), val);
case ElemKind::Float16Ty:
llvm_unreachable("Not implemented");
case ElemKind::BFloat16Ty:
llvm_unreachable("Not implemented");
case ElemKind::Float64Ty:
return llvm::ConstantFP::get(llvm::Type::getDoubleTy(getLLVMContext()),
val);
case ElemKind::Int64ITy:
return builder.getInt64(static_cast<int64_t>(val));
case ElemKind::Int8QTy:
return builder.getInt8(static_cast<int8_t>(val));
case ElemKind::UInt8QTy:
llvm_unreachable("Not implemented");
case ElemKind::Int16QTy:
return builder.getInt16(static_cast<int16_t>(val));
case ElemKind::Int32QTy:
return builder.getInt32(static_cast<int32_t>(val));
case ElemKind::UInt8ITy:
return builder.getInt8(static_cast<uint8_t>(val));
case ElemKind::Int64QTy:
return builder.getInt64(static_cast<int64_t>(val));
case ElemKind::Int32ITy:
return builder.getInt32(static_cast<int32_t>(val));
case ElemKind::UInt8FusedQTy:
return builder.getInt8(static_cast<int8_t>(val));
case ElemKind::UInt8FusedFP16QTy:
return builder.getInt8(static_cast<int8_t>(val));
case ElemKind::UInt4FusedFP16QTy:
return builder.getInt8(static_cast<int8_t>(val));
case ElemKind::UInt4FusedQTy:
return builder.getInt8(static_cast<int8_t>(val));
case ElemKind::BoolTy:
return builder.getInt8(static_cast<int8_t>(val));
}
llvm_unreachable("Unknown element type");
}
llvm::Value *LLVMIRGen::emitStringConst(llvm::IRBuilder<> &builder,
llvm::StringRef str) {
llvm::Constant *constStrArray =
llvm::ConstantDataArray::getString(getLLVMContext(), str, true);
llvm::GlobalVariable *gvarStr = new llvm::GlobalVariable(
*llmodule_, constStrArray->getType(), true,
llvm::GlobalValue::PrivateLinkage, constStrArray, ".str");
#if LLVM_VERSION_MAJOR >= 10
gvarStr->setAlignment(llvm::MaybeAlign(1));
#else
gvarStr->setAlignment(1);
#endif
// Add unnamed_addr attribute to enable constmerge pass.
gvarStr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
return builder.CreateBitCast(gvarStr, builder.getInt8PtrTy());
}
void LLVMIRGen::markArgAsUnspecialized(llvm::Value *val) {
dontSpecializeArgsSet_.insert(val);
}
static std::string createName(const std::string &name, ElemKind elemTy) {
switch (elemTy) {
case ElemKind::FloatTy:
return name + "_f";
case ElemKind::Float16Ty:
return name + "_fp16";
case ElemKind::BFloat16Ty:
return name + "_bfloat16";
case ElemKind::Int8QTy:
return name + "_i8";
case ElemKind::Int16QTy:
return name + "_i16";
case ElemKind::Int32QTy:
return name + "_i32";
case ElemKind::Int32ITy:
return name + "_i32";
case ElemKind::Int64ITy:
return name + "_u";
case ElemKind::BoolTy:
return name + "_b";
default:
LOG(FATAL) << "Unsupported element type: "
<< Type::getElementName(elemTy).str();
}
}
void LLVMIRGen::initLLVMFunctionNameToMangledNameMap() {
CHECK(llvmFunctionNameToMangledName_.empty());
constexpr size_t maxFnBaseNameLen = 4096;
char fnNameBuf[maxFnBaseNameLen];
// Build a map from names to the list of matching mangled names.
for (llvm::Function &F : getModule()) {
auto mangledName = F.getName().str();
llvm::ItaniumPartialDemangler Mangler;
if (Mangler.partialDemangle(mangledName.c_str())) {
// Could not demangle.
continue;
}
size_t fnNameLen = maxFnBaseNameLen;
size_t fnContextLen = maxFnBaseNameLen;
// Skip C++ functions that have names like a::b::c. It helps to avoid name
// conflicts with kernels that may be called just c and conflict with C++
// functions.
fnNameBuf[0] = '\0';
char *contextNamePtr =
Mangler.getFunctionDeclContextName(fnNameBuf, &fnContextLen);
if (contextNamePtr && fnContextLen != 0 && contextNamePtr[0]) {
continue;
}
fnNameBuf[0] = '\0';
char *demangledNamePtr = Mangler.getFunctionBaseName(fnNameBuf, &fnNameLen);
if (!demangledNamePtr || fnNameLen == 0) {
continue;
}
std::string demangledFnName(demangledNamePtr);
// Add the information about the mapping for a specific function.
// Remember the mapping between the function name and its mangled name.
if (!llvmFunctionNameToMangledName_.count(demangledFnName)) {
llvmFunctionNameToMangledName_.insert({demangledFnName, {}});
}
llvmFunctionNameToMangledName_[demangledFnName].push_back(mangledName);
}
DEBUG_GLOW({
// Dump the map for debugging purposes.
llvm::dbgs() << "Mapping between function names and matching LLVM function "
"names in the module:\n";
for (auto &kv : llvmFunctionNameToMangledName_) {
auto &nonMangledName = kv.first;
auto &mangledNames = kv.second;
llvm::dbgs() << nonMangledName << " -> ";
for (auto &mangledName : mangledNames) {
llvm::dbgs() << mangledName << "; ";
}
llvm::dbgs() << "\n";
}
llvm::dbgs() << "\n";
llvm::dbgs().flush();
});
}
llvm::Function *LLVMIRGen::getFunctionByName(const std::string &name) {
// Initialize if this is the first time getFunctionByName is invoked.
if (llvmFunctionNameToMangledName_.empty()) {
initLLVMFunctionNameToMangledNameMap();
}
auto lookupFunctionByName = [&]() -> llvm::Function * {
auto it = llvmFunctionNameToMangledName_.find(name);
if (it != llvmFunctionNameToMangledName_.end()) {
// Check if there is a conflict as there are multiple functions with the
// same name. This is likely due to having multiple C++ functions with the
// same name, but different types of arguments.
auto &mangledNames = it->second;
if (mangledNames.size() > 1) {
LOG(INFO) << "Multiple functions matching name: " << name << "\n";
for (auto &mangledName : mangledNames) {
LOG(INFO) << "\t" << mangledName << "\n";
}
}
CHECK_EQ(mangledNames.size(), 1)
<< "Expected only one matching function for " << name;
auto fullName = mangledNames.front();
auto *F = getModule().getFunction(fullName);
if (!F) {
// TODO: Remove the function name from the map.
}
return F;
}
// No match found.
auto *F = getModule().getFunction(name);
if (F) {
// Update the map with the new function.
if (!llvmFunctionNameToMangledName_.count(name)) {
llvmFunctionNameToMangledName_.insert({name, {}});
}
llvmFunctionNameToMangledName_[name].push_back(name);
}
return F;
};
// Check if the full function name is known already.
auto *F = lookupFunctionByName();
return F;
}
llvm::Function *
LLVMIRGen::getFunction(const std::string &name,
llvm::ArrayRef<glow::ElemKind> elemTyArray) {
auto strName = name;
for (auto elTy : elemTyArray) {
strName = createName(strName, elTy);
}
return getFunction(strName);
}
llvm::Function *LLVMIRGen::getFunction(const std::string &name) {
auto *F = getFunctionByName("libjit_" + name);
CHECK(F) << "Unable to load the function: " << name;
return F;
}
llvm::Function *LLVMIRGen::getFunction(const std::string &name,
ElemKind elemTy) {
return getFunction(name, llvm::ArrayRef<ElemKind>{elemTy});
}
llvm::Function *LLVMIRGen::getLLVMFunction() { return llvmF_; }
llvm::CallInst *LLVMIRGen::createCall(llvm::IRBuilder<> &builder,
llvm::Function *callee,
llvm::ArrayRef<llvm::Value *> args,
bool checked) {
llvm::CallInst *result = builder.CreateCall(callee, args);
#ifndef NDEBUG
llvm::FunctionType *FTy = callee->getFunctionType();
if (args.size() != FTy->getNumParams() &&
!(FTy->isVarArg() && args.size() > FTy->getNumParams())) {
result->print(llvm::errs());
llvm::errs() << "\n";
CHECK_LT(FTy->getNumParams(), args.size())
<< "Calling a function with bad signature: wrong number of arguments.";
}
for (unsigned i = 0; i != args.size(); ++i) {
if (i >= FTy->getNumParams()) {
continue;
}
if (FTy->getParamType(i) != args[i]->getType()) {
result->print(llvm::errs());
llvm::errs() << "\n";
llvm::errs() << "Expected type: ";
FTy->getParamType(i)->print(llvm::errs());
llvm::errs() << "at index " << i << "\n";
llvm::errs() << "Provided type: ";
args[i]->print(llvm::errs());
llvm::errs() << "at index " << i << "\n";
CHECK_EQ(FTy->getParamType(i), args[i]->getType())
<< "Calling a function with a bad signature: argument type mismatch.";
}
}
#endif
if (!checked || !callee->getReturnType()->isIntegerTy()) {
return result;
}
// Check if callee returned an error, i.e. non-zero result.
// Emit a return with this error code in this case.
auto *zero = builder.getIntN(result->getType()->getIntegerBitWidth(), 0);
auto *cond = builder.CreateICmpNE(result, zero);
auto insertionPoint = builder.GetInsertPoint();
auto *currentBB = result->getParent();
auto *falseBB =
currentBB->splitBasicBlock(builder.GetInsertPoint(), "cont_bb");
auto *trueBB = llvm::BasicBlock::Create(getLLVMContext(), "error_bb",
result->getFunction());
builder.SetInsertPoint(currentBB->getTerminator());
builder.CreateCondBr(cond, trueBB, falseBB);
currentBB->getTerminator()->eraseFromParent();
builder.SetInsertPoint(trueBB);
auto *castedResult =
builder.CreateBitCast(result, builder.getIntNTy(getLibjitIntWidth()));
builder.CreateRet(castedResult);
builder.SetInsertPoint(falseBB, insertionPoint);
builder.SetInsertPoint(falseBB->getTerminator());
return result;
}
llvm::CallInst *
LLVMIRGen::createCheckedCall(llvm::IRBuilder<> &builder, llvm::Function *callee,
llvm::ArrayRef<llvm::Value *> args) {
return createCall(builder, callee, args, /* checked */ true);
}
llvm::CallInst *
LLVMIRGen::createUncheckedCall(llvm::IRBuilder<> &builder,
llvm::Function *callee,
llvm::ArrayRef<llvm::Value *> args) {
return createCall(builder, callee, args, /* checked */ false);
}
std::pair<llvm::BasicBlock *, llvm::BasicBlock *>
LLVMIRGen::createLoop(llvm::IRBuilder<> &builder, llvm::LLVMContext &ctx,
llvm::Value *numElements) const {
auto dimTTy = builder.getIntNTy(DIM_T_BITWIDTH);
auto *initVal = llvm::ConstantInt::get(dimTTy, 0);
// Make the new basic block for the loop header. Insert it after current
// block.
llvm::Function *func = builder.GetInsertBlock()->getParent();
auto *preheaderBB = builder.GetInsertBlock();
auto *loopBB = llvm::BasicBlock::Create(ctx, "loop", func);
// Insert a jump from the current block to the loopBB.
builder.CreateBr(loopBB);