blob: a960223db8ee89d04c6fb142af3a1ca4850b6e04 [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"
Chris Lattner4613d9e2018-08-19 21:17:22 -070023#include "mlir/IR/Function.h"
Chris Lattner36b4ed12018-07-04 10:43:29 -070024#include "mlir/IR/Identifier.h"
Uday Bondhugulabc535622018-08-07 14:24:38 -070025#include "mlir/IR/IntegerSet.h"
Chris Lattnerff0d5902018-07-05 09:12:11 -070026#include "mlir/IR/OperationSet.h"
27#include "mlir/IR/StandardOps.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070028#include "mlir/IR/Types.h"
Chris Lattner36b4ed12018-07-04 10:43:29 -070029#include "mlir/Support/STLExtras.h"
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -070030#include "third_party/llvm/llvm/include/llvm/ADT/STLExtras.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070031#include "llvm/ADT/DenseSet.h"
Chris Lattnered65a732018-06-28 20:45:33 -070032#include "llvm/ADT/StringMap.h"
Chris Lattner95865062018-08-01 10:18:59 -070033#include "llvm/ADT/Twine.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070034#include "llvm/Support/Allocator.h"
Chris Lattner95865062018-08-01 10:18:59 -070035#include "llvm/Support/raw_ostream.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070036using namespace mlir;
37using namespace llvm;
38
39namespace {
James Molloy87d81022018-07-23 11:44:40 -070040struct FunctionTypeKeyInfo : DenseMapInfo<FunctionType *> {
Chris Lattnerf7e22732018-06-22 22:03:48 -070041 // Functions are uniqued based on their inputs and results.
James Molloy87d81022018-07-23 11:44:40 -070042 using KeyTy = std::pair<ArrayRef<Type *>, ArrayRef<Type *>>;
43 using DenseMapInfo<FunctionType *>::getHashValue;
44 using DenseMapInfo<FunctionType *>::isEqual;
Chris Lattnerf7e22732018-06-22 22:03:48 -070045
46 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -070047 return hash_combine(
48 hash_combine_range(key.first.begin(), key.first.end()),
49 hash_combine_range(key.second.begin(), key.second.end()));
Chris Lattnerf7e22732018-06-22 22:03:48 -070050 }
51
52 static bool isEqual(const KeyTy &lhs, const FunctionType *rhs) {
53 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
54 return false;
55 return lhs == KeyTy(rhs->getInputs(), rhs->getResults());
56 }
57};
Uday Bondhugula015cbb12018-07-03 20:16:08 -070058
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070059struct AffineMapKeyInfo : DenseMapInfo<AffineMap *> {
Uday Bondhugula015cbb12018-07-03 20:16:08 -070060 // Affine maps are uniqued based on their dim/symbol counts and affine
61 // expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070062 using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr *>,
63 ArrayRef<AffineExpr *>>;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070064 using DenseMapInfo<AffineMap *>::getHashValue;
65 using DenseMapInfo<AffineMap *>::isEqual;
66
67 static unsigned getHashValue(KeyTy key) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -070068 return hash_combine(
Chris Lattner36b4ed12018-07-04 10:43:29 -070069 std::get<0>(key), std::get<1>(key),
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070070 hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
71 hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070072 }
73
Uday Bondhugula015cbb12018-07-03 20:16:08 -070074 static bool isEqual(const KeyTy &lhs, const AffineMap *rhs) {
75 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
76 return false;
Chris Lattner36b4ed12018-07-04 10:43:29 -070077 return lhs == std::make_tuple(rhs->getNumDims(), rhs->getNumSymbols(),
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070078 rhs->getResults(), rhs->getRangeSizes());
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070079 }
80};
81
James Molloy87d81022018-07-23 11:44:40 -070082struct VectorTypeKeyInfo : DenseMapInfo<VectorType *> {
Chris Lattnerf7e22732018-06-22 22:03:48 -070083 // Vectors are uniqued based on their element type and shape.
James Molloy87d81022018-07-23 11:44:40 -070084 using KeyTy = std::pair<Type *, ArrayRef<unsigned>>;
85 using DenseMapInfo<VectorType *>::getHashValue;
86 using DenseMapInfo<VectorType *>::isEqual;
Chris Lattnerf7e22732018-06-22 22:03:48 -070087
88 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -070089 return hash_combine(
90 DenseMapInfo<Type *>::getHashValue(key.first),
91 hash_combine_range(key.second.begin(), key.second.end()));
Chris Lattnerf7e22732018-06-22 22:03:48 -070092 }
93
94 static bool isEqual(const KeyTy &lhs, const VectorType *rhs) {
95 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
96 return false;
97 return lhs == KeyTy(rhs->getElementType(), rhs->getShape());
98 }
99};
Chris Lattner36b4ed12018-07-04 10:43:29 -0700100
James Molloy87d81022018-07-23 11:44:40 -0700101struct RankedTensorTypeKeyInfo : DenseMapInfo<RankedTensorType *> {
MLIR Team355ec862018-06-23 18:09:09 -0700102 // Ranked tensors are uniqued based on their element type and shape.
James Molloy87d81022018-07-23 11:44:40 -0700103 using KeyTy = std::pair<Type *, ArrayRef<int>>;
104 using DenseMapInfo<RankedTensorType *>::getHashValue;
105 using DenseMapInfo<RankedTensorType *>::isEqual;
MLIR Team355ec862018-06-23 18:09:09 -0700106
107 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -0700108 return hash_combine(
109 DenseMapInfo<Type *>::getHashValue(key.first),
110 hash_combine_range(key.second.begin(), key.second.end()));
MLIR Team355ec862018-06-23 18:09:09 -0700111 }
112
113 static bool isEqual(const KeyTy &lhs, const RankedTensorType *rhs) {
114 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
115 return false;
116 return lhs == KeyTy(rhs->getElementType(), rhs->getShape());
117 }
118};
Chris Lattner36b4ed12018-07-04 10:43:29 -0700119
James Molloy87d81022018-07-23 11:44:40 -0700120struct MemRefTypeKeyInfo : DenseMapInfo<MemRefType *> {
MLIR Team718c82f2018-07-16 09:45:22 -0700121 // MemRefs are uniqued based on their element type, shape, affine map
122 // composition, and memory space.
James Molloy87d81022018-07-23 11:44:40 -0700123 using KeyTy =
124 std::tuple<Type *, ArrayRef<int>, ArrayRef<AffineMap *>, unsigned>;
125 using DenseMapInfo<MemRefType *>::getHashValue;
126 using DenseMapInfo<MemRefType *>::isEqual;
MLIR Team718c82f2018-07-16 09:45:22 -0700127
128 static unsigned getHashValue(KeyTy key) {
129 return hash_combine(
James Molloy87d81022018-07-23 11:44:40 -0700130 DenseMapInfo<Type *>::getHashValue(std::get<0>(key)),
MLIR Team718c82f2018-07-16 09:45:22 -0700131 hash_combine_range(std::get<1>(key).begin(), std::get<1>(key).end()),
132 hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
133 std::get<3>(key));
134 }
135
136 static bool isEqual(const KeyTy &lhs, const MemRefType *rhs) {
137 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
138 return false;
139 return lhs == std::make_tuple(rhs->getElementType(), rhs->getShape(),
140 rhs->getAffineMaps(), rhs->getMemorySpace());
141 }
142};
143
James Molloy87d81022018-07-23 11:44:40 -0700144struct ArrayAttrKeyInfo : DenseMapInfo<ArrayAttr *> {
Chris Lattner36b4ed12018-07-04 10:43:29 -0700145 // Array attributes are uniqued based on their elements.
James Molloy87d81022018-07-23 11:44:40 -0700146 using KeyTy = ArrayRef<Attribute *>;
147 using DenseMapInfo<ArrayAttr *>::getHashValue;
148 using DenseMapInfo<ArrayAttr *>::isEqual;
Chris Lattner36b4ed12018-07-04 10:43:29 -0700149
150 static unsigned getHashValue(KeyTy key) {
151 return hash_combine_range(key.begin(), key.end());
152 }
153
154 static bool isEqual(const KeyTy &lhs, const ArrayAttr *rhs) {
155 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
156 return false;
157 return lhs == rhs->getValue();
158 }
159};
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700160
161struct AttributeListKeyInfo : DenseMapInfo<AttributeListStorage *> {
162 // Array attributes are uniqued based on their elements.
163 using KeyTy = ArrayRef<NamedAttribute>;
164 using DenseMapInfo<AttributeListStorage *>::getHashValue;
165 using DenseMapInfo<AttributeListStorage *>::isEqual;
166
167 static unsigned getHashValue(KeyTy key) {
168 return hash_combine_range(key.begin(), key.end());
169 }
170
171 static bool isEqual(const KeyTy &lhs, const AttributeListStorage *rhs) {
172 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
173 return false;
174 return lhs == rhs->getElements();
175 }
176};
177
Chris Lattnerf7e22732018-06-22 22:03:48 -0700178} // end anonymous namespace.
179
Chris Lattnerf7e22732018-06-22 22:03:48 -0700180namespace mlir {
181/// This is the implementation of the MLIRContext class, using the pImpl idiom.
182/// This class is completely private to this file, so everything is public.
183class MLIRContextImpl {
184public:
185 /// We put immortal objects into this allocator.
186 llvm::BumpPtrAllocator allocator;
187
Chris Lattnerff0d5902018-07-05 09:12:11 -0700188 /// This is the set of all operations that are registered with the system.
189 OperationSet operationSet;
190
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700191 /// This is the handler to use to report diagnostics, or null if not
192 /// registered.
193 MLIRContext::DiagnosticHandlerTy diagnosticHandler;
Chris Lattner95865062018-08-01 10:18:59 -0700194
Chris Lattnered65a732018-06-28 20:45:33 -0700195 /// These are identifiers uniqued into this MLIRContext.
James Molloy87d81022018-07-23 11:44:40 -0700196 llvm::StringMap<char, llvm::BumpPtrAllocator &> identifiers;
Chris Lattnered65a732018-06-28 20:45:33 -0700197
Chris Lattnerc3251192018-07-27 13:09:58 -0700198 // Uniquing table for 'other' types.
199 OtherType *otherTypes[int(Type::Kind::LAST_OTHER_TYPE) -
200 int(Type::Kind::FIRST_OTHER_TYPE) + 1] = {nullptr};
201
202 // Uniquing table for 'float' types.
203 FloatType *floatTypes[int(Type::Kind::LAST_FLOATING_POINT_TYPE) -
204 int(Type::Kind::FIRST_FLOATING_POINT_TYPE) + 1] = {
James Molloy87d81022018-07-23 11:44:40 -0700205 nullptr};
Chris Lattnerf7e22732018-06-22 22:03:48 -0700206
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700207 // Affine map uniquing.
208 using AffineMapSet = DenseSet<AffineMap *, AffineMapKeyInfo>;
209 AffineMapSet affineMaps;
210
Uday Bondhugula0b80a162018-07-03 21:34:58 -0700211 // Affine binary op expression uniquing. Figure out uniquing of dimensional
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700212 // or symbolic identifiers.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700213 DenseMap<std::tuple<unsigned, AffineExpr *, AffineExpr *>, AffineExpr *>
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700214 affineExprs;
215
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700216 // Uniqui'ing of AffineDimExpr, AffineSymbolExpr's by their position.
217 std::vector<AffineDimExpr *> dimExprs;
218 std::vector<AffineSymbolExpr *> symbolExprs;
219
220 // Uniqui'ing of AffineConstantExpr using constant value as key.
221 DenseMap<int64_t, AffineConstantExpr *> constExprs;
222
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700223 /// Integer type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700224 DenseMap<unsigned, IntegerType *> integers;
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700225
Chris Lattnerf7e22732018-06-22 22:03:48 -0700226 /// Function type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700227 using FunctionTypeSet = DenseSet<FunctionType *, FunctionTypeKeyInfo>;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700228 FunctionTypeSet functions;
229
230 /// Vector type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700231 using VectorTypeSet = DenseSet<VectorType *, VectorTypeKeyInfo>;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700232 VectorTypeSet vectors;
233
MLIR Team355ec862018-06-23 18:09:09 -0700234 /// Ranked tensor type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700235 using RankedTensorTypeSet =
236 DenseSet<RankedTensorType *, RankedTensorTypeKeyInfo>;
MLIR Team355ec862018-06-23 18:09:09 -0700237 RankedTensorTypeSet rankedTensors;
238
239 /// Unranked tensor type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700240 DenseMap<Type *, UnrankedTensorType *> unrankedTensors;
MLIR Team355ec862018-06-23 18:09:09 -0700241
MLIR Team718c82f2018-07-16 09:45:22 -0700242 /// MemRef type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700243 using MemRefTypeSet = DenseSet<MemRefType *, MemRefTypeKeyInfo>;
MLIR Team718c82f2018-07-16 09:45:22 -0700244 MemRefTypeSet memrefs;
245
Chris Lattner36b4ed12018-07-04 10:43:29 -0700246 // Attribute uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700247 BoolAttr *boolAttrs[2] = {nullptr};
248 DenseMap<int64_t, IntegerAttr *> integerAttrs;
249 DenseMap<int64_t, FloatAttr *> floatAttrs;
250 StringMap<StringAttr *> stringAttrs;
251 using ArrayAttrSet = DenseSet<ArrayAttr *, ArrayAttrKeyInfo>;
Chris Lattner36b4ed12018-07-04 10:43:29 -0700252 ArrayAttrSet arrayAttrs;
James Molloy87d81022018-07-23 11:44:40 -0700253 DenseMap<AffineMap *, AffineMapAttr *> affineMapAttrs;
James Molloyf0d2f442018-08-03 01:54:46 -0700254 DenseMap<Type *, TypeAttr *> typeAttrs;
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700255 using AttributeListSet =
256 DenseSet<AttributeListStorage *, AttributeListKeyInfo>;
257 AttributeListSet attributeLists;
Chris Lattner4613d9e2018-08-19 21:17:22 -0700258 DenseMap<Function *, FunctionAttr *> functionAttrs;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700259
260public:
Chris Lattnerff0d5902018-07-05 09:12:11 -0700261 MLIRContextImpl() : identifiers(allocator) {
262 registerStandardOperations(operationSet);
263 }
Chris Lattnered65a732018-06-28 20:45:33 -0700264
Chris Lattnerf7e22732018-06-22 22:03:48 -0700265 /// Copy the specified array of elements into memory managed by our bump
266 /// pointer allocator. This assumes the elements are all PODs.
James Molloy72b0cbe2018-08-01 12:55:27 -0700267 template <typename T>
268 ArrayRef<T> copyInto(ArrayRef<T> elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700269 auto result = allocator.Allocate<T>(elements.size());
270 std::uninitialized_copy(elements.begin(), elements.end(), result);
271 return ArrayRef<T>(result, elements.size());
272 }
273};
274} // end namespace mlir
275
James Molloy87d81022018-07-23 11:44:40 -0700276MLIRContext::MLIRContext() : impl(new MLIRContextImpl()) {}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700277
James Molloy87d81022018-07-23 11:44:40 -0700278MLIRContext::~MLIRContext() {}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700279
Chris Lattner95865062018-08-01 10:18:59 -0700280/// Register an issue handler with this LLVM context. The issue handler is
281/// passed location information if present (nullptr if not) along with a
282/// message and a boolean that indicates whether this is an error or warning.
283void MLIRContext::registerDiagnosticHandler(
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700284 const DiagnosticHandlerTy &handler) {
285 getImpl().diagnosticHandler = handler;
Chris Lattner95865062018-08-01 10:18:59 -0700286}
287
288/// This emits a diagnostic using the registered issue handle if present, or
289/// with the default behavior if not. The MLIR compiler should not generally
290/// interact with this, it should use methods on Operation instead.
291void MLIRContext::emitDiagnostic(Attribute *location,
292 const llvm::Twine &message,
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700293 DiagnosticKind kind) const {
Chris Lattner95865062018-08-01 10:18:59 -0700294 // If we had a handler registered, emit the diagnostic using it.
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700295 auto handler = getImpl().diagnosticHandler;
296 if (handler && location)
297 return handler(location, message.str(), kind);
Chris Lattner95865062018-08-01 10:18:59 -0700298
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700299 // The default behavior for notes and warnings is to ignore them.
300 if (kind != DiagnosticKind::Error)
Chris Lattner95865062018-08-01 10:18:59 -0700301 return;
302
303 // The default behavior for errors is to emit them to stderr and exit.
304 llvm::errs() << message.str() << "\n";
305 llvm::errs().flush();
306 exit(1);
307}
308
Chris Lattnerff0d5902018-07-05 09:12:11 -0700309/// Return the operation set associated with the specified MLIRContext object.
310OperationSet &OperationSet::get(MLIRContext *context) {
311 return context->getImpl().operationSet;
312}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700313
Chris Lattner21e67f62018-07-06 10:46:19 -0700314/// If this operation has a registered operation description in the
315/// OperationSet, return it. Otherwise return null.
Chris Lattner95865062018-08-01 10:18:59 -0700316const AbstractOperation *Operation::getAbstractOperation() const {
317 return OperationSet::get(getContext()).lookup(getName().str());
Chris Lattner21e67f62018-07-06 10:46:19 -0700318}
319
Chris Lattnered65a732018-06-28 20:45:33 -0700320//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700321// Identifier uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700322//===----------------------------------------------------------------------===//
323
324/// Return an identifier for the specified string.
325Identifier Identifier::get(StringRef str, const MLIRContext *context) {
326 assert(!str.empty() && "Cannot create an empty identifier");
327 assert(str.find('\0') == StringRef::npos &&
328 "Cannot create an identifier with a nul character");
329
330 auto &impl = context->getImpl();
331 auto it = impl.identifiers.insert({str, char()}).first;
332 return Identifier(it->getKeyData());
333}
334
Chris Lattnered65a732018-06-28 20:45:33 -0700335//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700336// Type uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700337//===----------------------------------------------------------------------===//
338
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700339IntegerType *IntegerType::get(unsigned width, MLIRContext *context) {
340 auto &impl = context->getImpl();
341
342 auto *&result = impl.integers[width];
343 if (!result) {
344 result = impl.allocator.Allocate<IntegerType>();
345 new (result) IntegerType(width, context);
346 }
347
348 return result;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700349}
350
Chris Lattnerc3251192018-07-27 13:09:58 -0700351FloatType *FloatType::get(Kind kind, MLIRContext *context) {
352 assert(kind >= Kind::FIRST_FLOATING_POINT_TYPE &&
353 kind <= Kind::LAST_FLOATING_POINT_TYPE && "Not an FP type kind");
354 auto &impl = context->getImpl();
355
356 // We normally have these types.
357 auto *&entry =
358 impl.floatTypes[(int)kind - int(Kind::FIRST_FLOATING_POINT_TYPE)];
359 if (entry)
360 return entry;
361
362 // On the first use, we allocate them into the bump pointer.
363 auto *ptr = impl.allocator.Allocate<FloatType>();
364
365 // Initialize the memory using placement new.
366 new (ptr) FloatType(kind, context);
367
368 // Cache and return it.
369 return entry = ptr;
370}
371
372OtherType *OtherType::get(Kind kind, MLIRContext *context) {
373 assert(kind >= Kind::FIRST_OTHER_TYPE && kind <= Kind::LAST_OTHER_TYPE &&
374 "Not an 'other' type kind");
375 auto &impl = context->getImpl();
376
377 // We normally have these types.
378 auto *&entry = impl.otherTypes[(int)kind - int(Kind::FIRST_OTHER_TYPE)];
379 if (entry)
380 return entry;
381
382 // On the first use, we allocate them into the bump pointer.
383 auto *ptr = impl.allocator.Allocate<OtherType>();
384
385 // Initialize the memory using placement new.
386 new (ptr) OtherType(kind, context);
387
388 // Cache and return it.
389 return entry = ptr;
390}
391
James Molloy87d81022018-07-23 11:44:40 -0700392FunctionType *FunctionType::get(ArrayRef<Type *> inputs,
393 ArrayRef<Type *> results,
Chris Lattnerf7e22732018-06-22 22:03:48 -0700394 MLIRContext *context) {
395 auto &impl = context->getImpl();
396
397 // Look to see if we already have this function type.
398 FunctionTypeKeyInfo::KeyTy key(inputs, results);
399 auto existing = impl.functions.insert_as(nullptr, key);
400
401 // If we already have it, return that value.
402 if (!existing.second)
403 return *existing.first;
404
405 // On the first use, we allocate them into the bump pointer.
406 auto *result = impl.allocator.Allocate<FunctionType>();
407
408 // Copy the inputs and results into the bump pointer.
James Molloy87d81022018-07-23 11:44:40 -0700409 SmallVector<Type *, 16> types;
410 types.reserve(inputs.size() + results.size());
Chris Lattnerf7e22732018-06-22 22:03:48 -0700411 types.append(inputs.begin(), inputs.end());
412 types.append(results.begin(), results.end());
James Molloy87d81022018-07-23 11:44:40 -0700413 auto typesList = impl.copyInto(ArrayRef<Type *>(types));
Chris Lattnerf7e22732018-06-22 22:03:48 -0700414
415 // Initialize the memory using placement new.
James Molloy87d81022018-07-23 11:44:40 -0700416 new (result)
417 FunctionType(typesList.data(), inputs.size(), results.size(), context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700418
419 // Cache and return it.
420 return *existing.first = result;
421}
422
Chris Lattnerf7e22732018-06-22 22:03:48 -0700423VectorType *VectorType::get(ArrayRef<unsigned> shape, Type *elementType) {
424 assert(!shape.empty() && "vector types must have at least one dimension");
Chris Lattnerc3251192018-07-27 13:09:58 -0700425 assert((isa<FloatType>(elementType) || isa<IntegerType>(elementType)) &&
Chris Lattnerf7e22732018-06-22 22:03:48 -0700426 "vectors elements must be primitives");
427
428 auto *context = elementType->getContext();
429 auto &impl = context->getImpl();
430
431 // Look to see if we already have this vector type.
432 VectorTypeKeyInfo::KeyTy key(elementType, shape);
433 auto existing = impl.vectors.insert_as(nullptr, key);
434
435 // If we already have it, return that value.
436 if (!existing.second)
437 return *existing.first;
438
439 // On the first use, we allocate them into the bump pointer.
440 auto *result = impl.allocator.Allocate<VectorType>();
441
442 // Copy the shape into the bump pointer.
443 shape = impl.copyInto(shape);
444
445 // Initialize the memory using placement new.
Jacques Pienaar3cdb8542018-07-23 11:48:22 -0700446 new (result) VectorType(shape, elementType, context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700447
448 // Cache and return it.
449 return *existing.first = result;
450}
MLIR Team355ec862018-06-23 18:09:09 -0700451
James Molloy72b0cbe2018-08-01 12:55:27 -0700452static bool isValidTensorElementType(Type *type, MLIRContext *context) {
453 return isa<FloatType>(type) || isa<VectorType>(type) ||
454 isa<IntegerType>(type) || type == Type::getTFString(context);
455}
456
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700457TensorType::TensorType(Kind kind, Type *elementType, MLIRContext *context)
James Molloy87d81022018-07-23 11:44:40 -0700458 : Type(kind, context), elementType(elementType) {
James Molloy72b0cbe2018-08-01 12:55:27 -0700459 assert(isValidTensorElementType(elementType, context));
MLIR Team355ec862018-06-23 18:09:09 -0700460 assert(isa<TensorType>(this));
461}
462
MLIR Team355ec862018-06-23 18:09:09 -0700463RankedTensorType *RankedTensorType::get(ArrayRef<int> shape,
464 Type *elementType) {
465 auto *context = elementType->getContext();
466 auto &impl = context->getImpl();
467
468 // Look to see if we already have this ranked tensor type.
469 RankedTensorTypeKeyInfo::KeyTy key(elementType, shape);
470 auto existing = impl.rankedTensors.insert_as(nullptr, key);
471
472 // If we already have it, return that value.
473 if (!existing.second)
474 return *existing.first;
475
476 // On the first use, we allocate them into the bump pointer.
477 auto *result = impl.allocator.Allocate<RankedTensorType>();
478
479 // Copy the shape into the bump pointer.
480 shape = impl.copyInto(shape);
481
482 // Initialize the memory using placement new.
483 new (result) RankedTensorType(shape, elementType, context);
484
485 // Cache and return it.
486 return *existing.first = result;
487}
488
489UnrankedTensorType *UnrankedTensorType::get(Type *elementType) {
490 auto *context = elementType->getContext();
491 auto &impl = context->getImpl();
492
493 // Look to see if we already have this unranked tensor type.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700494 auto *&result = impl.unrankedTensors[elementType];
MLIR Team355ec862018-06-23 18:09:09 -0700495
496 // If we already have it, return that value.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700497 if (result)
498 return result;
MLIR Team355ec862018-06-23 18:09:09 -0700499
500 // On the first use, we allocate them into the bump pointer.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700501 result = impl.allocator.Allocate<UnrankedTensorType>();
MLIR Team355ec862018-06-23 18:09:09 -0700502
503 // Initialize the memory using placement new.
504 new (result) UnrankedTensorType(elementType, context);
Chris Lattner36b4ed12018-07-04 10:43:29 -0700505 return result;
506}
507
MLIR Team718c82f2018-07-16 09:45:22 -0700508MemRefType *MemRefType::get(ArrayRef<int> shape, Type *elementType,
James Molloy87d81022018-07-23 11:44:40 -0700509 ArrayRef<AffineMap *> affineMapComposition,
MLIR Team718c82f2018-07-16 09:45:22 -0700510 unsigned memorySpace) {
511 auto *context = elementType->getContext();
512 auto &impl = context->getImpl();
513
514 // Look to see if we already have this memref type.
James Molloy87d81022018-07-23 11:44:40 -0700515 auto key =
516 std::make_tuple(elementType, shape, affineMapComposition, memorySpace);
MLIR Team718c82f2018-07-16 09:45:22 -0700517 auto existing = impl.memrefs.insert_as(nullptr, key);
518
519 // If we already have it, return that value.
520 if (!existing.second)
521 return *existing.first;
522
523 // On the first use, we allocate them into the bump pointer.
524 auto *result = impl.allocator.Allocate<MemRefType>();
525
526 // Copy the shape into the bump pointer.
527 shape = impl.copyInto(shape);
528
529 // Copy the affine map composition into the bump pointer.
530 // TODO(andydavis) Assert that the structure of the composition is valid.
James Molloy87d81022018-07-23 11:44:40 -0700531 affineMapComposition =
532 impl.copyInto(ArrayRef<AffineMap *>(affineMapComposition));
MLIR Team718c82f2018-07-16 09:45:22 -0700533
534 // Initialize the memory using placement new.
535 new (result) MemRefType(shape, elementType, affineMapComposition, memorySpace,
536 context);
537 // Cache and return it.
538 return *existing.first = result;
539}
540
Chris Lattner36b4ed12018-07-04 10:43:29 -0700541//===----------------------------------------------------------------------===//
542// Attribute uniquing
543//===----------------------------------------------------------------------===//
544
545BoolAttr *BoolAttr::get(bool value, MLIRContext *context) {
546 auto *&result = context->getImpl().boolAttrs[value];
547 if (result)
548 return result;
549
550 result = context->getImpl().allocator.Allocate<BoolAttr>();
551 new (result) BoolAttr(value);
552 return result;
553}
554
555IntegerAttr *IntegerAttr::get(int64_t value, MLIRContext *context) {
556 auto *&result = context->getImpl().integerAttrs[value];
557 if (result)
558 return result;
559
560 result = context->getImpl().allocator.Allocate<IntegerAttr>();
561 new (result) IntegerAttr(value);
562 return result;
563}
564
565FloatAttr *FloatAttr::get(double value, MLIRContext *context) {
566 // We hash based on the bit representation of the double to ensure we don't
567 // merge things like -0.0 and 0.0 in the hash comparison.
568 union {
569 double floatValue;
570 int64_t intValue;
571 };
572 floatValue = value;
573
574 auto *&result = context->getImpl().floatAttrs[intValue];
575 if (result)
576 return result;
577
578 result = context->getImpl().allocator.Allocate<FloatAttr>();
579 new (result) FloatAttr(value);
580 return result;
581}
582
583StringAttr *StringAttr::get(StringRef bytes, MLIRContext *context) {
584 auto it = context->getImpl().stringAttrs.insert({bytes, nullptr}).first;
585
586 if (it->second)
587 return it->second;
588
589 auto result = context->getImpl().allocator.Allocate<StringAttr>();
590 new (result) StringAttr(it->first());
591 it->second = result;
592 return result;
593}
594
James Molloy87d81022018-07-23 11:44:40 -0700595ArrayAttr *ArrayAttr::get(ArrayRef<Attribute *> value, MLIRContext *context) {
Chris Lattner36b4ed12018-07-04 10:43:29 -0700596 auto &impl = context->getImpl();
597
598 // Look to see if we already have this.
599 auto existing = impl.arrayAttrs.insert_as(nullptr, value);
600
601 // If we already have it, return that value.
602 if (!existing.second)
603 return *existing.first;
604
605 // On the first use, we allocate them into the bump pointer.
606 auto *result = impl.allocator.Allocate<ArrayAttr>();
607
608 // Copy the elements into the bump pointer.
609 value = impl.copyInto(value);
610
611 // Initialize the memory using placement new.
612 new (result) ArrayAttr(value);
MLIR Team355ec862018-06-23 18:09:09 -0700613
614 // Cache and return it.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700615 return *existing.first = result;
MLIR Team355ec862018-06-23 18:09:09 -0700616}
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700617
James Molloy87d81022018-07-23 11:44:40 -0700618AffineMapAttr *AffineMapAttr::get(AffineMap *value, MLIRContext *context) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700619 auto *&result = context->getImpl().affineMapAttrs[value];
620 if (result)
621 return result;
622
623 result = context->getImpl().allocator.Allocate<AffineMapAttr>();
624 new (result) AffineMapAttr(value);
625 return result;
626}
627
James Molloyf0d2f442018-08-03 01:54:46 -0700628TypeAttr *TypeAttr::get(Type *type, MLIRContext *context) {
629 auto *&result = context->getImpl().typeAttrs[type];
630 if (result)
631 return result;
632
633 result = context->getImpl().allocator.Allocate<TypeAttr>();
634 new (result) TypeAttr(type);
635 return result;
636}
637
Chris Lattner4613d9e2018-08-19 21:17:22 -0700638FunctionAttr *FunctionAttr::get(Function *value, MLIRContext *context) {
639 auto *&result = context->getImpl().functionAttrs[value];
640 if (result)
641 return result;
642
643 result = context->getImpl().allocator.Allocate<FunctionAttr>();
644 new (result) FunctionAttr(value);
645 return result;
646}
647
648/// This function is used by the internals of the Function class to null out
649/// attributes refering to functions that are about to be deleted.
650void FunctionAttr::dropFunctionReference(Function *value) {
651 // Check to see if there was an attribute referring to this function.
652 auto &functionAttrs = value->getContext()->getImpl().functionAttrs;
653
654 // If not, then we're done.
655 auto it = functionAttrs.find(value);
656 if (it == functionAttrs.end())
657 return;
658
659 // If so, null out the function reference in the attribute (to avoid dangling
660 // pointers) and remove the entry from the map so the map doesn't contain
661 // dangling keys.
662 it->second->value = nullptr;
663 functionAttrs.erase(it);
664}
665
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700666/// Perform a three-way comparison between the names of the specified
667/// NamedAttributes.
668static int compareNamedAttributes(const NamedAttribute *lhs,
669 const NamedAttribute *rhs) {
670 return lhs->first.str().compare(rhs->first.str());
671}
672
673/// Given a list of NamedAttribute's, canonicalize the list (sorting
674/// by name) and return the unique'd result. Note that the empty list is
675/// represented with a null pointer.
676AttributeListStorage *AttributeListStorage::get(ArrayRef<NamedAttribute> attrs,
677 MLIRContext *context) {
678 // We need to sort the element list to canonicalize it, but we also don't want
679 // to do a ton of work in the super common case where the element list is
680 // already sorted.
681 SmallVector<NamedAttribute, 8> storage;
682 switch (attrs.size()) {
683 case 0:
684 // An empty list is represented with a null pointer.
685 return nullptr;
686 case 1:
687 // A single element is already sorted.
688 break;
689 case 2:
690 // Don't invoke a general sort for two element case.
691 if (attrs[0].first.str() > attrs[1].first.str()) {
692 storage.push_back(attrs[1]);
693 storage.push_back(attrs[0]);
694 attrs = storage;
695 }
696 break;
697 default:
698 // Check to see they are sorted already.
699 bool isSorted = true;
700 for (unsigned i = 0, e = attrs.size() - 1; i != e; ++i) {
701 if (attrs[i].first.str() > attrs[i + 1].first.str()) {
702 isSorted = false;
703 break;
704 }
705 }
706 // If not, do a general sort.
707 if (!isSorted) {
708 storage.append(attrs.begin(), attrs.end());
709 llvm::array_pod_sort(storage.begin(), storage.end(),
710 compareNamedAttributes);
711 attrs = storage;
712 }
713 }
714
715 // Ok, now that we've canonicalized our attributes, unique them.
716 auto &impl = context->getImpl();
717
718 // Look to see if we already have this.
719 auto existing = impl.attributeLists.insert_as(nullptr, attrs);
720
721 // If we already have it, return that value.
722 if (!existing.second)
723 return *existing.first;
724
725 // Otherwise, allocate a new AttributeListStorage, unique it and return it.
726 auto byteSize =
727 AttributeListStorage::totalSizeToAlloc<NamedAttribute>(attrs.size());
728 auto rawMem = impl.allocator.Allocate(byteSize, alignof(NamedAttribute));
729
730 // Placement initialize the AggregateSymbolicValue.
731 auto result = ::new (rawMem) AttributeListStorage(attrs.size());
732 std::uninitialized_copy(attrs.begin(), attrs.end(),
733 result->getTrailingObjects<NamedAttribute>());
734 return *existing.first = result;
735}
736
Chris Lattner36b4ed12018-07-04 10:43:29 -0700737//===----------------------------------------------------------------------===//
738// AffineMap and AffineExpr uniquing
739//===----------------------------------------------------------------------===//
740
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700741AffineMap *AffineMap::get(unsigned dimCount, unsigned symbolCount,
742 ArrayRef<AffineExpr *> results,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700743 ArrayRef<AffineExpr *> rangeSizes,
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700744 MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700745 // The number of results can't be zero.
746 assert(!results.empty());
747
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700748 assert(rangeSizes.empty() || results.size() == rangeSizes.size());
749
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700750 auto &impl = context->getImpl();
751
752 // Check if we already have this affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700753 auto key = std::make_tuple(dimCount, symbolCount, results, rangeSizes);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700754 auto existing = impl.affineMaps.insert_as(nullptr, key);
755
756 // If we already have it, return that value.
757 if (!existing.second)
758 return *existing.first;
759
760 // On the first use, we allocate them into the bump pointer.
761 auto *res = impl.allocator.Allocate<AffineMap>();
762
Uday Bondhugula1e500b42018-07-12 18:04:04 -0700763 // Copy the results and range sizes into the bump pointer.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700764 results = impl.copyInto(ArrayRef<AffineExpr *>(results));
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700765 rangeSizes = impl.copyInto(ArrayRef<AffineExpr *>(rangeSizes));
766
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700767 // Initialize the memory using placement new.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700768 new (res) AffineMap(dimCount, symbolCount, results.size(), results.data(),
769 rangeSizes.empty() ? nullptr : rangeSizes.data());
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700770
771 // Cache and return it.
772 return *existing.first = res;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700773}
774
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700775/// Return a binary affine op expression with the specified op type and
776/// operands: if it doesn't exist, create it and store it; if it is already
777/// present, return from the list. The stored expressions are unique: they are
778/// constructed and stored in a simplified/canonicalized form. The result after
779/// simplification could be any form of affine expression.
780AffineExpr *AffineBinaryOpExpr::get(AffineExpr::Kind kind, AffineExpr *lhs,
781 AffineExpr *rhs, MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700782 auto &impl = context->getImpl();
783
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700784 // Check if we already have this affine expression, and return it if we do.
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700785 auto keyValue = std::make_tuple((unsigned)kind, lhs, rhs);
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700786 auto cached = impl.affineExprs.find(keyValue);
787 if (cached != impl.affineExprs.end())
788 return cached->second;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700789
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700790 // Simplify the expression if possible.
791 AffineExpr *simplified;
792 switch (kind) {
793 case Kind::Add:
794 simplified = AffineBinaryOpExpr::simplifyAdd(lhs, rhs, context);
795 break;
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700796 case Kind::Mul:
797 simplified = AffineBinaryOpExpr::simplifyMul(lhs, rhs, context);
798 break;
799 case Kind::FloorDiv:
800 simplified = AffineBinaryOpExpr::simplifyFloorDiv(lhs, rhs, context);
801 break;
802 case Kind::CeilDiv:
803 simplified = AffineBinaryOpExpr::simplifyCeilDiv(lhs, rhs, context);
804 break;
805 case Kind::Mod:
806 simplified = AffineBinaryOpExpr::simplifyMod(lhs, rhs, context);
807 break;
808 default:
809 llvm_unreachable("unexpected binary affine expr");
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700810 }
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700811
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700812 // The simplified one would have already been cached; just return it.
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700813 if (simplified)
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700814 return simplified;
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700815
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700816 // An expression with these operands will already be in the
817 // simplified/canonical form. Create and store it.
818 auto *result = impl.allocator.Allocate<AffineBinaryOpExpr>();
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700819 // Initialize the memory using placement new.
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700820 new (result) AffineBinaryOpExpr(kind, lhs, rhs);
821 bool inserted = impl.affineExprs.insert({keyValue, result}).second;
822 assert(inserted && "the expression shouldn't already exist in the map");
823 (void)inserted;
824 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700825}
826
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700827AffineDimExpr *AffineDimExpr::get(unsigned position, MLIRContext *context) {
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700828 auto &impl = context->getImpl();
829
830 // Check if we need to resize.
831 if (position >= impl.dimExprs.size())
832 impl.dimExprs.resize(position + 1, nullptr);
833
834 auto *&result = impl.dimExprs[position];
835 if (result)
836 return result;
837
838 result = impl.allocator.Allocate<AffineDimExpr>();
839 // Initialize the memory using placement new.
840 new (result) AffineDimExpr(position);
841 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700842}
843
844AffineSymbolExpr *AffineSymbolExpr::get(unsigned position,
845 MLIRContext *context) {
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700846 auto &impl = context->getImpl();
847
848 // Check if we need to resize.
849 if (position >= impl.symbolExprs.size())
850 impl.symbolExprs.resize(position + 1, nullptr);
851
852 auto *&result = impl.symbolExprs[position];
853 if (result)
854 return result;
855
856 result = impl.allocator.Allocate<AffineSymbolExpr>();
857 // Initialize the memory using placement new.
858 new (result) AffineSymbolExpr(position);
859 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700860}
861
862AffineConstantExpr *AffineConstantExpr::get(int64_t constant,
863 MLIRContext *context) {
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700864 auto &impl = context->getImpl();
865 auto *&result = impl.constExprs[constant];
866
867 if (result)
868 return result;
869
870 result = impl.allocator.Allocate<AffineConstantExpr>();
871 // Initialize the memory using placement new.
872 new (result) AffineConstantExpr(constant);
873 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700874}
Uday Bondhugulabc535622018-08-07 14:24:38 -0700875
876//===----------------------------------------------------------------------===//
877// Integer Sets: these are allocated into the bump pointer, and are immutable.
878// But they aren't uniqued like AffineMap's; there isn't an advantage to.
879//===----------------------------------------------------------------------===//
880
881IntegerSet *IntegerSet::get(unsigned dimCount, unsigned symbolCount,
882 ArrayRef<AffineExpr *> constraints,
883 ArrayRef<bool> eqFlags, MLIRContext *context) {
884 assert(eqFlags.size() == constraints.size());
885
886 auto &impl = context->getImpl();
887
888 // Allocate them into the bump pointer.
889 auto *res = impl.allocator.Allocate<IntegerSet>();
890
891 // Copy the equalities and inequalities into the bump pointer.
892 constraints = impl.copyInto(ArrayRef<AffineExpr *>(constraints));
893 eqFlags = impl.copyInto(ArrayRef<bool>(eqFlags));
894
895 // Initialize the memory using placement new.
896 return new (res) IntegerSet(dimCount, symbolCount, constraints.size(),
897 constraints.data(), eqFlags.data());
898}