blob: 8d2de10976134c65280c8471af2852b36c37b0a8 [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 {
36struct FunctionTypeKeyInfo : DenseMapInfo<FunctionType*> {
37 // Functions are uniqued based on their inputs and results.
38 using KeyTy = std::pair<ArrayRef<Type*>, ArrayRef<Type*>>;
39 using DenseMapInfo<FunctionType*>::getHashValue;
40 using DenseMapInfo<FunctionType*>::isEqual;
41
42 static unsigned getHashValue(KeyTy key) {
43 return hash_combine(hash_combine_range(key.first.begin(), key.first.end()),
44 hash_combine_range(key.second.begin(),
45 key.second.end()));
46 }
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
Chris Lattnerf7e22732018-06-22 22:03:48 -070078struct VectorTypeKeyInfo : DenseMapInfo<VectorType*> {
79 // Vectors are uniqued based on their element type and shape.
80 using KeyTy = std::pair<Type*, ArrayRef<unsigned>>;
81 using DenseMapInfo<VectorType*>::getHashValue;
82 using DenseMapInfo<VectorType*>::isEqual;
83
84 static unsigned getHashValue(KeyTy key) {
85 return hash_combine(DenseMapInfo<Type*>::getHashValue(key.first),
86 hash_combine_range(key.second.begin(),
87 key.second.end()));
88 }
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
MLIR Team355ec862018-06-23 18:09:09 -070097struct RankedTensorTypeKeyInfo : DenseMapInfo<RankedTensorType*> {
98 // Ranked tensors are uniqued based on their element type and shape.
99 using KeyTy = std::pair<Type*, ArrayRef<int>>;
100 using DenseMapInfo<RankedTensorType*>::getHashValue;
101 using DenseMapInfo<RankedTensorType*>::isEqual;
102
103 static unsigned getHashValue(KeyTy key) {
104 return hash_combine(DenseMapInfo<Type*>::getHashValue(key.first),
105 hash_combine_range(key.second.begin(),
106 key.second.end()));
107 }
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
MLIR Team718c82f2018-07-16 09:45:22 -0700116struct MemRefTypeKeyInfo : DenseMapInfo<MemRefType*> {
117 // MemRefs are uniqued based on their element type, shape, affine map
118 // composition, and memory space.
119 using KeyTy = std::tuple<Type*, ArrayRef<int>, ArrayRef<AffineMap*>,
120 unsigned>;
121 using DenseMapInfo<MemRefType*>::getHashValue;
122 using DenseMapInfo<MemRefType*>::isEqual;
123
124 static unsigned getHashValue(KeyTy key) {
125 return hash_combine(
126 DenseMapInfo<Type*>::getHashValue(std::get<0>(key)),
127 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
Chris Lattner36b4ed12018-07-04 10:43:29 -0700140struct ArrayAttrKeyInfo : DenseMapInfo<ArrayAttr*> {
141 // Array attributes are uniqued based on their elements.
142 using KeyTy = ArrayRef<Attribute*>;
143 using DenseMapInfo<ArrayAttr*>::getHashValue;
144 using DenseMapInfo<ArrayAttr*>::isEqual;
145
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
176
177namespace mlir {
178/// This is the implementation of the MLIRContext class, using the pImpl idiom.
179/// This class is completely private to this file, so everything is public.
180class MLIRContextImpl {
181public:
182 /// We put immortal objects into this allocator.
183 llvm::BumpPtrAllocator allocator;
184
Chris Lattnerff0d5902018-07-05 09:12:11 -0700185 /// This is the set of all operations that are registered with the system.
186 OperationSet operationSet;
187
Chris Lattnered65a732018-06-28 20:45:33 -0700188 /// These are identifiers uniqued into this MLIRContext.
189 llvm::StringMap<char, llvm::BumpPtrAllocator&> identifiers;
190
Chris Lattnerf7e22732018-06-22 22:03:48 -0700191 // Primitive type uniquing.
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700192 PrimitiveType *primitives[int(Type::Kind::LAST_PRIMITIVE_TYPE)+1] = {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.
204 DenseMap<unsigned, IntegerType*> integers;
205
Chris Lattnerf7e22732018-06-22 22:03:48 -0700206 /// Function type uniquing.
207 using FunctionTypeSet = DenseSet<FunctionType*, FunctionTypeKeyInfo>;
208 FunctionTypeSet functions;
209
210 /// Vector type uniquing.
211 using VectorTypeSet = DenseSet<VectorType*, VectorTypeKeyInfo>;
212 VectorTypeSet vectors;
213
MLIR Team355ec862018-06-23 18:09:09 -0700214 /// Ranked tensor type uniquing.
215 using RankedTensorTypeSet = DenseSet<RankedTensorType*,
216 RankedTensorTypeKeyInfo>;
217 RankedTensorTypeSet rankedTensors;
218
219 /// Unranked tensor type uniquing.
220 DenseMap<Type*, UnrankedTensorType*> unrankedTensors;
221
MLIR Team718c82f2018-07-16 09:45:22 -0700222 /// MemRef type uniquing.
223 using MemRefTypeSet = DenseSet<MemRefType*, MemRefTypeKeyInfo>;
224 MemRefTypeSet memrefs;
225
Chris Lattner36b4ed12018-07-04 10:43:29 -0700226 // Attribute uniquing.
227 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>;
232 ArrayAttrSet arrayAttrs;
MLIR Teamb61885d2018-07-18 16:29:21 -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.
245 template<typename T>
246 ArrayRef<T> copyInto(ArrayRef<T> elements) {
247 auto result = allocator.Allocate<T>(elements.size());
248 std::uninitialized_copy(elements.begin(), elements.end(), result);
249 return ArrayRef<T>(result, elements.size());
250 }
251};
252} // end namespace mlir
253
254MLIRContext::MLIRContext() : impl(new MLIRContextImpl()) {
255}
256
257MLIRContext::~MLIRContext() {
258}
259
Chris Lattnerff0d5902018-07-05 09:12:11 -0700260/// Return the operation set associated with the specified MLIRContext object.
261OperationSet &OperationSet::get(MLIRContext *context) {
262 return context->getImpl().operationSet;
263}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700264
Chris Lattner21e67f62018-07-06 10:46:19 -0700265/// If this operation has a registered operation description in the
266/// OperationSet, return it. Otherwise return null.
267/// TODO: Shouldn't have to pass a Context here.
268const AbstractOperation *
269Operation::getAbstractOperation(MLIRContext *context) const {
270 return OperationSet::get(context).lookup(getName().str());
271}
272
Chris Lattnered65a732018-06-28 20:45:33 -0700273//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700274// Identifier uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700275//===----------------------------------------------------------------------===//
276
277/// Return an identifier for the specified string.
278Identifier Identifier::get(StringRef str, const MLIRContext *context) {
279 assert(!str.empty() && "Cannot create an empty identifier");
280 assert(str.find('\0') == StringRef::npos &&
281 "Cannot create an identifier with a nul character");
282
283 auto &impl = context->getImpl();
284 auto it = impl.identifiers.insert({str, char()}).first;
285 return Identifier(it->getKeyData());
286}
287
Chris Lattnered65a732018-06-28 20:45:33 -0700288//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700289// Type uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700290//===----------------------------------------------------------------------===//
291
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700292PrimitiveType *PrimitiveType::get(Kind kind, MLIRContext *context) {
293 assert(kind <= Kind::LAST_PRIMITIVE_TYPE && "Not a primitive type kind");
Chris Lattnerf7e22732018-06-22 22:03:48 -0700294 auto &impl = context->getImpl();
295
296 // We normally have these types.
297 if (impl.primitives[(int)kind])
298 return impl.primitives[(int)kind];
299
300 // On the first use, we allocate them into the bump pointer.
301 auto *ptr = impl.allocator.Allocate<PrimitiveType>();
302
303 // Initialize the memory using placement new.
304 new(ptr) PrimitiveType(kind, context);
305
306 // Cache and return it.
307 return impl.primitives[(int)kind] = ptr;
308}
309
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700310IntegerType *IntegerType::get(unsigned width, MLIRContext *context) {
311 auto &impl = context->getImpl();
312
313 auto *&result = impl.integers[width];
314 if (!result) {
315 result = impl.allocator.Allocate<IntegerType>();
316 new (result) IntegerType(width, context);
317 }
318
319 return result;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700320}
321
322FunctionType *FunctionType::get(ArrayRef<Type*> inputs, ArrayRef<Type*> results,
323 MLIRContext *context) {
324 auto &impl = context->getImpl();
325
326 // Look to see if we already have this function type.
327 FunctionTypeKeyInfo::KeyTy key(inputs, results);
328 auto existing = impl.functions.insert_as(nullptr, key);
329
330 // If we already have it, return that value.
331 if (!existing.second)
332 return *existing.first;
333
334 // On the first use, we allocate them into the bump pointer.
335 auto *result = impl.allocator.Allocate<FunctionType>();
336
337 // Copy the inputs and results into the bump pointer.
338 SmallVector<Type*, 16> types;
339 types.reserve(inputs.size()+results.size());
340 types.append(inputs.begin(), inputs.end());
341 types.append(results.begin(), results.end());
342 auto typesList = impl.copyInto(ArrayRef<Type*>(types));
343
344 // Initialize the memory using placement new.
345 new (result) FunctionType(typesList.data(), inputs.size(), results.size(),
346 context);
347
348 // Cache and return it.
349 return *existing.first = result;
350}
351
Chris Lattnerf7e22732018-06-22 22:03:48 -0700352VectorType *VectorType::get(ArrayRef<unsigned> shape, Type *elementType) {
353 assert(!shape.empty() && "vector types must have at least one dimension");
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700354 assert((isa<PrimitiveType>(elementType) || isa<IntegerType>(elementType)) &&
Chris Lattnerf7e22732018-06-22 22:03:48 -0700355 "vectors elements must be primitives");
356
357 auto *context = elementType->getContext();
358 auto &impl = context->getImpl();
359
360 // Look to see if we already have this vector type.
361 VectorTypeKeyInfo::KeyTy key(elementType, shape);
362 auto existing = impl.vectors.insert_as(nullptr, key);
363
364 // If we already have it, return that value.
365 if (!existing.second)
366 return *existing.first;
367
368 // On the first use, we allocate them into the bump pointer.
369 auto *result = impl.allocator.Allocate<VectorType>();
370
371 // Copy the shape into the bump pointer.
372 shape = impl.copyInto(shape);
373
374 // Initialize the memory using placement new.
375 new (result) VectorType(shape, cast<PrimitiveType>(elementType), context);
376
377 // Cache and return it.
378 return *existing.first = result;
379}
MLIR Team355ec862018-06-23 18:09:09 -0700380
381
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700382TensorType::TensorType(Kind kind, Type *elementType, MLIRContext *context)
MLIR Team355ec862018-06-23 18:09:09 -0700383 : Type(kind, context), elementType(elementType) {
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700384 assert((isa<PrimitiveType>(elementType) || isa<VectorType>(elementType) ||
385 isa<IntegerType>(elementType)) &&
MLIR Team355ec862018-06-23 18:09:09 -0700386 "tensor elements must be primitives or vectors");
387 assert(isa<TensorType>(this));
388}
389
MLIR Team355ec862018-06-23 18:09:09 -0700390RankedTensorType *RankedTensorType::get(ArrayRef<int> shape,
391 Type *elementType) {
392 auto *context = elementType->getContext();
393 auto &impl = context->getImpl();
394
395 // Look to see if we already have this ranked tensor type.
396 RankedTensorTypeKeyInfo::KeyTy key(elementType, shape);
397 auto existing = impl.rankedTensors.insert_as(nullptr, key);
398
399 // If we already have it, return that value.
400 if (!existing.second)
401 return *existing.first;
402
403 // On the first use, we allocate them into the bump pointer.
404 auto *result = impl.allocator.Allocate<RankedTensorType>();
405
406 // Copy the shape into the bump pointer.
407 shape = impl.copyInto(shape);
408
409 // Initialize the memory using placement new.
410 new (result) RankedTensorType(shape, elementType, context);
411
412 // Cache and return it.
413 return *existing.first = result;
414}
415
416UnrankedTensorType *UnrankedTensorType::get(Type *elementType) {
417 auto *context = elementType->getContext();
418 auto &impl = context->getImpl();
419
420 // Look to see if we already have this unranked tensor type.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700421 auto *&result = impl.unrankedTensors[elementType];
MLIR Team355ec862018-06-23 18:09:09 -0700422
423 // If we already have it, return that value.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700424 if (result)
425 return result;
MLIR Team355ec862018-06-23 18:09:09 -0700426
427 // On the first use, we allocate them into the bump pointer.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700428 result = impl.allocator.Allocate<UnrankedTensorType>();
MLIR Team355ec862018-06-23 18:09:09 -0700429
430 // Initialize the memory using placement new.
431 new (result) UnrankedTensorType(elementType, context);
Chris Lattner36b4ed12018-07-04 10:43:29 -0700432 return result;
433}
434
MLIR Team718c82f2018-07-16 09:45:22 -0700435MemRefType *MemRefType::get(ArrayRef<int> shape, Type *elementType,
436 ArrayRef<AffineMap*> affineMapComposition,
437 unsigned memorySpace) {
438 auto *context = elementType->getContext();
439 auto &impl = context->getImpl();
440
441 // Look to see if we already have this memref type.
442 auto key = std::make_tuple(elementType, shape, affineMapComposition,
443 memorySpace);
444 auto existing = impl.memrefs.insert_as(nullptr, key);
445
446 // If we already have it, return that value.
447 if (!existing.second)
448 return *existing.first;
449
450 // On the first use, we allocate them into the bump pointer.
451 auto *result = impl.allocator.Allocate<MemRefType>();
452
453 // Copy the shape into the bump pointer.
454 shape = impl.copyInto(shape);
455
456 // Copy the affine map composition into the bump pointer.
457 // TODO(andydavis) Assert that the structure of the composition is valid.
458 affineMapComposition = impl.copyInto(ArrayRef<AffineMap*>(
459 affineMapComposition));
460
461 // Initialize the memory using placement new.
462 new (result) MemRefType(shape, elementType, affineMapComposition, memorySpace,
463 context);
464 // Cache and return it.
465 return *existing.first = result;
466}
467
Chris Lattner36b4ed12018-07-04 10:43:29 -0700468//===----------------------------------------------------------------------===//
469// Attribute uniquing
470//===----------------------------------------------------------------------===//
471
472BoolAttr *BoolAttr::get(bool value, MLIRContext *context) {
473 auto *&result = context->getImpl().boolAttrs[value];
474 if (result)
475 return result;
476
477 result = context->getImpl().allocator.Allocate<BoolAttr>();
478 new (result) BoolAttr(value);
479 return result;
480}
481
482IntegerAttr *IntegerAttr::get(int64_t value, MLIRContext *context) {
483 auto *&result = context->getImpl().integerAttrs[value];
484 if (result)
485 return result;
486
487 result = context->getImpl().allocator.Allocate<IntegerAttr>();
488 new (result) IntegerAttr(value);
489 return result;
490}
491
492FloatAttr *FloatAttr::get(double value, MLIRContext *context) {
493 // We hash based on the bit representation of the double to ensure we don't
494 // merge things like -0.0 and 0.0 in the hash comparison.
495 union {
496 double floatValue;
497 int64_t intValue;
498 };
499 floatValue = value;
500
501 auto *&result = context->getImpl().floatAttrs[intValue];
502 if (result)
503 return result;
504
505 result = context->getImpl().allocator.Allocate<FloatAttr>();
506 new (result) FloatAttr(value);
507 return result;
508}
509
510StringAttr *StringAttr::get(StringRef bytes, MLIRContext *context) {
511 auto it = context->getImpl().stringAttrs.insert({bytes, nullptr}).first;
512
513 if (it->second)
514 return it->second;
515
516 auto result = context->getImpl().allocator.Allocate<StringAttr>();
517 new (result) StringAttr(it->first());
518 it->second = result;
519 return result;
520}
521
522ArrayAttr *ArrayAttr::get(ArrayRef<Attribute*> value, MLIRContext *context) {
523 auto &impl = context->getImpl();
524
525 // Look to see if we already have this.
526 auto existing = impl.arrayAttrs.insert_as(nullptr, value);
527
528 // If we already have it, return that value.
529 if (!existing.second)
530 return *existing.first;
531
532 // On the first use, we allocate them into the bump pointer.
533 auto *result = impl.allocator.Allocate<ArrayAttr>();
534
535 // Copy the elements into the bump pointer.
536 value = impl.copyInto(value);
537
538 // Initialize the memory using placement new.
539 new (result) ArrayAttr(value);
MLIR Team355ec862018-06-23 18:09:09 -0700540
541 // Cache and return it.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700542 return *existing.first = result;
MLIR Team355ec862018-06-23 18:09:09 -0700543}
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700544
MLIR Teamb61885d2018-07-18 16:29:21 -0700545AffineMapAttr *AffineMapAttr::get(AffineMap* value, MLIRContext *context) {
546 auto *&result = context->getImpl().affineMapAttrs[value];
547 if (result)
548 return result;
549
550 result = context->getImpl().allocator.Allocate<AffineMapAttr>();
551 new (result) AffineMapAttr(value);
552 return result;
553}
554
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700555/// Perform a three-way comparison between the names of the specified
556/// NamedAttributes.
557static int compareNamedAttributes(const NamedAttribute *lhs,
558 const NamedAttribute *rhs) {
559 return lhs->first.str().compare(rhs->first.str());
560}
561
562/// Given a list of NamedAttribute's, canonicalize the list (sorting
563/// by name) and return the unique'd result. Note that the empty list is
564/// represented with a null pointer.
565AttributeListStorage *AttributeListStorage::get(ArrayRef<NamedAttribute> attrs,
566 MLIRContext *context) {
567 // We need to sort the element list to canonicalize it, but we also don't want
568 // to do a ton of work in the super common case where the element list is
569 // already sorted.
570 SmallVector<NamedAttribute, 8> storage;
571 switch (attrs.size()) {
572 case 0:
573 // An empty list is represented with a null pointer.
574 return nullptr;
575 case 1:
576 // A single element is already sorted.
577 break;
578 case 2:
579 // Don't invoke a general sort for two element case.
580 if (attrs[0].first.str() > attrs[1].first.str()) {
581 storage.push_back(attrs[1]);
582 storage.push_back(attrs[0]);
583 attrs = storage;
584 }
585 break;
586 default:
587 // Check to see they are sorted already.
588 bool isSorted = true;
589 for (unsigned i = 0, e = attrs.size() - 1; i != e; ++i) {
590 if (attrs[i].first.str() > attrs[i + 1].first.str()) {
591 isSorted = false;
592 break;
593 }
594 }
595 // If not, do a general sort.
596 if (!isSorted) {
597 storage.append(attrs.begin(), attrs.end());
598 llvm::array_pod_sort(storage.begin(), storage.end(),
599 compareNamedAttributes);
600 attrs = storage;
601 }
602 }
603
604 // Ok, now that we've canonicalized our attributes, unique them.
605 auto &impl = context->getImpl();
606
607 // Look to see if we already have this.
608 auto existing = impl.attributeLists.insert_as(nullptr, attrs);
609
610 // If we already have it, return that value.
611 if (!existing.second)
612 return *existing.first;
613
614 // Otherwise, allocate a new AttributeListStorage, unique it and return it.
615 auto byteSize =
616 AttributeListStorage::totalSizeToAlloc<NamedAttribute>(attrs.size());
617 auto rawMem = impl.allocator.Allocate(byteSize, alignof(NamedAttribute));
618
619 // Placement initialize the AggregateSymbolicValue.
620 auto result = ::new (rawMem) AttributeListStorage(attrs.size());
621 std::uninitialized_copy(attrs.begin(), attrs.end(),
622 result->getTrailingObjects<NamedAttribute>());
623 return *existing.first = result;
624}
625
Chris Lattner36b4ed12018-07-04 10:43:29 -0700626//===----------------------------------------------------------------------===//
627// AffineMap and AffineExpr uniquing
628//===----------------------------------------------------------------------===//
629
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700630AffineMap *AffineMap::get(unsigned dimCount, unsigned symbolCount,
631 ArrayRef<AffineExpr *> results,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700632 ArrayRef<AffineExpr *> rangeSizes,
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700633 MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700634 // The number of results can't be zero.
635 assert(!results.empty());
636
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700637 assert(rangeSizes.empty() || results.size() == rangeSizes.size());
638
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700639 auto &impl = context->getImpl();
640
641 // Check if we already have this affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700642 auto key = std::make_tuple(dimCount, symbolCount, results, rangeSizes);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700643 auto existing = impl.affineMaps.insert_as(nullptr, key);
644
645 // If we already have it, return that value.
646 if (!existing.second)
647 return *existing.first;
648
649 // On the first use, we allocate them into the bump pointer.
650 auto *res = impl.allocator.Allocate<AffineMap>();
651
Uday Bondhugula1e500b42018-07-12 18:04:04 -0700652 // Copy the results and range sizes into the bump pointer.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700653 results = impl.copyInto(ArrayRef<AffineExpr *>(results));
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700654 rangeSizes = impl.copyInto(ArrayRef<AffineExpr *>(rangeSizes));
655
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700656 // Initialize the memory using placement new.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700657 new (res) AffineMap(dimCount, symbolCount, results.size(), results.data(),
658 rangeSizes.empty() ? nullptr : rangeSizes.data());
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700659
660 // Cache and return it.
661 return *existing.first = res;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700662}
663
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700664/// Return a binary affine op expression with the specified op type and
665/// operands: if it doesn't exist, create it and store it; if it is already
666/// present, return from the list. The stored expressions are unique: they are
667/// constructed and stored in a simplified/canonicalized form. The result after
668/// simplification could be any form of affine expression.
669AffineExpr *AffineBinaryOpExpr::get(AffineExpr::Kind kind, AffineExpr *lhs,
670 AffineExpr *rhs, MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700671 auto &impl = context->getImpl();
672
673 // Check if we already have this affine expression.
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700674 auto keyValue = std::make_tuple((unsigned)kind, lhs, rhs);
Chris Lattner36b4ed12018-07-04 10:43:29 -0700675 auto *&result = impl.affineExprs[keyValue];
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700676
677 // If we already have it, return that value.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700678 if (result)
679 return result;
680
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700681 // Simplify the expression if possible.
682 AffineExpr *simplified;
683 switch (kind) {
684 case Kind::Add:
685 simplified = AffineBinaryOpExpr::simplifyAdd(lhs, rhs, context);
686 break;
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700687 case Kind::Mul:
688 simplified = AffineBinaryOpExpr::simplifyMul(lhs, rhs, context);
689 break;
690 case Kind::FloorDiv:
691 simplified = AffineBinaryOpExpr::simplifyFloorDiv(lhs, rhs, context);
692 break;
693 case Kind::CeilDiv:
694 simplified = AffineBinaryOpExpr::simplifyCeilDiv(lhs, rhs, context);
695 break;
696 case Kind::Mod:
697 simplified = AffineBinaryOpExpr::simplifyMod(lhs, rhs, context);
698 break;
699 default:
700 llvm_unreachable("unexpected binary affine expr");
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700701 }
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700702
703 // If simplified to a non-binary affine op expr, don't store it.
704 if (simplified && !isa<AffineBinaryOpExpr>(simplified)) {
705 // 'affineExprs' only contains uniqued AffineBinaryOpExpr's.
706 return simplified;
707 }
708
709 if (simplified)
710 // We know that it's a binary op expression.
711 return result = simplified;
712
713 // On the first use, we allocate them into the bump pointer.
714 result = impl.allocator.Allocate<AffineBinaryOpExpr>();
715 // Initialize the memory using placement new.
716 new (result) AffineBinaryOpExpr(kind, lhs, rhs);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700717 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700718}
719
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700720AffineDimExpr *AffineDimExpr::get(unsigned position, MLIRContext *context) {
721 // TODO(bondhugula): complete this
722 // FIXME: this should be POD
723 return new AffineDimExpr(position);
724}
725
726AffineSymbolExpr *AffineSymbolExpr::get(unsigned position,
727 MLIRContext *context) {
728 // TODO(bondhugula): complete this
729 // FIXME: this should be POD
730 return new AffineSymbolExpr(position);
731}
732
733AffineConstantExpr *AffineConstantExpr::get(int64_t constant,
734 MLIRContext *context) {
735 // TODO(bondhugula): complete this
736 // FIXME: this should be POD
737 return new AffineConstantExpr(constant);
738}