/
Attributes.h
1459 lines (1213 loc) · 54.1 KB
/
Attributes.h
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
//===- Attributes.h - MLIR Attribute Classes --------------------*- C++ -*-===//
//
// Part of the MLIR 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
//
//===----------------------------------------------------------------------===//
#ifndef MLIR_IR_ATTRIBUTES_H
#define MLIR_IR_ATTRIBUTES_H
#include "mlir/IR/AttributeSupport.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Sequence.h"
namespace mlir {
class AffineMap;
class Dialect;
class FunctionType;
class Identifier;
class IntegerSet;
class Location;
class MLIRContext;
class ShapedType;
class Type;
namespace detail {
struct AffineMapAttributeStorage;
struct ArrayAttributeStorage;
struct BoolAttributeStorage;
struct DictionaryAttributeStorage;
struct IntegerAttributeStorage;
struct IntegerSetAttributeStorage;
struct FloatAttributeStorage;
struct OpaqueAttributeStorage;
struct StringAttributeStorage;
struct SymbolRefAttributeStorage;
struct TypeAttributeStorage;
/// Elements Attributes.
struct DenseElementsAttributeStorage;
struct OpaqueElementsAttributeStorage;
struct SparseElementsAttributeStorage;
} // namespace detail
/// Attributes are known-constant values of operations and functions.
///
/// Instances of the Attribute class are references to immutable, uniqued,
/// and immortal values owned by MLIRContext. As such, an Attribute is a thin
/// wrapper around an underlying storage pointer. Attributes are usually passed
/// by value.
class Attribute {
public:
/// Integer identifier for all the concrete attribute kinds.
enum Kind {
// Reserve attribute kinds for dialect specific extensions.
#define DEFINE_SYM_KIND_RANGE(Dialect) \
FIRST_##Dialect##_ATTR, LAST_##Dialect##_ATTR = FIRST_##Dialect##_ATTR + 0xff,
#include "DialectSymbolRegistry.def"
};
/// Utility class for implementing attributes.
template <typename ConcreteType, typename BaseType = Attribute,
typename StorageType = AttributeStorage>
using AttrBase = detail::StorageUserBase<ConcreteType, BaseType, StorageType,
detail::AttributeUniquer>;
using ImplType = AttributeStorage;
using ValueType = void;
Attribute() : impl(nullptr) {}
/* implicit */ Attribute(const ImplType *impl)
: impl(const_cast<ImplType *>(impl)) {}
Attribute(const Attribute &other) = default;
Attribute &operator=(const Attribute &other) = default;
bool operator==(Attribute other) const { return impl == other.impl; }
bool operator!=(Attribute other) const { return !(*this == other); }
explicit operator bool() const { return impl; }
bool operator!() const { return impl == nullptr; }
template <typename U> bool isa() const;
template <typename U> U dyn_cast() const;
template <typename U> U dyn_cast_or_null() const;
template <typename U> U cast() const;
// Support dyn_cast'ing Attribute to itself.
static bool classof(Attribute) { return true; }
/// Return the classification for this attribute.
unsigned getKind() const { return impl->getKind(); }
/// Return the type of this attribute.
Type getType() const;
/// Return the context this attribute belongs to.
MLIRContext *getContext() const;
/// Get the dialect this attribute is registered to.
Dialect &getDialect() const;
/// Print the attribute.
void print(raw_ostream &os) const;
void dump() const;
/// Get an opaque pointer to the attribute.
const void *getAsOpaquePointer() const { return impl; }
/// Construct an attribute from the opaque pointer representation.
static Attribute getFromOpaquePointer(const void *ptr) {
return Attribute(reinterpret_cast<const ImplType *>(ptr));
}
friend ::llvm::hash_code hash_value(Attribute arg);
protected:
ImplType *impl;
};
inline raw_ostream &operator<<(raw_ostream &os, Attribute attr) {
attr.print(os);
return os;
}
namespace StandardAttributes {
enum Kind {
AffineMap = Attribute::FIRST_STANDARD_ATTR,
Array,
Bool,
Dictionary,
Float,
Integer,
IntegerSet,
Opaque,
String,
SymbolRef,
Type,
Unit,
/// Elements Attributes.
DenseElements,
OpaqueElements,
SparseElements,
FIRST_ELEMENTS_ATTR = DenseElements,
LAST_ELEMENTS_ATTR = SparseElements,
/// Locations.
CallSiteLocation,
FileLineColLocation,
FusedLocation,
NameLocation,
OpaqueLocation,
UnknownLocation,
// Represents a location as a 'void*' pointer to a front-end's opaque
// location information, which must live longer than the MLIR objects that
// refer to it. OpaqueLocation's are never serialized.
//
// TODO: OpaqueLocation,
// Represents a value inlined through a function call.
// TODO: InlinedLocation,
FIRST_LOCATION_ATTR = CallSiteLocation,
LAST_LOCATION_ATTR = UnknownLocation,
};
} // namespace StandardAttributes
//===----------------------------------------------------------------------===//
// AffineMapAttr
//===----------------------------------------------------------------------===//
class AffineMapAttr
: public Attribute::AttrBase<AffineMapAttr, Attribute,
detail::AffineMapAttributeStorage> {
public:
using Base::Base;
using ValueType = AffineMap;
static AffineMapAttr get(AffineMap value);
AffineMap getValue() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::AffineMap;
}
};
//===----------------------------------------------------------------------===//
// ArrayAttr
//===----------------------------------------------------------------------===//
/// Array attributes are lists of other attributes. They are not necessarily
/// type homogenous given that attributes don't, in general, carry types.
class ArrayAttr : public Attribute::AttrBase<ArrayAttr, Attribute,
detail::ArrayAttributeStorage> {
public:
using Base::Base;
using ValueType = ArrayRef<Attribute>;
static ArrayAttr get(ArrayRef<Attribute> value, MLIRContext *context);
ArrayRef<Attribute> getValue() const;
/// Support range iteration.
using iterator = llvm::ArrayRef<Attribute>::iterator;
iterator begin() const { return getValue().begin(); }
iterator end() const { return getValue().end(); }
size_t size() const { return getValue().size(); }
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::Array;
}
private:
/// Class for underlying value iterator support.
template <typename AttrTy>
class attr_value_iterator final
: public llvm::mapped_iterator<iterator, AttrTy (*)(Attribute)> {
public:
explicit attr_value_iterator(iterator it)
: llvm::mapped_iterator<iterator, AttrTy (*)(Attribute)>(
it, [](Attribute attr) { return attr.cast<AttrTy>(); }) {}
AttrTy operator*() { return (*this->I).template cast<AttrTy>(); }
};
public:
template <typename AttrTy>
llvm::iterator_range<attr_value_iterator<AttrTy>> getAsRange() {
return llvm::make_range(attr_value_iterator<AttrTy>(begin()),
attr_value_iterator<AttrTy>(end()));
}
};
//===----------------------------------------------------------------------===//
// BoolAttr
//===----------------------------------------------------------------------===//
class BoolAttr : public Attribute::AttrBase<BoolAttr, Attribute,
detail::BoolAttributeStorage> {
public:
using Base::Base;
using ValueType = bool;
static BoolAttr get(bool value, MLIRContext *context);
bool getValue() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) { return kind == StandardAttributes::Bool; }
};
//===----------------------------------------------------------------------===//
// DictionaryAttr
//===----------------------------------------------------------------------===//
/// NamedAttribute is used for dictionary attributes, it holds an identifier for
/// the name and a value for the attribute. The attribute pointer should always
/// be non-null.
using NamedAttribute = std::pair<Identifier, Attribute>;
/// Dictionary attribute is an attribute that represents a sorted collection of
/// named attribute values. The elements are sorted by name, and each name must
/// be unique within the collection.
class DictionaryAttr
: public Attribute::AttrBase<DictionaryAttr, Attribute,
detail::DictionaryAttributeStorage> {
public:
using Base::Base;
using ValueType = ArrayRef<NamedAttribute>;
static DictionaryAttr get(ArrayRef<NamedAttribute> value,
MLIRContext *context);
ArrayRef<NamedAttribute> getValue() const;
/// Return the specified attribute if present, null otherwise.
Attribute get(StringRef name) const;
Attribute get(Identifier name) const;
/// Support range iteration.
using iterator = llvm::ArrayRef<NamedAttribute>::iterator;
iterator begin() const;
iterator end() const;
bool empty() const { return size() == 0; }
size_t size() const;
/// Methods for supporting type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::Dictionary;
}
};
//===----------------------------------------------------------------------===//
// FloatAttr
//===----------------------------------------------------------------------===//
class FloatAttr : public Attribute::AttrBase<FloatAttr, Attribute,
detail::FloatAttributeStorage> {
public:
using Base::Base;
using ValueType = APFloat;
/// Return a float attribute for the specified value in the specified type.
/// These methods should only be used for simple constant values, e.g 1.0/2.0,
/// that are known-valid both as host double and the 'type' format.
static FloatAttr get(Type type, double value);
static FloatAttr getChecked(Type type, double value, Location loc);
/// Return a float attribute for the specified value in the specified type.
static FloatAttr get(Type type, const APFloat &value);
static FloatAttr getChecked(Type type, const APFloat &value, Location loc);
APFloat getValue() const;
/// This function is used to convert the value to a double, even if it loses
/// precision.
double getValueAsDouble() const;
static double getValueAsDouble(APFloat val);
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::Float;
}
/// Verify the construction invariants for a double value.
static LogicalResult verifyConstructionInvariants(Optional<Location> loc,
MLIRContext *ctx, Type type,
double value);
static LogicalResult verifyConstructionInvariants(Optional<Location> loc,
MLIRContext *ctx, Type type,
const APFloat &value);
};
//===----------------------------------------------------------------------===//
// IntegerAttr
//===----------------------------------------------------------------------===//
class IntegerAttr
: public Attribute::AttrBase<IntegerAttr, Attribute,
detail::IntegerAttributeStorage> {
public:
using Base::Base;
using ValueType = APInt;
static IntegerAttr get(Type type, int64_t value);
static IntegerAttr get(Type type, const APInt &value);
APInt getValue() const;
// TODO(jpienaar): Change callers to use getValue instead.
int64_t getInt() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::Integer;
}
};
//===----------------------------------------------------------------------===//
// IntegerSetAttr
//===----------------------------------------------------------------------===//
class IntegerSetAttr
: public Attribute::AttrBase<IntegerSetAttr, Attribute,
detail::IntegerSetAttributeStorage> {
public:
using Base::Base;
using ValueType = IntegerSet;
static IntegerSetAttr get(IntegerSet value);
IntegerSet getValue() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::IntegerSet;
}
};
//===----------------------------------------------------------------------===//
// OpaqueAttr
//===----------------------------------------------------------------------===//
/// Opaque attributes represent attributes of non-registered dialects. These are
/// attribute represented in their raw string form, and can only usefully be
/// tested for attribute equality.
class OpaqueAttr : public Attribute::AttrBase<OpaqueAttr, Attribute,
detail::OpaqueAttributeStorage> {
public:
using Base::Base;
/// Get or create a new OpaqueAttr with the provided dialect and string data.
static OpaqueAttr get(Identifier dialect, StringRef attrData, Type type,
MLIRContext *context);
/// Get or create a new OpaqueAttr with the provided dialect and string data.
/// If the given identifier is not a valid namespace for a dialect, then a
/// null attribute is returned.
static OpaqueAttr getChecked(Identifier dialect, StringRef attrData,
Type type, Location location);
/// Returns the dialect namespace of the opaque attribute.
Identifier getDialectNamespace() const;
/// Returns the raw attribute data of the opaque attribute.
StringRef getAttrData() const;
/// Verify the construction of an opaque attribute.
static LogicalResult verifyConstructionInvariants(Optional<Location> loc,
MLIRContext *context,
Identifier dialect,
StringRef attrData,
Type type);
static bool kindof(unsigned kind) {
return kind == StandardAttributes::Opaque;
}
};
//===----------------------------------------------------------------------===//
// StringAttr
//===----------------------------------------------------------------------===//
class StringAttr : public Attribute::AttrBase<StringAttr, Attribute,
detail::StringAttributeStorage> {
public:
using Base::Base;
using ValueType = StringRef;
/// Get an instance of a StringAttr with the given string.
static StringAttr get(StringRef bytes, MLIRContext *context);
/// Get an instance of a StringAttr with the given string and Type.
static StringAttr get(StringRef bytes, Type type);
StringRef getValue() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::String;
}
};
//===----------------------------------------------------------------------===//
// SymbolRefAttr
//===----------------------------------------------------------------------===//
class FlatSymbolRefAttr;
/// A symbol reference attribute represents a symbolic reference to another
/// operation.
class SymbolRefAttr
: public Attribute::AttrBase<SymbolRefAttr, Attribute,
detail::SymbolRefAttributeStorage> {
public:
using Base::Base;
/// Construct a symbol reference for the given value name.
static FlatSymbolRefAttr get(StringRef value, MLIRContext *ctx);
/// Construct a symbol reference for the given value name, and a set of nested
/// references that are further resolve to a nested symbol.
static SymbolRefAttr get(StringRef value,
ArrayRef<FlatSymbolRefAttr> references,
MLIRContext *ctx);
/// Returns the name of the top level symbol reference, i.e. the root of the
/// reference path.
StringRef getRootReference() const;
/// Returns the name of the fully resolved symbol, i.e. the leaf of the
/// reference path.
StringRef getLeafReference() const;
/// Returns the set of nested references representing the path to the symbol
/// nested under the root reference.
ArrayRef<FlatSymbolRefAttr> getNestedReferences() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) {
return kind == StandardAttributes::SymbolRef;
}
};
/// A symbol reference with a reference path containing a single element. This
/// is used to refer to an operation within the current symbol table.
class FlatSymbolRefAttr : public SymbolRefAttr {
public:
using SymbolRefAttr::SymbolRefAttr;
using ValueType = StringRef;
/// Construct a symbol reference for the given value name.
static FlatSymbolRefAttr get(StringRef value, MLIRContext *ctx) {
return SymbolRefAttr::get(value, ctx);
}
/// Returns the name of the held symbol reference.
StringRef getValue() const { return getRootReference(); }
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool classof(Attribute attr) {
SymbolRefAttr refAttr = attr.dyn_cast<SymbolRefAttr>();
return refAttr && refAttr.getNestedReferences().empty();
}
private:
using SymbolRefAttr::get;
using SymbolRefAttr::getNestedReferences;
};
//===----------------------------------------------------------------------===//
// Type
//===----------------------------------------------------------------------===//
class TypeAttr : public Attribute::AttrBase<TypeAttr, Attribute,
detail::TypeAttributeStorage> {
public:
using Base::Base;
using ValueType = Type;
static TypeAttr get(Type value);
Type getValue() const;
/// Methods for support type inquiry through isa, cast, and dyn_cast.
static bool kindof(unsigned kind) { return kind == StandardAttributes::Type; }
};
//===----------------------------------------------------------------------===//
// UnitAttr
//===----------------------------------------------------------------------===//
/// Unit attributes are attributes that hold no specific value and are given
/// meaning by their existence.
class UnitAttr : public Attribute::AttrBase<UnitAttr> {
public:
using Base::Base;
static UnitAttr get(MLIRContext *context);
static bool kindof(unsigned kind) { return kind == StandardAttributes::Unit; }
};
//===----------------------------------------------------------------------===//
// Elements Attributes
//===----------------------------------------------------------------------===//
namespace detail {
template <typename T> class ElementsAttrIterator;
template <typename T> class ElementsAttrRange;
} // namespace detail
/// A base attribute that represents a reference to a static shaped tensor or
/// vector constant.
class ElementsAttr : public Attribute {
public:
using Attribute::Attribute;
template <typename T> using iterator = detail::ElementsAttrIterator<T>;
template <typename T> using iterator_range = detail::ElementsAttrRange<T>;
/// Return the type of this ElementsAttr, guaranteed to be a vector or tensor
/// with static shape.
ShapedType getType() const;
/// Return the value at the given index. The index is expected to refer to a
/// valid element.
Attribute getValue(ArrayRef<uint64_t> index) const;
/// Return the value of type 'T' at the given index, where 'T' corresponds to
/// an Attribute type.
template <typename T> T getValue(ArrayRef<uint64_t> index) const {
return getValue(index).template cast<T>();
}
/// Return the elements of this attribute as a value of type 'T'. Note:
/// Aborts if the subclass is OpaqueElementsAttrs, these attrs do not support
/// iteration.
template <typename T> iterator_range<T> getValues() const;
/// Return if the given 'index' refers to a valid element in this attribute.
bool isValidIndex(ArrayRef<uint64_t> index) const;
/// Returns the number of elements held by this attribute.
int64_t getNumElements() const;
/// Generates a new ElementsAttr by mapping each int value to a new
/// underlying APInt. The new values can represent either a integer or float.
/// This ElementsAttr should contain integers.
ElementsAttr mapValues(Type newElementType,
function_ref<APInt(const APInt &)> mapping) const;
/// Generates a new ElementsAttr by mapping each float value to a new
/// underlying APInt. The new values can represent either a integer or float.
/// This ElementsAttr should contain floats.
ElementsAttr mapValues(Type newElementType,
function_ref<APInt(const APFloat &)> mapping) const;
/// Method for support type inquiry through isa, cast and dyn_cast.
static bool classof(Attribute attr) {
return attr.getKind() >= StandardAttributes::FIRST_ELEMENTS_ATTR &&
attr.getKind() <= StandardAttributes::LAST_ELEMENTS_ATTR;
}
protected:
/// Returns the 1 dimensional flattened row-major index from the given
/// multi-dimensional index.
uint64_t getFlattenedIndex(ArrayRef<uint64_t> index) const;
};
namespace detail {
/// DenseElementsAttr data is aligned to uint64_t, so this traits class is
/// necessary to interop with PointerIntPair.
class DenseElementDataPointerTypeTraits {
public:
static inline const void *getAsVoidPointer(const char *ptr) { return ptr; }
static inline const char *getFromVoidPointer(const void *ptr) {
return static_cast<const char *>(ptr);
}
// Note: We could steal more bits if the need arises.
enum { NumLowBitsAvailable = 1 };
};
/// Pair of raw pointer and a boolean flag of whether the pointer holds a splat,
using DenseIterPtrAndSplat =
llvm::PointerIntPair<const char *, 1, bool,
DenseElementDataPointerTypeTraits>;
/// Impl iterator for indexed DenseElementAttr iterators that records a data
/// pointer and data index that is adjusted for the case of a splat attribute.
template <typename ConcreteT, typename T, typename PointerT = T *,
typename ReferenceT = T &>
class DenseElementIndexedIteratorImpl
: public indexed_accessor_iterator<ConcreteT, DenseIterPtrAndSplat, T,
PointerT, ReferenceT> {
protected:
DenseElementIndexedIteratorImpl(const char *data, bool isSplat,
size_t dataIndex)
: indexed_accessor_iterator<ConcreteT, DenseIterPtrAndSplat, T, PointerT,
ReferenceT>({data, isSplat}, dataIndex) {}
/// Return the current index for this iterator, adjusted for the case of a
/// splat.
ptrdiff_t getDataIndex() const {
bool isSplat = this->base.getInt();
return isSplat ? 0 : this->index;
}
/// Return the data base pointer.
const char *getData() const { return this->base.getPointer(); }
};
} // namespace detail
/// An attribute that represents a reference to a dense vector or tensor object.
///
class DenseElementsAttr
: public Attribute::AttrBase<DenseElementsAttr, ElementsAttr,
detail::DenseElementsAttributeStorage> {
public:
using Base::Base;
/// Method for support type inquiry through isa, cast and dyn_cast.
static bool classof(Attribute attr) {
return attr.getKind() == StandardAttributes::DenseElements;
}
/// Constructs a dense elements attribute from an array of element values.
/// Each element attribute value is expected to be an element of 'type'.
/// 'type' must be a vector or tensor with static shape.
static DenseElementsAttr get(ShapedType type, ArrayRef<Attribute> values);
/// Constructs a dense integer elements attribute from an array of integer
/// or floating-point values. Each value is expected to be the same bitwidth
/// of the element type of 'type'. 'type' must be a vector or tensor with
/// static shape.
template <typename T, typename = typename std::enable_if<
std::numeric_limits<T>::is_integer ||
llvm::is_one_of<T, float, double>::value>::type>
static DenseElementsAttr get(const ShapedType &type, ArrayRef<T> values) {
const char *data = reinterpret_cast<const char *>(values.data());
return getRawIntOrFloat(
type, ArrayRef<char>(data, values.size() * sizeof(T)), sizeof(T),
/*isInt=*/std::numeric_limits<T>::is_integer);
}
/// Constructs a dense integer elements attribute from a single element.
template <typename T, typename = typename std::enable_if<
std::numeric_limits<T>::is_integer ||
llvm::is_one_of<T, float, double>::value>::type>
static DenseElementsAttr get(const ShapedType &type, T value) {
return get(type, llvm::makeArrayRef(value));
}
/// Overload of the above 'get' method that is specialized for boolean values.
static DenseElementsAttr get(ShapedType type, ArrayRef<bool> values);
/// Constructs a dense integer elements attribute from an array of APInt
/// values. Each APInt value is expected to have the same bitwidth as the
/// element type of 'type'. 'type' must be a vector or tensor with static
/// shape.
static DenseElementsAttr get(ShapedType type, ArrayRef<APInt> values);
/// Constructs a dense float elements attribute from an array of APFloat
/// values. Each APFloat value is expected to have the same bitwidth as the
/// element type of 'type'. 'type' must be a vector or tensor with static
/// shape.
static DenseElementsAttr get(ShapedType type, ArrayRef<APFloat> values);
/// Construct a dense elements attribute for an initializer_list of values.
/// Each value is expected to be the same bitwidth of the element type of
/// 'type'. 'type' must be a vector or tensor with static shape.
template <typename T>
static DenseElementsAttr get(const ShapedType &type,
const std::initializer_list<T> &list) {
return get(type, ArrayRef<T>(list));
}
//===--------------------------------------------------------------------===//
// Iterators
//===--------------------------------------------------------------------===//
/// A utility iterator that allows walking over the internal Attribute values
/// of a DenseElementsAttr.
class AttributeElementIterator
: public indexed_accessor_iterator<AttributeElementIterator, const void *,
Attribute, Attribute, Attribute> {
public:
/// Accesses the Attribute value at this iterator position.
Attribute operator*() const;
private:
friend DenseElementsAttr;
/// Constructs a new iterator.
AttributeElementIterator(DenseElementsAttr attr, size_t index);
};
/// Iterator for walking raw element values of the specified type 'T', which
/// may be any c++ data type matching the stored representation: int32_t,
/// float, etc.
template <typename T>
class ElementIterator
: public detail::DenseElementIndexedIteratorImpl<ElementIterator<T>,
const T> {
public:
/// Accesses the raw value at this iterator position.
const T &operator*() const {
return reinterpret_cast<const T *>(this->getData())[this->getDataIndex()];
}
private:
friend DenseElementsAttr;
/// Constructs a new iterator.
ElementIterator(const char *data, bool isSplat, size_t dataIndex)
: detail::DenseElementIndexedIteratorImpl<ElementIterator<T>, const T>(
data, isSplat, dataIndex) {}
};
/// A utility iterator that allows walking over the internal bool values.
class BoolElementIterator
: public detail::DenseElementIndexedIteratorImpl<BoolElementIterator,
bool, bool, bool> {
public:
/// Accesses the bool value at this iterator position.
bool operator*() const;
private:
friend DenseElementsAttr;
/// Constructs a new iterator.
BoolElementIterator(DenseElementsAttr attr, size_t dataIndex);
};
/// A utility iterator that allows walking over the internal raw APInt values.
class IntElementIterator
: public detail::DenseElementIndexedIteratorImpl<IntElementIterator,
APInt, APInt, APInt> {
public:
/// Accesses the raw APInt value at this iterator position.
APInt operator*() const;
private:
friend DenseElementsAttr;
/// Constructs a new iterator.
IntElementIterator(DenseElementsAttr attr, size_t dataIndex);
/// The bitwidth of the element type.
size_t bitWidth;
};
/// Iterator for walking over APFloat values.
class FloatElementIterator final
: public llvm::mapped_iterator<IntElementIterator,
std::function<APFloat(const APInt &)>> {
friend DenseElementsAttr;
/// Initializes the float element iterator to the specified iterator.
FloatElementIterator(const llvm::fltSemantics &smt, IntElementIterator it);
public:
using reference = APFloat;
};
//===--------------------------------------------------------------------===//
// Value Querying
//===--------------------------------------------------------------------===//
/// Returns if this attribute corresponds to a splat, i.e. if all element
/// values are the same.
bool isSplat() const;
/// Return the splat value for this attribute. This asserts that the attribute
/// corresponds to a splat.
Attribute getSplatValue() const { return getSplatValue<Attribute>(); }
template <typename T>
typename std::enable_if<!std::is_base_of<Attribute, T>::value ||
std::is_same<Attribute, T>::value,
T>::type
getSplatValue() const {
assert(isSplat() && "expected the attribute to be a splat");
return *getValues<T>().begin();
}
/// Return the splat value for derived attribute element types.
template <typename T>
typename std::enable_if<std::is_base_of<Attribute, T>::value &&
!std::is_same<Attribute, T>::value,
T>::type
getSplatValue() const {
return getSplatValue().template cast<T>();
}
/// Return the value at the given index. The 'index' is expected to refer to a
/// valid element.
Attribute getValue(ArrayRef<uint64_t> index) const {
return getValue<Attribute>(index);
}
template <typename T> T getValue(ArrayRef<uint64_t> index) const {
// Skip to the element corresponding to the flattened index.
return *std::next(getValues<T>().begin(), getFlattenedIndex(index));
}
/// Return the held element values as a range of integer or floating-point
/// values.
template <typename T, typename = typename std::enable_if<
(!std::is_same<T, bool>::value &&
std::numeric_limits<T>::is_integer) ||
llvm::is_one_of<T, float, double>::value>::type>
llvm::iterator_range<ElementIterator<T>> getValues() const {
assert(isValidIntOrFloat(sizeof(T), std::numeric_limits<T>::is_integer));
auto rawData = getRawData().data();
bool splat = isSplat();
return {ElementIterator<T>(rawData, splat, 0),
ElementIterator<T>(rawData, splat, getNumElements())};
}
/// Return the held element values as a range of Attributes.
llvm::iterator_range<AttributeElementIterator> getAttributeValues() const;
template <typename T, typename = typename std::enable_if<
std::is_same<T, Attribute>::value>::type>
llvm::iterator_range<AttributeElementIterator> getValues() const {
return getAttributeValues();
}
AttributeElementIterator attr_value_begin() const;
AttributeElementIterator attr_value_end() const;
/// Return the held element values a range of T, where T is a derived
/// attribute type.
template <typename T>
using DerivedAttributeElementIterator =
llvm::mapped_iterator<AttributeElementIterator, T (*)(Attribute)>;
template <typename T, typename = typename std::enable_if<
std::is_base_of<Attribute, T>::value &&
!std::is_same<Attribute, T>::value>::type>
llvm::iterator_range<DerivedAttributeElementIterator<T>> getValues() const {
auto castFn = [](Attribute attr) { return attr.template cast<T>(); };
return llvm::map_range(getAttributeValues(),
static_cast<T (*)(Attribute)>(castFn));
}
/// Return the held element values as a range of bool. The element type of
/// this attribute must be of integer type of bitwidth 1.
llvm::iterator_range<BoolElementIterator> getBoolValues() const;
template <typename T, typename = typename std::enable_if<
std::is_same<T, bool>::value>::type>
llvm::iterator_range<BoolElementIterator> getValues() const {
return getBoolValues();
}
/// Return the held element values as a range of APInts. The element type of
/// this attribute must be of integer type.
llvm::iterator_range<IntElementIterator> getIntValues() const;
template <typename T, typename = typename std::enable_if<
std::is_same<T, APInt>::value>::type>
llvm::iterator_range<IntElementIterator> getValues() const {
return getIntValues();
}
IntElementIterator int_value_begin() const;
IntElementIterator int_value_end() const;
/// Return the held element values as a range of APFloat. The element type of
/// this attribute must be of float type.
llvm::iterator_range<FloatElementIterator> getFloatValues() const;
template <typename T, typename = typename std::enable_if<
std::is_same<T, APFloat>::value>::type>
llvm::iterator_range<FloatElementIterator> getValues() const {
return getFloatValues();
}
FloatElementIterator float_value_begin() const;
FloatElementIterator float_value_end() const;
//===--------------------------------------------------------------------===//
// Mutation Utilities
//===--------------------------------------------------------------------===//
/// Return a new DenseElementsAttr that has the same data as the current
/// attribute, but has been reshaped to 'newType'. The new type must have the
/// same total number of elements as well as element type.
DenseElementsAttr reshape(ShapedType newType);
/// Generates a new DenseElementsAttr by mapping each int value to a new
/// underlying APInt. The new values can represent either a integer or float.
/// This underlying type must be an DenseIntElementsAttr.
DenseElementsAttr mapValues(Type newElementType,
function_ref<APInt(const APInt &)> mapping) const;
/// Generates a new DenseElementsAttr by mapping each float value to a new
/// underlying APInt. the new values can represent either a integer or float.
/// This underlying type must be an DenseFPElementsAttr.
DenseElementsAttr
mapValues(Type newElementType,
function_ref<APInt(const APFloat &)> mapping) const;
protected:
/// Return the raw storage data held by this attribute.
ArrayRef<char> getRawData() const;
/// Get iterators to the raw APInt values for each element in this attribute.
IntElementIterator raw_int_begin() const {
return IntElementIterator(*this, 0);
}
IntElementIterator raw_int_end() const {
return IntElementIterator(*this, getNumElements());
}
/// Constructs a dense elements attribute from an array of raw APInt values.
/// Each APInt value is expected to have the same bitwidth as the element type
/// of 'type'. 'type' must be a vector or tensor with static shape.
static DenseElementsAttr getRaw(ShapedType type, ArrayRef<APInt> values);
/// Get or create a new dense elements attribute instance with the given raw
/// data buffer. 'type' must be a vector or tensor with static shape.
static DenseElementsAttr getRaw(ShapedType type, ArrayRef<char> data,
bool isSplat);
/// Overload of the raw 'get' method that asserts that the given type is of
/// integer or floating-point type. This method is used to verify type
/// invariants that the templatized 'get' method cannot.
static DenseElementsAttr getRawIntOrFloat(ShapedType type,
ArrayRef<char> data,
int64_t dataEltSize, bool isInt);
/// Check the information for a c++ data type, check if this type is valid for
/// the current attribute. This method is used to verify specific type
/// invariants that the templatized 'getValues' method cannot.
bool isValidIntOrFloat(int64_t dataEltSize, bool isInt) const;
};
/// An attribute that represents a reference to a dense float vector or tensor
/// object. Each element is stored as a double.
class DenseFPElementsAttr : public DenseElementsAttr {
public:
using iterator = DenseElementsAttr::FloatElementIterator;
using DenseElementsAttr::DenseElementsAttr;
/// Get an instance of a DenseFPElementsAttr with the given arguments. This
/// simply wraps the DenseElementsAttr::get calls.
template <typename Arg>
static DenseFPElementsAttr get(const ShapedType &type, Arg &&arg) {
return DenseElementsAttr::get(type, llvm::makeArrayRef(arg))
.template cast<DenseFPElementsAttr>();
}
template <typename T>
static DenseFPElementsAttr get(const ShapedType &type,
const std::initializer_list<T> &list) {
return DenseElementsAttr::get(type, list)
.template cast<DenseFPElementsAttr>();
}
/// Generates a new DenseElementsAttr by mapping each value attribute, and
/// constructing the DenseElementsAttr given the new element type.
DenseElementsAttr
mapValues(Type newElementType,
function_ref<APInt(const APFloat &)> mapping) const;