-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
LLVMTypes.cpp
930 lines (797 loc) · 34.2 KB
/
LLVMTypes.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
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the types for the LLVM dialect in MLIR. These MLIR types
// correspond to the LLVM IR type system.
//
//===----------------------------------------------------------------------===//
#include "TypeDetail.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/TypeSupport.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/TypeSize.h"
using namespace mlir;
using namespace mlir::LLVM;
constexpr const static unsigned kBitsInByte = 8;
//===----------------------------------------------------------------------===//
// Array type.
//===----------------------------------------------------------------------===//
bool LLVMArrayType::isValidElementType(Type type) {
return !type.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType,
LLVMFunctionType, LLVMTokenType, LLVMScalableVectorType>();
}
LLVMArrayType LLVMArrayType::get(Type elementType, unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::get(elementType.getContext(), elementType, numElements);
}
LLVMArrayType
LLVMArrayType::getChecked(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::getChecked(emitError, elementType.getContext(), elementType,
numElements);
}
Type LLVMArrayType::getElementType() const { return getImpl()->elementType; }
unsigned LLVMArrayType::getNumElements() const {
return getImpl()->numElements;
}
LogicalResult
LLVMArrayType::verify(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned numElements) {
if (!isValidElementType(elementType))
return emitError() << "invalid array element type: " << elementType;
return success();
}
unsigned LLVMArrayType::getTypeSizeInBits(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
return kBitsInByte * getTypeSize(dataLayout, params);
}
unsigned LLVMArrayType::getTypeSize(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
return llvm::alignTo(dataLayout.getTypeSize(getElementType()),
dataLayout.getTypeABIAlignment(getElementType())) *
getNumElements();
}
unsigned LLVMArrayType::getABIAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
return dataLayout.getTypeABIAlignment(getElementType());
}
unsigned
LLVMArrayType::getPreferredAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
return dataLayout.getTypePreferredAlignment(getElementType());
}
//===----------------------------------------------------------------------===//
// Function type.
//===----------------------------------------------------------------------===//
bool LLVMFunctionType::isValidArgumentType(Type type) {
return !type.isa<LLVMVoidType, LLVMFunctionType>();
}
bool LLVMFunctionType::isValidResultType(Type type) {
return !type.isa<LLVMFunctionType, LLVMMetadataType, LLVMLabelType>();
}
LLVMFunctionType LLVMFunctionType::get(Type result, ArrayRef<Type> arguments,
bool isVarArg) {
assert(result && "expected non-null result");
return Base::get(result.getContext(), result, arguments, isVarArg);
}
LLVMFunctionType
LLVMFunctionType::getChecked(function_ref<InFlightDiagnostic()> emitError,
Type result, ArrayRef<Type> arguments,
bool isVarArg) {
assert(result && "expected non-null result");
return Base::getChecked(emitError, result.getContext(), result, arguments,
isVarArg);
}
LLVMFunctionType LLVMFunctionType::clone(TypeRange inputs,
TypeRange results) const {
assert(results.size() == 1 && "expected a single result type");
return get(results[0], llvm::to_vector(inputs), isVarArg());
}
Type LLVMFunctionType::getReturnType() { return getImpl()->getReturnType(); }
ArrayRef<Type> LLVMFunctionType::getReturnTypes() {
return getImpl()->getReturnType();
}
unsigned LLVMFunctionType::getNumParams() {
return getImpl()->getArgumentTypes().size();
}
Type LLVMFunctionType::getParamType(unsigned i) {
return getImpl()->getArgumentTypes()[i];
}
bool LLVMFunctionType::isVarArg() const { return getImpl()->isVariadic(); }
ArrayRef<Type> LLVMFunctionType::getParams() {
return getImpl()->getArgumentTypes();
}
LogicalResult
LLVMFunctionType::verify(function_ref<InFlightDiagnostic()> emitError,
Type result, ArrayRef<Type> arguments, bool) {
if (!isValidResultType(result))
return emitError() << "invalid function result type: " << result;
for (Type arg : arguments)
if (!isValidArgumentType(arg))
return emitError() << "invalid function argument type: " << arg;
return success();
}
//===----------------------------------------------------------------------===//
// Pointer type.
//===----------------------------------------------------------------------===//
bool LLVMPointerType::isValidElementType(Type type) {
if (!type)
return true;
return isCompatibleOuterType(type)
? !type.isa<LLVMVoidType, LLVMTokenType, LLVMMetadataType,
LLVMLabelType>()
: type.isa<PointerElementTypeInterface>();
}
LLVMPointerType LLVMPointerType::get(Type pointee, unsigned addressSpace) {
assert(pointee && "expected non-null subtype, pass the context instead if "
"the opaque pointer type is desired");
return Base::get(pointee.getContext(), pointee, addressSpace);
}
LLVMPointerType LLVMPointerType::get(MLIRContext *context,
unsigned addressSpace) {
return Base::get(context, Type(), addressSpace);
}
LLVMPointerType
LLVMPointerType::getChecked(function_ref<InFlightDiagnostic()> emitError,
Type pointee, unsigned addressSpace) {
return Base::getChecked(emitError, pointee.getContext(), pointee,
addressSpace);
}
LLVMPointerType
LLVMPointerType::getChecked(function_ref<InFlightDiagnostic()> emitError,
MLIRContext *context, unsigned addressSpace) {
return Base::getChecked(emitError, context, Type(), addressSpace);
}
Type LLVMPointerType::getElementType() const { return getImpl()->pointeeType; }
bool LLVMPointerType::isOpaque() const { return !getImpl()->pointeeType; }
unsigned LLVMPointerType::getAddressSpace() const {
return getImpl()->addressSpace;
}
LogicalResult
LLVMPointerType::verify(function_ref<InFlightDiagnostic()> emitError,
Type pointee, unsigned) {
if (!isValidElementType(pointee))
return emitError() << "invalid pointer element type: " << pointee;
return success();
}
namespace {
/// The positions of different values in the data layout entry.
enum class DLEntryPos { Size = 0, Abi = 1, Preferred = 2, Address = 3 };
} // namespace
constexpr const static unsigned kDefaultPointerSizeBits = 64;
constexpr const static unsigned kDefaultPointerAlignment = 8;
/// Returns the value that corresponds to named position `pos` from the
/// attribute `attr` assuming it's a dense integer elements attribute.
static unsigned extractPointerSpecValue(Attribute attr, DLEntryPos pos) {
return attr.cast<DenseIntElementsAttr>()
.getValues<unsigned>()[static_cast<unsigned>(pos)];
}
/// Returns the part of the data layout entry that corresponds to `pos` for the
/// given `type` by interpreting the list of entries `params`. For the pointer
/// type in the default address space, returns the default value if the entries
/// do not provide a custom one, for other address spaces returns None.
static Optional<unsigned>
getPointerDataLayoutEntry(DataLayoutEntryListRef params, LLVMPointerType type,
DLEntryPos pos) {
// First, look for the entry for the pointer in the current address space.
Attribute currentEntry;
for (DataLayoutEntryInterface entry : params) {
if (!entry.isTypeEntry())
continue;
if (entry.getKey().get<Type>().cast<LLVMPointerType>().getAddressSpace() ==
type.getAddressSpace()) {
currentEntry = entry.getValue();
break;
}
}
if (currentEntry) {
return extractPointerSpecValue(currentEntry, pos) /
(pos == DLEntryPos::Size ? 1 : kBitsInByte);
}
// If not found, and this is the pointer to the default memory space, assume
// 64-bit pointers.
if (type.getAddressSpace() == 0) {
return pos == DLEntryPos::Size ? kDefaultPointerSizeBits
: kDefaultPointerAlignment;
}
return llvm::None;
}
unsigned
LLVMPointerType::getTypeSizeInBits(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
if (Optional<unsigned> size =
getPointerDataLayoutEntry(params, *this, DLEntryPos::Size))
return *size;
// For other memory spaces, use the size of the pointer to the default memory
// space.
if (isOpaque())
return dataLayout.getTypeSizeInBits(get(getContext()));
return dataLayout.getTypeSizeInBits(get(getElementType()));
}
unsigned LLVMPointerType::getABIAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
if (Optional<unsigned> alignment =
getPointerDataLayoutEntry(params, *this, DLEntryPos::Abi))
return *alignment;
if (isOpaque())
return dataLayout.getTypeABIAlignment(get(getContext()));
return dataLayout.getTypeABIAlignment(get(getElementType()));
}
unsigned
LLVMPointerType::getPreferredAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
if (Optional<unsigned> alignment =
getPointerDataLayoutEntry(params, *this, DLEntryPos::Preferred))
return *alignment;
if (isOpaque())
return dataLayout.getTypePreferredAlignment(get(getContext()));
return dataLayout.getTypePreferredAlignment(get(getElementType()));
}
bool LLVMPointerType::areCompatible(DataLayoutEntryListRef oldLayout,
DataLayoutEntryListRef newLayout) const {
for (DataLayoutEntryInterface newEntry : newLayout) {
if (!newEntry.isTypeEntry())
continue;
unsigned size = kDefaultPointerSizeBits;
unsigned abi = kDefaultPointerAlignment;
auto newType = newEntry.getKey().get<Type>().cast<LLVMPointerType>();
const auto *it =
llvm::find_if(oldLayout, [&](DataLayoutEntryInterface entry) {
if (auto type = entry.getKey().dyn_cast<Type>()) {
return type.cast<LLVMPointerType>().getAddressSpace() ==
newType.getAddressSpace();
}
return false;
});
if (it == oldLayout.end()) {
llvm::find_if(oldLayout, [&](DataLayoutEntryInterface entry) {
if (auto type = entry.getKey().dyn_cast<Type>()) {
return type.cast<LLVMPointerType>().getAddressSpace() == 0;
}
return false;
});
}
if (it != oldLayout.end()) {
size = extractPointerSpecValue(*it, DLEntryPos::Size);
abi = extractPointerSpecValue(*it, DLEntryPos::Abi);
}
Attribute newSpec = newEntry.getValue().cast<DenseIntElementsAttr>();
unsigned newSize = extractPointerSpecValue(newSpec, DLEntryPos::Size);
unsigned newAbi = extractPointerSpecValue(newSpec, DLEntryPos::Abi);
if (size != newSize || abi < newAbi || abi % newAbi != 0)
return false;
}
return true;
}
LogicalResult LLVMPointerType::verifyEntries(DataLayoutEntryListRef entries,
Location loc) const {
for (DataLayoutEntryInterface entry : entries) {
if (!entry.isTypeEntry())
continue;
auto key = entry.getKey().get<Type>().cast<LLVMPointerType>();
auto values = entry.getValue().dyn_cast<DenseIntElementsAttr>();
if (!values || (values.size() != 3 && values.size() != 4)) {
return emitError(loc)
<< "expected layout attribute for " << entry.getKey().get<Type>()
<< " to be a dense integer elements attribute with 3 or 4 "
"elements";
}
if (key.getElementType() && !key.getElementType().isInteger(8)) {
return emitError(loc) << "unexpected layout attribute for pointer to "
<< key.getElementType();
}
if (extractPointerSpecValue(values, DLEntryPos::Abi) >
extractPointerSpecValue(values, DLEntryPos::Preferred)) {
return emitError(loc) << "preferred alignment is expected to be at least "
"as large as ABI alignment";
}
}
return success();
}
//===----------------------------------------------------------------------===//
// Struct type.
//===----------------------------------------------------------------------===//
bool LLVMStructType::isValidElementType(Type type) {
return !type.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType,
LLVMFunctionType, LLVMTokenType, LLVMScalableVectorType>();
}
LLVMStructType LLVMStructType::getIdentified(MLIRContext *context,
StringRef name) {
return Base::get(context, name, /*opaque=*/false);
}
LLVMStructType LLVMStructType::getIdentifiedChecked(
function_ref<InFlightDiagnostic()> emitError, MLIRContext *context,
StringRef name) {
return Base::getChecked(emitError, context, name, /*opaque=*/false);
}
LLVMStructType LLVMStructType::getNewIdentified(MLIRContext *context,
StringRef name,
ArrayRef<Type> elements,
bool isPacked) {
std::string stringName = name.str();
unsigned counter = 0;
do {
auto type = LLVMStructType::getIdentified(context, stringName);
if (type.isInitialized() || failed(type.setBody(elements, isPacked))) {
counter += 1;
stringName = (Twine(name) + "." + std::to_string(counter)).str();
continue;
}
return type;
} while (true);
}
LLVMStructType LLVMStructType::getLiteral(MLIRContext *context,
ArrayRef<Type> types, bool isPacked) {
return Base::get(context, types, isPacked);
}
LLVMStructType
LLVMStructType::getLiteralChecked(function_ref<InFlightDiagnostic()> emitError,
MLIRContext *context, ArrayRef<Type> types,
bool isPacked) {
return Base::getChecked(emitError, context, types, isPacked);
}
LLVMStructType LLVMStructType::getOpaque(StringRef name, MLIRContext *context) {
return Base::get(context, name, /*opaque=*/true);
}
LLVMStructType
LLVMStructType::getOpaqueChecked(function_ref<InFlightDiagnostic()> emitError,
MLIRContext *context, StringRef name) {
return Base::getChecked(emitError, context, name, /*opaque=*/true);
}
LogicalResult LLVMStructType::setBody(ArrayRef<Type> types, bool isPacked) {
assert(isIdentified() && "can only set bodies of identified structs");
assert(llvm::all_of(types, LLVMStructType::isValidElementType) &&
"expected valid body types");
return Base::mutate(types, isPacked);
}
bool LLVMStructType::isPacked() const { return getImpl()->isPacked(); }
bool LLVMStructType::isIdentified() const { return getImpl()->isIdentified(); }
bool LLVMStructType::isOpaque() {
return getImpl()->isIdentified() &&
(getImpl()->isOpaque() || !getImpl()->isInitialized());
}
bool LLVMStructType::isInitialized() { return getImpl()->isInitialized(); }
StringRef LLVMStructType::getName() { return getImpl()->getIdentifier(); }
ArrayRef<Type> LLVMStructType::getBody() const {
return isIdentified() ? getImpl()->getIdentifiedStructBody()
: getImpl()->getTypeList();
}
LogicalResult LLVMStructType::verify(function_ref<InFlightDiagnostic()>,
StringRef, bool) {
return success();
}
LogicalResult
LLVMStructType::verify(function_ref<InFlightDiagnostic()> emitError,
ArrayRef<Type> types, bool) {
for (Type t : types)
if (!isValidElementType(t))
return emitError() << "invalid LLVM structure element type: " << t;
return success();
}
unsigned
LLVMStructType::getTypeSizeInBits(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
unsigned structSize = 0;
unsigned structAlignment = 1;
for (Type element : getBody()) {
unsigned elementAlignment =
isPacked() ? 1 : dataLayout.getTypeABIAlignment(element);
// Add padding to the struct size to align it to the abi alignment of the
// element type before than adding the size of the element
structSize = llvm::alignTo(structSize, elementAlignment);
structSize += dataLayout.getTypeSize(element);
// The alignment requirement of a struct is equal to the strictest alignment
// requirement of its elements.
structAlignment = std::max(elementAlignment, structAlignment);
}
// At the end, add padding to the struct to satisfy its own alignment
// requirement. Otherwise structs inside of arrays would be misaligned.
structSize = llvm::alignTo(structSize, structAlignment);
return structSize * kBitsInByte;
}
namespace {
enum class StructDLEntryPos { Abi = 0, Preferred = 1 };
} // namespace
static Optional<unsigned>
getStructDataLayoutEntry(DataLayoutEntryListRef params, LLVMStructType type,
StructDLEntryPos pos) {
const auto *currentEntry =
llvm::find_if(params, [](DataLayoutEntryInterface entry) {
return entry.isTypeEntry();
});
if (currentEntry == params.end())
return llvm::None;
auto attr = currentEntry->getValue().cast<DenseIntElementsAttr>();
if (pos == StructDLEntryPos::Preferred &&
attr.size() <= static_cast<unsigned>(StructDLEntryPos::Preferred))
// If no preferred was specified, fall back to abi alignment
pos = StructDLEntryPos::Abi;
return attr.getValues<unsigned>()[static_cast<unsigned>(pos)];
}
static unsigned calculateStructAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params,
LLVMStructType type,
StructDLEntryPos pos) {
// Packed structs always have an abi alignment of 1
if (pos == StructDLEntryPos::Abi && type.isPacked()) {
return 1;
}
// The alignment requirement of a struct is equal to the strictest alignment
// requirement of its elements.
unsigned structAlignment = 1;
for (Type iter : type.getBody()) {
structAlignment =
std::max(dataLayout.getTypeABIAlignment(iter), structAlignment);
}
// Entries are only allowed to be stricter than the required alignment
if (Optional<unsigned> entryResult =
getStructDataLayoutEntry(params, type, pos))
return std::max(*entryResult / kBitsInByte, structAlignment);
return structAlignment;
}
unsigned LLVMStructType::getABIAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
return calculateStructAlignment(dataLayout, params, *this,
StructDLEntryPos::Abi);
}
unsigned
LLVMStructType::getPreferredAlignment(const DataLayout &dataLayout,
DataLayoutEntryListRef params) const {
return calculateStructAlignment(dataLayout, params, *this,
StructDLEntryPos::Preferred);
}
static unsigned extractStructSpecValue(Attribute attr, StructDLEntryPos pos) {
return attr.cast<DenseIntElementsAttr>()
.getValues<unsigned>()[static_cast<unsigned>(pos)];
}
bool LLVMStructType::areCompatible(DataLayoutEntryListRef oldLayout,
DataLayoutEntryListRef newLayout) const {
for (DataLayoutEntryInterface newEntry : newLayout) {
if (!newEntry.isTypeEntry())
continue;
const auto *previousEntry =
llvm::find_if(oldLayout, [](DataLayoutEntryInterface entry) {
return entry.isTypeEntry();
});
if (previousEntry == oldLayout.end())
continue;
unsigned abi = extractStructSpecValue(previousEntry->getValue(),
StructDLEntryPos::Abi);
unsigned newAbi =
extractStructSpecValue(newEntry.getValue(), StructDLEntryPos::Abi);
if (abi < newAbi || abi % newAbi != 0)
return false;
}
return true;
}
LogicalResult LLVMStructType::verifyEntries(DataLayoutEntryListRef entries,
Location loc) const {
for (DataLayoutEntryInterface entry : entries) {
if (!entry.isTypeEntry())
continue;
auto key = entry.getKey().get<Type>().cast<LLVMStructType>();
auto values = entry.getValue().dyn_cast<DenseIntElementsAttr>();
if (!values || (values.size() != 2 && values.size() != 1)) {
return emitError(loc)
<< "expected layout attribute for " << entry.getKey().get<Type>()
<< " to be a dense integer elements attribute of 1 or 2 elements";
}
if (key.isIdentified() || !key.getBody().empty()) {
return emitError(loc) << "unexpected layout attribute for struct " << key;
}
if (values.size() == 1)
continue;
if (extractStructSpecValue(values, StructDLEntryPos::Abi) >
extractStructSpecValue(values, StructDLEntryPos::Preferred)) {
return emitError(loc) << "preferred alignment is expected to be at least "
"as large as ABI alignment";
}
}
return mlir::success();
}
//===----------------------------------------------------------------------===//
// Vector types.
//===----------------------------------------------------------------------===//
/// Verifies that the type about to be constructed is well-formed.
template <typename VecTy>
static LogicalResult
verifyVectorConstructionInvariants(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned numElements) {
if (numElements == 0)
return emitError() << "the number of vector elements must be positive";
if (!VecTy::isValidElementType(elementType))
return emitError() << "invalid vector element type";
return success();
}
LLVMFixedVectorType LLVMFixedVectorType::get(Type elementType,
unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::get(elementType.getContext(), elementType, numElements);
}
LLVMFixedVectorType
LLVMFixedVectorType::getChecked(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned numElements) {
assert(elementType && "expected non-null subtype");
return Base::getChecked(emitError, elementType.getContext(), elementType,
numElements);
}
Type LLVMFixedVectorType::getElementType() {
return static_cast<detail::LLVMTypeAndSizeStorage *>(impl)->elementType;
}
unsigned LLVMFixedVectorType::getNumElements() {
return getImpl()->numElements;
}
bool LLVMFixedVectorType::isValidElementType(Type type) {
return type.isa<LLVMPointerType, LLVMPPCFP128Type>();
}
LogicalResult
LLVMFixedVectorType::verify(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned numElements) {
return verifyVectorConstructionInvariants<LLVMFixedVectorType>(
emitError, elementType, numElements);
}
//===----------------------------------------------------------------------===//
// LLVMScalableVectorType.
//===----------------------------------------------------------------------===//
LLVMScalableVectorType LLVMScalableVectorType::get(Type elementType,
unsigned minNumElements) {
assert(elementType && "expected non-null subtype");
return Base::get(elementType.getContext(), elementType, minNumElements);
}
LLVMScalableVectorType
LLVMScalableVectorType::getChecked(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned minNumElements) {
assert(elementType && "expected non-null subtype");
return Base::getChecked(emitError, elementType.getContext(), elementType,
minNumElements);
}
Type LLVMScalableVectorType::getElementType() {
return static_cast<detail::LLVMTypeAndSizeStorage *>(impl)->elementType;
}
unsigned LLVMScalableVectorType::getMinNumElements() {
return getImpl()->numElements;
}
bool LLVMScalableVectorType::isValidElementType(Type type) {
if (auto intType = type.dyn_cast<IntegerType>())
return intType.isSignless();
return isCompatibleFloatingPointType(type) || type.isa<LLVMPointerType>();
}
LogicalResult
LLVMScalableVectorType::verify(function_ref<InFlightDiagnostic()> emitError,
Type elementType, unsigned numElements) {
return verifyVectorConstructionInvariants<LLVMScalableVectorType>(
emitError, elementType, numElements);
}
//===----------------------------------------------------------------------===//
// Utility functions.
//===----------------------------------------------------------------------===//
bool mlir::LLVM::isCompatibleOuterType(Type type) {
// clang-format off
if (type.isa<
BFloat16Type,
Float16Type,
Float32Type,
Float64Type,
Float80Type,
Float128Type,
LLVMArrayType,
LLVMFunctionType,
LLVMLabelType,
LLVMMetadataType,
LLVMPPCFP128Type,
LLVMPointerType,
LLVMStructType,
LLVMTokenType,
LLVMFixedVectorType,
LLVMScalableVectorType,
LLVMVoidType,
LLVMX86MMXType
>()) {
// clang-format on
return true;
}
// Only signless integers are compatible.
if (auto intType = type.dyn_cast<IntegerType>())
return intType.isSignless();
// 1D vector types are compatible.
if (auto vecType = type.dyn_cast<VectorType>())
return vecType.getRank() == 1;
return false;
}
static bool isCompatibleImpl(Type type, DenseSet<Type> &compatibleTypes) {
if (!compatibleTypes.insert(type).second)
return true;
auto isCompatible = [&](Type type) {
return isCompatibleImpl(type, compatibleTypes);
};
bool result =
llvm::TypeSwitch<Type, bool>(type)
.Case<LLVMStructType>([&](auto structType) {
return llvm::all_of(structType.getBody(), isCompatible);
})
.Case<LLVMFunctionType>([&](auto funcType) {
return isCompatible(funcType.getReturnType()) &&
llvm::all_of(funcType.getParams(), isCompatible);
})
.Case<IntegerType>([](auto intType) { return intType.isSignless(); })
.Case<VectorType>([&](auto vecType) {
return vecType.getRank() == 1 &&
isCompatible(vecType.getElementType());
})
.Case<LLVMPointerType>([&](auto pointerType) {
if (pointerType.isOpaque())
return true;
return isCompatible(pointerType.getElementType());
})
// clang-format off
.Case<
LLVMFixedVectorType,
LLVMScalableVectorType,
LLVMArrayType
>([&](auto containerType) {
return isCompatible(containerType.getElementType());
})
.Case<
BFloat16Type,
Float16Type,
Float32Type,
Float64Type,
Float80Type,
Float128Type,
LLVMLabelType,
LLVMMetadataType,
LLVMPPCFP128Type,
LLVMTokenType,
LLVMVoidType,
LLVMX86MMXType
>([](Type) { return true; })
// clang-format on
.Default([](Type) { return false; });
if (!result)
compatibleTypes.erase(type);
return result;
}
bool LLVMDialect::isCompatibleType(Type type) {
if (auto *llvmDialect =
type.getContext()->getLoadedDialect<LLVM::LLVMDialect>())
return isCompatibleImpl(type, llvmDialect->compatibleTypes.get());
DenseSet<Type> localCompatibleTypes;
return isCompatibleImpl(type, localCompatibleTypes);
}
bool mlir::LLVM::isCompatibleType(Type type) {
return LLVMDialect::isCompatibleType(type);
}
bool mlir::LLVM::isCompatibleFloatingPointType(Type type) {
return type.isa<BFloat16Type, Float16Type, Float32Type, Float64Type,
Float80Type, Float128Type, LLVMPPCFP128Type>();
}
bool mlir::LLVM::isCompatibleVectorType(Type type) {
if (type.isa<LLVMFixedVectorType, LLVMScalableVectorType>())
return true;
if (auto vecType = type.dyn_cast<VectorType>()) {
if (vecType.getRank() != 1)
return false;
Type elementType = vecType.getElementType();
if (auto intType = elementType.dyn_cast<IntegerType>())
return intType.isSignless();
return elementType.isa<BFloat16Type, Float16Type, Float32Type, Float64Type,
Float80Type, Float128Type>();
}
return false;
}
Type mlir::LLVM::getVectorElementType(Type type) {
return llvm::TypeSwitch<Type, Type>(type)
.Case<LLVMFixedVectorType, LLVMScalableVectorType, VectorType>(
[](auto ty) { return ty.getElementType(); })
.Default([](Type) -> Type {
llvm_unreachable("incompatible with LLVM vector type");
});
}
llvm::ElementCount mlir::LLVM::getVectorNumElements(Type type) {
return llvm::TypeSwitch<Type, llvm::ElementCount>(type)
.Case([](VectorType ty) {
if (ty.isScalable())
return llvm::ElementCount::getScalable(ty.getNumElements());
return llvm::ElementCount::getFixed(ty.getNumElements());
})
.Case([](LLVMFixedVectorType ty) {
return llvm::ElementCount::getFixed(ty.getNumElements());
})
.Case([](LLVMScalableVectorType ty) {
return llvm::ElementCount::getScalable(ty.getMinNumElements());
})
.Default([](Type) -> llvm::ElementCount {
llvm_unreachable("incompatible with LLVM vector type");
});
}
bool mlir::LLVM::isScalableVectorType(Type vectorType) {
assert(
(vectorType
.isa<LLVMFixedVectorType, LLVMScalableVectorType, VectorType>()) &&
"expected LLVM-compatible vector type");
return !vectorType.isa<LLVMFixedVectorType>() &&
(vectorType.isa<LLVMScalableVectorType>() ||
vectorType.cast<VectorType>().isScalable());
}
Type mlir::LLVM::getVectorType(Type elementType, unsigned numElements,
bool isScalable) {
bool useLLVM = LLVMFixedVectorType::isValidElementType(elementType);
bool useBuiltIn = VectorType::isValidElementType(elementType);
(void)useBuiltIn;
assert((useLLVM ^ useBuiltIn) && "expected LLVM-compatible fixed-vector type "
"to be either builtin or LLVM dialect type");
if (useLLVM) {
if (isScalable)
return LLVMScalableVectorType::get(elementType, numElements);
return LLVMFixedVectorType::get(elementType, numElements);
}
return VectorType::get(numElements, elementType, (unsigned)isScalable);
}
Type mlir::LLVM::getFixedVectorType(Type elementType, unsigned numElements) {
bool useLLVM = LLVMFixedVectorType::isValidElementType(elementType);
bool useBuiltIn = VectorType::isValidElementType(elementType);
(void)useBuiltIn;
assert((useLLVM ^ useBuiltIn) && "expected LLVM-compatible fixed-vector type "
"to be either builtin or LLVM dialect type");
if (useLLVM)
return LLVMFixedVectorType::get(elementType, numElements);
return VectorType::get(numElements, elementType);
}
Type mlir::LLVM::getScalableVectorType(Type elementType, unsigned numElements) {
bool useLLVM = LLVMScalableVectorType::isValidElementType(elementType);
bool useBuiltIn = VectorType::isValidElementType(elementType);
(void)useBuiltIn;
assert((useLLVM ^ useBuiltIn) && "expected LLVM-compatible scalable-vector "
"type to be either builtin or LLVM dialect "
"type");
if (useLLVM)
return LLVMScalableVectorType::get(elementType, numElements);
return VectorType::get(numElements, elementType, /*numScalableDims=*/1);
}
llvm::TypeSize mlir::LLVM::getPrimitiveTypeSizeInBits(Type type) {
assert(isCompatibleType(type) &&
"expected a type compatible with the LLVM dialect");
return llvm::TypeSwitch<Type, llvm::TypeSize>(type)
.Case<BFloat16Type, Float16Type>(
[](Type) { return llvm::TypeSize::Fixed(16); })
.Case<Float32Type>([](Type) { return llvm::TypeSize::Fixed(32); })
.Case<Float64Type, LLVMX86MMXType>(
[](Type) { return llvm::TypeSize::Fixed(64); })
.Case<Float80Type>([](Type) { return llvm::TypeSize::Fixed(80); })
.Case<Float128Type>([](Type) { return llvm::TypeSize::Fixed(128); })
.Case<IntegerType>([](IntegerType intTy) {
return llvm::TypeSize::Fixed(intTy.getWidth());
})
.Case<LLVMPPCFP128Type>([](Type) { return llvm::TypeSize::Fixed(128); })
.Case<LLVMFixedVectorType>([](LLVMFixedVectorType t) {
llvm::TypeSize elementSize =
getPrimitiveTypeSizeInBits(t.getElementType());
return llvm::TypeSize(elementSize.getFixedSize() * t.getNumElements(),
elementSize.isScalable());
})
.Case<VectorType>([](VectorType t) {
assert(isCompatibleVectorType(t) &&
"unexpected incompatible with LLVM vector type");
llvm::TypeSize elementSize =
getPrimitiveTypeSizeInBits(t.getElementType());
return llvm::TypeSize(elementSize.getFixedSize() * t.getNumElements(),
elementSize.isScalable());
})
.Default([](Type ty) {
assert((ty.isa<LLVMVoidType, LLVMLabelType, LLVMMetadataType,
LLVMTokenType, LLVMStructType, LLVMArrayType,
LLVMPointerType, LLVMFunctionType>()) &&
"unexpected missing support for primitive type");
return llvm::TypeSize::Fixed(0);
});
}
#include "mlir/Dialect/LLVMIR/LLVMTypeInterfaces.cpp.inc"