blob: a74be26194b857f5f3a33f7a9198166395371edc [file] [log] [blame]
Chris Lattnerf7e22732018-06-22 22:03:48 -07001//===- MLIRContext.cpp - MLIR Type Classes --------------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17
18#include "mlir/IR/MLIRContext.h"
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -070019#include "AttributeListStorage.h"
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070020#include "mlir/IR/AffineExpr.h"
21#include "mlir/IR/AffineMap.h"
Chris Lattner36b4ed12018-07-04 10:43:29 -070022#include "mlir/IR/Attributes.h"
23#include "mlir/IR/Identifier.h"
Chris Lattnerff0d5902018-07-05 09:12:11 -070024#include "mlir/IR/OperationSet.h"
25#include "mlir/IR/StandardOps.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070026#include "mlir/IR/Types.h"
Chris Lattner36b4ed12018-07-04 10:43:29 -070027#include "mlir/Support/STLExtras.h"
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -070028#include "third_party/llvm/llvm/include/llvm/ADT/STLExtras.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070029#include "llvm/ADT/DenseSet.h"
Chris Lattnered65a732018-06-28 20:45:33 -070030#include "llvm/ADT/StringMap.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070031#include "llvm/Support/Allocator.h"
32using namespace mlir;
33using namespace llvm;
34
35namespace {
James Molloy87d81022018-07-23 11:44:40 -070036struct FunctionTypeKeyInfo : DenseMapInfo<FunctionType *> {
Chris Lattnerf7e22732018-06-22 22:03:48 -070037 // Functions are uniqued based on their inputs and results.
James Molloy87d81022018-07-23 11:44:40 -070038 using KeyTy = std::pair<ArrayRef<Type *>, ArrayRef<Type *>>;
39 using DenseMapInfo<FunctionType *>::getHashValue;
40 using DenseMapInfo<FunctionType *>::isEqual;
Chris Lattnerf7e22732018-06-22 22:03:48 -070041
42 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -070043 return hash_combine(
44 hash_combine_range(key.first.begin(), key.first.end()),
45 hash_combine_range(key.second.begin(), key.second.end()));
Chris Lattnerf7e22732018-06-22 22:03:48 -070046 }
47
48 static bool isEqual(const KeyTy &lhs, const FunctionType *rhs) {
49 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
50 return false;
51 return lhs == KeyTy(rhs->getInputs(), rhs->getResults());
52 }
53};
Uday Bondhugula015cbb12018-07-03 20:16:08 -070054
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070055struct AffineMapKeyInfo : DenseMapInfo<AffineMap *> {
Uday Bondhugula015cbb12018-07-03 20:16:08 -070056 // Affine maps are uniqued based on their dim/symbol counts and affine
57 // expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070058 using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr *>,
59 ArrayRef<AffineExpr *>>;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070060 using DenseMapInfo<AffineMap *>::getHashValue;
61 using DenseMapInfo<AffineMap *>::isEqual;
62
63 static unsigned getHashValue(KeyTy key) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -070064 return hash_combine(
Chris Lattner36b4ed12018-07-04 10:43:29 -070065 std::get<0>(key), std::get<1>(key),
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070066 hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
67 hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070068 }
69
Uday Bondhugula015cbb12018-07-03 20:16:08 -070070 static bool isEqual(const KeyTy &lhs, const AffineMap *rhs) {
71 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
72 return false;
Chris Lattner36b4ed12018-07-04 10:43:29 -070073 return lhs == std::make_tuple(rhs->getNumDims(), rhs->getNumSymbols(),
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070074 rhs->getResults(), rhs->getRangeSizes());
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070075 }
76};
77
James Molloy87d81022018-07-23 11:44:40 -070078struct VectorTypeKeyInfo : DenseMapInfo<VectorType *> {
Chris Lattnerf7e22732018-06-22 22:03:48 -070079 // Vectors are uniqued based on their element type and shape.
James Molloy87d81022018-07-23 11:44:40 -070080 using KeyTy = std::pair<Type *, ArrayRef<unsigned>>;
81 using DenseMapInfo<VectorType *>::getHashValue;
82 using DenseMapInfo<VectorType *>::isEqual;
Chris Lattnerf7e22732018-06-22 22:03:48 -070083
84 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -070085 return hash_combine(
86 DenseMapInfo<Type *>::getHashValue(key.first),
87 hash_combine_range(key.second.begin(), key.second.end()));
Chris Lattnerf7e22732018-06-22 22:03:48 -070088 }
89
90 static bool isEqual(const KeyTy &lhs, const VectorType *rhs) {
91 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
92 return false;
93 return lhs == KeyTy(rhs->getElementType(), rhs->getShape());
94 }
95};
Chris Lattner36b4ed12018-07-04 10:43:29 -070096
James Molloy87d81022018-07-23 11:44:40 -070097struct RankedTensorTypeKeyInfo : DenseMapInfo<RankedTensorType *> {
MLIR Team355ec862018-06-23 18:09:09 -070098 // Ranked tensors are uniqued based on their element type and shape.
James Molloy87d81022018-07-23 11:44:40 -070099 using KeyTy = std::pair<Type *, ArrayRef<int>>;
100 using DenseMapInfo<RankedTensorType *>::getHashValue;
101 using DenseMapInfo<RankedTensorType *>::isEqual;
MLIR Team355ec862018-06-23 18:09:09 -0700102
103 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -0700104 return hash_combine(
105 DenseMapInfo<Type *>::getHashValue(key.first),
106 hash_combine_range(key.second.begin(), key.second.end()));
MLIR Team355ec862018-06-23 18:09:09 -0700107 }
108
109 static bool isEqual(const KeyTy &lhs, const RankedTensorType *rhs) {
110 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
111 return false;
112 return lhs == KeyTy(rhs->getElementType(), rhs->getShape());
113 }
114};
Chris Lattner36b4ed12018-07-04 10:43:29 -0700115
James Molloy87d81022018-07-23 11:44:40 -0700116struct MemRefTypeKeyInfo : DenseMapInfo<MemRefType *> {
MLIR Team718c82f2018-07-16 09:45:22 -0700117 // MemRefs are uniqued based on their element type, shape, affine map
118 // composition, and memory space.
James Molloy87d81022018-07-23 11:44:40 -0700119 using KeyTy =
120 std::tuple<Type *, ArrayRef<int>, ArrayRef<AffineMap *>, unsigned>;
121 using DenseMapInfo<MemRefType *>::getHashValue;
122 using DenseMapInfo<MemRefType *>::isEqual;
MLIR Team718c82f2018-07-16 09:45:22 -0700123
124 static unsigned getHashValue(KeyTy key) {
125 return hash_combine(
James Molloy87d81022018-07-23 11:44:40 -0700126 DenseMapInfo<Type *>::getHashValue(std::get<0>(key)),
MLIR Team718c82f2018-07-16 09:45:22 -0700127 hash_combine_range(std::get<1>(key).begin(), std::get<1>(key).end()),
128 hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
129 std::get<3>(key));
130 }
131
132 static bool isEqual(const KeyTy &lhs, const MemRefType *rhs) {
133 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
134 return false;
135 return lhs == std::make_tuple(rhs->getElementType(), rhs->getShape(),
136 rhs->getAffineMaps(), rhs->getMemorySpace());
137 }
138};
139
James Molloy87d81022018-07-23 11:44:40 -0700140struct ArrayAttrKeyInfo : DenseMapInfo<ArrayAttr *> {
Chris Lattner36b4ed12018-07-04 10:43:29 -0700141 // Array attributes are uniqued based on their elements.
James Molloy87d81022018-07-23 11:44:40 -0700142 using KeyTy = ArrayRef<Attribute *>;
143 using DenseMapInfo<ArrayAttr *>::getHashValue;
144 using DenseMapInfo<ArrayAttr *>::isEqual;
Chris Lattner36b4ed12018-07-04 10:43:29 -0700145
146 static unsigned getHashValue(KeyTy key) {
147 return hash_combine_range(key.begin(), key.end());
148 }
149
150 static bool isEqual(const KeyTy &lhs, const ArrayAttr *rhs) {
151 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
152 return false;
153 return lhs == rhs->getValue();
154 }
155};
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700156
157struct AttributeListKeyInfo : DenseMapInfo<AttributeListStorage *> {
158 // Array attributes are uniqued based on their elements.
159 using KeyTy = ArrayRef<NamedAttribute>;
160 using DenseMapInfo<AttributeListStorage *>::getHashValue;
161 using DenseMapInfo<AttributeListStorage *>::isEqual;
162
163 static unsigned getHashValue(KeyTy key) {
164 return hash_combine_range(key.begin(), key.end());
165 }
166
167 static bool isEqual(const KeyTy &lhs, const AttributeListStorage *rhs) {
168 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
169 return false;
170 return lhs == rhs->getElements();
171 }
172};
173
Chris Lattnerf7e22732018-06-22 22:03:48 -0700174} // end anonymous namespace.
175
Chris Lattnerf7e22732018-06-22 22:03:48 -0700176namespace mlir {
177/// This is the implementation of the MLIRContext class, using the pImpl idiom.
178/// This class is completely private to this file, so everything is public.
179class MLIRContextImpl {
180public:
181 /// We put immortal objects into this allocator.
182 llvm::BumpPtrAllocator allocator;
183
Chris Lattnerff0d5902018-07-05 09:12:11 -0700184 /// This is the set of all operations that are registered with the system.
185 OperationSet operationSet;
186
Chris Lattnered65a732018-06-28 20:45:33 -0700187 /// These are identifiers uniqued into this MLIRContext.
James Molloy87d81022018-07-23 11:44:40 -0700188 llvm::StringMap<char, llvm::BumpPtrAllocator &> identifiers;
Chris Lattnered65a732018-06-28 20:45:33 -0700189
Chris Lattnerf7e22732018-06-22 22:03:48 -0700190 // Primitive type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700191 PrimitiveType *primitives[int(Type::Kind::LAST_PRIMITIVE_TYPE) + 1] = {
192 nullptr};
Chris Lattnerf7e22732018-06-22 22:03:48 -0700193
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700194 // Affine map uniquing.
195 using AffineMapSet = DenseSet<AffineMap *, AffineMapKeyInfo>;
196 AffineMapSet affineMaps;
197
Uday Bondhugula0b80a162018-07-03 21:34:58 -0700198 // Affine binary op expression uniquing. Figure out uniquing of dimensional
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700199 // or symbolic identifiers.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700200 DenseMap<std::tuple<unsigned, AffineExpr *, AffineExpr *>, AffineExpr *>
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700201 affineExprs;
202
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700203 /// Integer type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700204 DenseMap<unsigned, IntegerType *> integers;
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700205
Chris Lattnerf7e22732018-06-22 22:03:48 -0700206 /// Function type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700207 using FunctionTypeSet = DenseSet<FunctionType *, FunctionTypeKeyInfo>;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700208 FunctionTypeSet functions;
209
210 /// Vector type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700211 using VectorTypeSet = DenseSet<VectorType *, VectorTypeKeyInfo>;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700212 VectorTypeSet vectors;
213
MLIR Team355ec862018-06-23 18:09:09 -0700214 /// Ranked tensor type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700215 using RankedTensorTypeSet =
216 DenseSet<RankedTensorType *, RankedTensorTypeKeyInfo>;
MLIR Team355ec862018-06-23 18:09:09 -0700217 RankedTensorTypeSet rankedTensors;
218
219 /// Unranked tensor type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700220 DenseMap<Type *, UnrankedTensorType *> unrankedTensors;
MLIR Team355ec862018-06-23 18:09:09 -0700221
MLIR Team718c82f2018-07-16 09:45:22 -0700222 /// MemRef type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700223 using MemRefTypeSet = DenseSet<MemRefType *, MemRefTypeKeyInfo>;
MLIR Team718c82f2018-07-16 09:45:22 -0700224 MemRefTypeSet memrefs;
225
Chris Lattner36b4ed12018-07-04 10:43:29 -0700226 // Attribute uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700227 BoolAttr *boolAttrs[2] = {nullptr};
228 DenseMap<int64_t, IntegerAttr *> integerAttrs;
229 DenseMap<int64_t, FloatAttr *> floatAttrs;
230 StringMap<StringAttr *> stringAttrs;
231 using ArrayAttrSet = DenseSet<ArrayAttr *, ArrayAttrKeyInfo>;
Chris Lattner36b4ed12018-07-04 10:43:29 -0700232 ArrayAttrSet arrayAttrs;
James Molloy87d81022018-07-23 11:44:40 -0700233 DenseMap<AffineMap *, AffineMapAttr *> affineMapAttrs;
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700234 using AttributeListSet =
235 DenseSet<AttributeListStorage *, AttributeListKeyInfo>;
236 AttributeListSet attributeLists;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700237
238public:
Chris Lattnerff0d5902018-07-05 09:12:11 -0700239 MLIRContextImpl() : identifiers(allocator) {
240 registerStandardOperations(operationSet);
241 }
Chris Lattnered65a732018-06-28 20:45:33 -0700242
Chris Lattnerf7e22732018-06-22 22:03:48 -0700243 /// Copy the specified array of elements into memory managed by our bump
244 /// pointer allocator. This assumes the elements are all PODs.
James Molloy87d81022018-07-23 11:44:40 -0700245 template <typename T> ArrayRef<T> copyInto(ArrayRef<T> elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700246 auto result = allocator.Allocate<T>(elements.size());
247 std::uninitialized_copy(elements.begin(), elements.end(), result);
248 return ArrayRef<T>(result, elements.size());
249 }
250};
251} // end namespace mlir
252
James Molloy87d81022018-07-23 11:44:40 -0700253MLIRContext::MLIRContext() : impl(new MLIRContextImpl()) {}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700254
James Molloy87d81022018-07-23 11:44:40 -0700255MLIRContext::~MLIRContext() {}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700256
Chris Lattnerff0d5902018-07-05 09:12:11 -0700257/// Return the operation set associated with the specified MLIRContext object.
258OperationSet &OperationSet::get(MLIRContext *context) {
259 return context->getImpl().operationSet;
260}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700261
Chris Lattner21e67f62018-07-06 10:46:19 -0700262/// If this operation has a registered operation description in the
263/// OperationSet, return it. Otherwise return null.
264/// TODO: Shouldn't have to pass a Context here.
265const AbstractOperation *
266Operation::getAbstractOperation(MLIRContext *context) const {
267 return OperationSet::get(context).lookup(getName().str());
268}
269
Chris Lattnered65a732018-06-28 20:45:33 -0700270//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700271// Identifier uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700272//===----------------------------------------------------------------------===//
273
274/// Return an identifier for the specified string.
275Identifier Identifier::get(StringRef str, const MLIRContext *context) {
276 assert(!str.empty() && "Cannot create an empty identifier");
277 assert(str.find('\0') == StringRef::npos &&
278 "Cannot create an identifier with a nul character");
279
280 auto &impl = context->getImpl();
281 auto it = impl.identifiers.insert({str, char()}).first;
282 return Identifier(it->getKeyData());
283}
284
Chris Lattnered65a732018-06-28 20:45:33 -0700285//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700286// Type uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700287//===----------------------------------------------------------------------===//
288
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700289PrimitiveType *PrimitiveType::get(Kind kind, MLIRContext *context) {
290 assert(kind <= Kind::LAST_PRIMITIVE_TYPE && "Not a primitive type kind");
Chris Lattnerf7e22732018-06-22 22:03:48 -0700291 auto &impl = context->getImpl();
292
293 // We normally have these types.
294 if (impl.primitives[(int)kind])
295 return impl.primitives[(int)kind];
296
297 // On the first use, we allocate them into the bump pointer.
298 auto *ptr = impl.allocator.Allocate<PrimitiveType>();
299
300 // Initialize the memory using placement new.
James Molloy87d81022018-07-23 11:44:40 -0700301 new (ptr) PrimitiveType(kind, context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700302
303 // Cache and return it.
304 return impl.primitives[(int)kind] = ptr;
305}
306
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700307IntegerType *IntegerType::get(unsigned width, MLIRContext *context) {
308 auto &impl = context->getImpl();
309
310 auto *&result = impl.integers[width];
311 if (!result) {
312 result = impl.allocator.Allocate<IntegerType>();
313 new (result) IntegerType(width, context);
314 }
315
316 return result;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700317}
318
James Molloy87d81022018-07-23 11:44:40 -0700319FunctionType *FunctionType::get(ArrayRef<Type *> inputs,
320 ArrayRef<Type *> results,
Chris Lattnerf7e22732018-06-22 22:03:48 -0700321 MLIRContext *context) {
322 auto &impl = context->getImpl();
323
324 // Look to see if we already have this function type.
325 FunctionTypeKeyInfo::KeyTy key(inputs, results);
326 auto existing = impl.functions.insert_as(nullptr, key);
327
328 // If we already have it, return that value.
329 if (!existing.second)
330 return *existing.first;
331
332 // On the first use, we allocate them into the bump pointer.
333 auto *result = impl.allocator.Allocate<FunctionType>();
334
335 // Copy the inputs and results into the bump pointer.
James Molloy87d81022018-07-23 11:44:40 -0700336 SmallVector<Type *, 16> types;
337 types.reserve(inputs.size() + results.size());
Chris Lattnerf7e22732018-06-22 22:03:48 -0700338 types.append(inputs.begin(), inputs.end());
339 types.append(results.begin(), results.end());
James Molloy87d81022018-07-23 11:44:40 -0700340 auto typesList = impl.copyInto(ArrayRef<Type *>(types));
Chris Lattnerf7e22732018-06-22 22:03:48 -0700341
342 // Initialize the memory using placement new.
James Molloy87d81022018-07-23 11:44:40 -0700343 new (result)
344 FunctionType(typesList.data(), inputs.size(), results.size(), context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700345
346 // Cache and return it.
347 return *existing.first = result;
348}
349
Chris Lattnerf7e22732018-06-22 22:03:48 -0700350VectorType *VectorType::get(ArrayRef<unsigned> shape, Type *elementType) {
351 assert(!shape.empty() && "vector types must have at least one dimension");
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700352 assert((isa<PrimitiveType>(elementType) || isa<IntegerType>(elementType)) &&
Chris Lattnerf7e22732018-06-22 22:03:48 -0700353 "vectors elements must be primitives");
354
355 auto *context = elementType->getContext();
356 auto &impl = context->getImpl();
357
358 // Look to see if we already have this vector type.
359 VectorTypeKeyInfo::KeyTy key(elementType, shape);
360 auto existing = impl.vectors.insert_as(nullptr, key);
361
362 // If we already have it, return that value.
363 if (!existing.second)
364 return *existing.first;
365
366 // On the first use, we allocate them into the bump pointer.
367 auto *result = impl.allocator.Allocate<VectorType>();
368
369 // Copy the shape into the bump pointer.
370 shape = impl.copyInto(shape);
371
372 // Initialize the memory using placement new.
Jacques Pienaar3cdb8542018-07-23 11:48:22 -0700373 new (result) VectorType(shape, elementType, context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700374
375 // Cache and return it.
376 return *existing.first = result;
377}
MLIR Team355ec862018-06-23 18:09:09 -0700378
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700379TensorType::TensorType(Kind kind, Type *elementType, MLIRContext *context)
James Molloy87d81022018-07-23 11:44:40 -0700380 : Type(kind, context), elementType(elementType) {
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700381 assert((isa<PrimitiveType>(elementType) || isa<VectorType>(elementType) ||
382 isa<IntegerType>(elementType)) &&
MLIR Team355ec862018-06-23 18:09:09 -0700383 "tensor elements must be primitives or vectors");
384 assert(isa<TensorType>(this));
385}
386
MLIR Team355ec862018-06-23 18:09:09 -0700387RankedTensorType *RankedTensorType::get(ArrayRef<int> shape,
388 Type *elementType) {
389 auto *context = elementType->getContext();
390 auto &impl = context->getImpl();
391
392 // Look to see if we already have this ranked tensor type.
393 RankedTensorTypeKeyInfo::KeyTy key(elementType, shape);
394 auto existing = impl.rankedTensors.insert_as(nullptr, key);
395
396 // If we already have it, return that value.
397 if (!existing.second)
398 return *existing.first;
399
400 // On the first use, we allocate them into the bump pointer.
401 auto *result = impl.allocator.Allocate<RankedTensorType>();
402
403 // Copy the shape into the bump pointer.
404 shape = impl.copyInto(shape);
405
406 // Initialize the memory using placement new.
407 new (result) RankedTensorType(shape, elementType, context);
408
409 // Cache and return it.
410 return *existing.first = result;
411}
412
413UnrankedTensorType *UnrankedTensorType::get(Type *elementType) {
414 auto *context = elementType->getContext();
415 auto &impl = context->getImpl();
416
417 // Look to see if we already have this unranked tensor type.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700418 auto *&result = impl.unrankedTensors[elementType];
MLIR Team355ec862018-06-23 18:09:09 -0700419
420 // If we already have it, return that value.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700421 if (result)
422 return result;
MLIR Team355ec862018-06-23 18:09:09 -0700423
424 // On the first use, we allocate them into the bump pointer.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700425 result = impl.allocator.Allocate<UnrankedTensorType>();
MLIR Team355ec862018-06-23 18:09:09 -0700426
427 // Initialize the memory using placement new.
428 new (result) UnrankedTensorType(elementType, context);
Chris Lattner36b4ed12018-07-04 10:43:29 -0700429 return result;
430}
431
MLIR Team718c82f2018-07-16 09:45:22 -0700432MemRefType *MemRefType::get(ArrayRef<int> shape, Type *elementType,
James Molloy87d81022018-07-23 11:44:40 -0700433 ArrayRef<AffineMap *> affineMapComposition,
MLIR Team718c82f2018-07-16 09:45:22 -0700434 unsigned memorySpace) {
435 auto *context = elementType->getContext();
436 auto &impl = context->getImpl();
437
438 // Look to see if we already have this memref type.
James Molloy87d81022018-07-23 11:44:40 -0700439 auto key =
440 std::make_tuple(elementType, shape, affineMapComposition, memorySpace);
MLIR Team718c82f2018-07-16 09:45:22 -0700441 auto existing = impl.memrefs.insert_as(nullptr, key);
442
443 // If we already have it, return that value.
444 if (!existing.second)
445 return *existing.first;
446
447 // On the first use, we allocate them into the bump pointer.
448 auto *result = impl.allocator.Allocate<MemRefType>();
449
450 // Copy the shape into the bump pointer.
451 shape = impl.copyInto(shape);
452
453 // Copy the affine map composition into the bump pointer.
454 // TODO(andydavis) Assert that the structure of the composition is valid.
James Molloy87d81022018-07-23 11:44:40 -0700455 affineMapComposition =
456 impl.copyInto(ArrayRef<AffineMap *>(affineMapComposition));
MLIR Team718c82f2018-07-16 09:45:22 -0700457
458 // Initialize the memory using placement new.
459 new (result) MemRefType(shape, elementType, affineMapComposition, memorySpace,
460 context);
461 // Cache and return it.
462 return *existing.first = result;
463}
464
Chris Lattner36b4ed12018-07-04 10:43:29 -0700465//===----------------------------------------------------------------------===//
466// Attribute uniquing
467//===----------------------------------------------------------------------===//
468
469BoolAttr *BoolAttr::get(bool value, MLIRContext *context) {
470 auto *&result = context->getImpl().boolAttrs[value];
471 if (result)
472 return result;
473
474 result = context->getImpl().allocator.Allocate<BoolAttr>();
475 new (result) BoolAttr(value);
476 return result;
477}
478
479IntegerAttr *IntegerAttr::get(int64_t value, MLIRContext *context) {
480 auto *&result = context->getImpl().integerAttrs[value];
481 if (result)
482 return result;
483
484 result = context->getImpl().allocator.Allocate<IntegerAttr>();
485 new (result) IntegerAttr(value);
486 return result;
487}
488
489FloatAttr *FloatAttr::get(double value, MLIRContext *context) {
490 // We hash based on the bit representation of the double to ensure we don't
491 // merge things like -0.0 and 0.0 in the hash comparison.
492 union {
493 double floatValue;
494 int64_t intValue;
495 };
496 floatValue = value;
497
498 auto *&result = context->getImpl().floatAttrs[intValue];
499 if (result)
500 return result;
501
502 result = context->getImpl().allocator.Allocate<FloatAttr>();
503 new (result) FloatAttr(value);
504 return result;
505}
506
507StringAttr *StringAttr::get(StringRef bytes, MLIRContext *context) {
508 auto it = context->getImpl().stringAttrs.insert({bytes, nullptr}).first;
509
510 if (it->second)
511 return it->second;
512
513 auto result = context->getImpl().allocator.Allocate<StringAttr>();
514 new (result) StringAttr(it->first());
515 it->second = result;
516 return result;
517}
518
James Molloy87d81022018-07-23 11:44:40 -0700519ArrayAttr *ArrayAttr::get(ArrayRef<Attribute *> value, MLIRContext *context) {
Chris Lattner36b4ed12018-07-04 10:43:29 -0700520 auto &impl = context->getImpl();
521
522 // Look to see if we already have this.
523 auto existing = impl.arrayAttrs.insert_as(nullptr, value);
524
525 // If we already have it, return that value.
526 if (!existing.second)
527 return *existing.first;
528
529 // On the first use, we allocate them into the bump pointer.
530 auto *result = impl.allocator.Allocate<ArrayAttr>();
531
532 // Copy the elements into the bump pointer.
533 value = impl.copyInto(value);
534
535 // Initialize the memory using placement new.
536 new (result) ArrayAttr(value);
MLIR Team355ec862018-06-23 18:09:09 -0700537
538 // Cache and return it.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700539 return *existing.first = result;
MLIR Team355ec862018-06-23 18:09:09 -0700540}
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700541
James Molloy87d81022018-07-23 11:44:40 -0700542AffineMapAttr *AffineMapAttr::get(AffineMap *value, MLIRContext *context) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700543 auto *&result = context->getImpl().affineMapAttrs[value];
544 if (result)
545 return result;
546
547 result = context->getImpl().allocator.Allocate<AffineMapAttr>();
548 new (result) AffineMapAttr(value);
549 return result;
550}
551
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700552/// Perform a three-way comparison between the names of the specified
553/// NamedAttributes.
554static int compareNamedAttributes(const NamedAttribute *lhs,
555 const NamedAttribute *rhs) {
556 return lhs->first.str().compare(rhs->first.str());
557}
558
559/// Given a list of NamedAttribute's, canonicalize the list (sorting
560/// by name) and return the unique'd result. Note that the empty list is
561/// represented with a null pointer.
562AttributeListStorage *AttributeListStorage::get(ArrayRef<NamedAttribute> attrs,
563 MLIRContext *context) {
564 // We need to sort the element list to canonicalize it, but we also don't want
565 // to do a ton of work in the super common case where the element list is
566 // already sorted.
567 SmallVector<NamedAttribute, 8> storage;
568 switch (attrs.size()) {
569 case 0:
570 // An empty list is represented with a null pointer.
571 return nullptr;
572 case 1:
573 // A single element is already sorted.
574 break;
575 case 2:
576 // Don't invoke a general sort for two element case.
577 if (attrs[0].first.str() > attrs[1].first.str()) {
578 storage.push_back(attrs[1]);
579 storage.push_back(attrs[0]);
580 attrs = storage;
581 }
582 break;
583 default:
584 // Check to see they are sorted already.
585 bool isSorted = true;
586 for (unsigned i = 0, e = attrs.size() - 1; i != e; ++i) {
587 if (attrs[i].first.str() > attrs[i + 1].first.str()) {
588 isSorted = false;
589 break;
590 }
591 }
592 // If not, do a general sort.
593 if (!isSorted) {
594 storage.append(attrs.begin(), attrs.end());
595 llvm::array_pod_sort(storage.begin(), storage.end(),
596 compareNamedAttributes);
597 attrs = storage;
598 }
599 }
600
601 // Ok, now that we've canonicalized our attributes, unique them.
602 auto &impl = context->getImpl();
603
604 // Look to see if we already have this.
605 auto existing = impl.attributeLists.insert_as(nullptr, attrs);
606
607 // If we already have it, return that value.
608 if (!existing.second)
609 return *existing.first;
610
611 // Otherwise, allocate a new AttributeListStorage, unique it and return it.
612 auto byteSize =
613 AttributeListStorage::totalSizeToAlloc<NamedAttribute>(attrs.size());
614 auto rawMem = impl.allocator.Allocate(byteSize, alignof(NamedAttribute));
615
616 // Placement initialize the AggregateSymbolicValue.
617 auto result = ::new (rawMem) AttributeListStorage(attrs.size());
618 std::uninitialized_copy(attrs.begin(), attrs.end(),
619 result->getTrailingObjects<NamedAttribute>());
620 return *existing.first = result;
621}
622
Chris Lattner36b4ed12018-07-04 10:43:29 -0700623//===----------------------------------------------------------------------===//
624// AffineMap and AffineExpr uniquing
625//===----------------------------------------------------------------------===//
626
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700627AffineMap *AffineMap::get(unsigned dimCount, unsigned symbolCount,
628 ArrayRef<AffineExpr *> results,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700629 ArrayRef<AffineExpr *> rangeSizes,
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700630 MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700631 // The number of results can't be zero.
632 assert(!results.empty());
633
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700634 assert(rangeSizes.empty() || results.size() == rangeSizes.size());
635
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700636 auto &impl = context->getImpl();
637
638 // Check if we already have this affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700639 auto key = std::make_tuple(dimCount, symbolCount, results, rangeSizes);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700640 auto existing = impl.affineMaps.insert_as(nullptr, key);
641
642 // If we already have it, return that value.
643 if (!existing.second)
644 return *existing.first;
645
646 // On the first use, we allocate them into the bump pointer.
647 auto *res = impl.allocator.Allocate<AffineMap>();
648
Uday Bondhugula1e500b42018-07-12 18:04:04 -0700649 // Copy the results and range sizes into the bump pointer.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700650 results = impl.copyInto(ArrayRef<AffineExpr *>(results));
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700651 rangeSizes = impl.copyInto(ArrayRef<AffineExpr *>(rangeSizes));
652
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700653 // Initialize the memory using placement new.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700654 new (res) AffineMap(dimCount, symbolCount, results.size(), results.data(),
655 rangeSizes.empty() ? nullptr : rangeSizes.data());
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700656
657 // Cache and return it.
658 return *existing.first = res;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700659}
660
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700661/// Return a binary affine op expression with the specified op type and
662/// operands: if it doesn't exist, create it and store it; if it is already
663/// present, return from the list. The stored expressions are unique: they are
664/// constructed and stored in a simplified/canonicalized form. The result after
665/// simplification could be any form of affine expression.
666AffineExpr *AffineBinaryOpExpr::get(AffineExpr::Kind kind, AffineExpr *lhs,
667 AffineExpr *rhs, MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700668 auto &impl = context->getImpl();
669
670 // Check if we already have this affine expression.
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700671 auto keyValue = std::make_tuple((unsigned)kind, lhs, rhs);
Chris Lattner36b4ed12018-07-04 10:43:29 -0700672 auto *&result = impl.affineExprs[keyValue];
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700673
674 // If we already have it, return that value.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700675 if (result)
676 return result;
677
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700678 // Simplify the expression if possible.
679 AffineExpr *simplified;
680 switch (kind) {
681 case Kind::Add:
682 simplified = AffineBinaryOpExpr::simplifyAdd(lhs, rhs, context);
683 break;
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700684 case Kind::Mul:
685 simplified = AffineBinaryOpExpr::simplifyMul(lhs, rhs, context);
686 break;
687 case Kind::FloorDiv:
688 simplified = AffineBinaryOpExpr::simplifyFloorDiv(lhs, rhs, context);
689 break;
690 case Kind::CeilDiv:
691 simplified = AffineBinaryOpExpr::simplifyCeilDiv(lhs, rhs, context);
692 break;
693 case Kind::Mod:
694 simplified = AffineBinaryOpExpr::simplifyMod(lhs, rhs, context);
695 break;
696 default:
697 llvm_unreachable("unexpected binary affine expr");
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700698 }
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700699
700 // If simplified to a non-binary affine op expr, don't store it.
701 if (simplified && !isa<AffineBinaryOpExpr>(simplified)) {
702 // 'affineExprs' only contains uniqued AffineBinaryOpExpr's.
703 return simplified;
704 }
705
706 if (simplified)
707 // We know that it's a binary op expression.
708 return result = simplified;
709
710 // On the first use, we allocate them into the bump pointer.
711 result = impl.allocator.Allocate<AffineBinaryOpExpr>();
712 // Initialize the memory using placement new.
713 new (result) AffineBinaryOpExpr(kind, lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700714 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700715}
716
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700717AffineDimExpr *AffineDimExpr::get(unsigned position, MLIRContext *context) {
718 // TODO(bondhugula): complete this
719 // FIXME: this should be POD
720 return new AffineDimExpr(position);
721}
722
723AffineSymbolExpr *AffineSymbolExpr::get(unsigned position,
724 MLIRContext *context) {
725 // TODO(bondhugula): complete this
726 // FIXME: this should be POD
727 return new AffineSymbolExpr(position);
728}
729
730AffineConstantExpr *AffineConstantExpr::get(int64_t constant,
731 MLIRContext *context) {
732 // TODO(bondhugula): complete this
733 // FIXME: this should be POD
734 return new AffineConstantExpr(constant);
735}