blob: f558ae105e7196155b4d8f3d9c590c2e6f95a207 [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 Lattner95865062018-08-01 10:18:59 -070031#include "llvm/ADT/Twine.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070032#include "llvm/Support/Allocator.h"
Chris Lattner95865062018-08-01 10:18:59 -070033#include "llvm/Support/raw_ostream.h"
Chris Lattnerf7e22732018-06-22 22:03:48 -070034using namespace mlir;
35using namespace llvm;
36
37namespace {
James Molloy87d81022018-07-23 11:44:40 -070038struct FunctionTypeKeyInfo : DenseMapInfo<FunctionType *> {
Chris Lattnerf7e22732018-06-22 22:03:48 -070039 // Functions are uniqued based on their inputs and results.
James Molloy87d81022018-07-23 11:44:40 -070040 using KeyTy = std::pair<ArrayRef<Type *>, ArrayRef<Type *>>;
41 using DenseMapInfo<FunctionType *>::getHashValue;
42 using DenseMapInfo<FunctionType *>::isEqual;
Chris Lattnerf7e22732018-06-22 22:03:48 -070043
44 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -070045 return hash_combine(
46 hash_combine_range(key.first.begin(), key.first.end()),
47 hash_combine_range(key.second.begin(), key.second.end()));
Chris Lattnerf7e22732018-06-22 22:03:48 -070048 }
49
50 static bool isEqual(const KeyTy &lhs, const FunctionType *rhs) {
51 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
52 return false;
53 return lhs == KeyTy(rhs->getInputs(), rhs->getResults());
54 }
55};
Uday Bondhugula015cbb12018-07-03 20:16:08 -070056
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070057struct AffineMapKeyInfo : DenseMapInfo<AffineMap *> {
Uday Bondhugula015cbb12018-07-03 20:16:08 -070058 // Affine maps are uniqued based on their dim/symbol counts and affine
59 // expressions.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070060 using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr *>,
61 ArrayRef<AffineExpr *>>;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070062 using DenseMapInfo<AffineMap *>::getHashValue;
63 using DenseMapInfo<AffineMap *>::isEqual;
64
65 static unsigned getHashValue(KeyTy key) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -070066 return hash_combine(
Chris Lattner36b4ed12018-07-04 10:43:29 -070067 std::get<0>(key), std::get<1>(key),
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070068 hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
69 hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070070 }
71
Uday Bondhugula015cbb12018-07-03 20:16:08 -070072 static bool isEqual(const KeyTy &lhs, const AffineMap *rhs) {
73 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
74 return false;
Chris Lattner36b4ed12018-07-04 10:43:29 -070075 return lhs == std::make_tuple(rhs->getNumDims(), rhs->getNumSymbols(),
Uday Bondhugula0115dbb2018-07-11 21:31:07 -070076 rhs->getResults(), rhs->getRangeSizes());
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070077 }
78};
79
James Molloy87d81022018-07-23 11:44:40 -070080struct VectorTypeKeyInfo : DenseMapInfo<VectorType *> {
Chris Lattnerf7e22732018-06-22 22:03:48 -070081 // Vectors are uniqued based on their element type and shape.
James Molloy87d81022018-07-23 11:44:40 -070082 using KeyTy = std::pair<Type *, ArrayRef<unsigned>>;
83 using DenseMapInfo<VectorType *>::getHashValue;
84 using DenseMapInfo<VectorType *>::isEqual;
Chris Lattnerf7e22732018-06-22 22:03:48 -070085
86 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -070087 return hash_combine(
88 DenseMapInfo<Type *>::getHashValue(key.first),
89 hash_combine_range(key.second.begin(), key.second.end()));
Chris Lattnerf7e22732018-06-22 22:03:48 -070090 }
91
92 static bool isEqual(const KeyTy &lhs, const VectorType *rhs) {
93 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
94 return false;
95 return lhs == KeyTy(rhs->getElementType(), rhs->getShape());
96 }
97};
Chris Lattner36b4ed12018-07-04 10:43:29 -070098
James Molloy87d81022018-07-23 11:44:40 -070099struct RankedTensorTypeKeyInfo : DenseMapInfo<RankedTensorType *> {
MLIR Team355ec862018-06-23 18:09:09 -0700100 // Ranked tensors are uniqued based on their element type and shape.
James Molloy87d81022018-07-23 11:44:40 -0700101 using KeyTy = std::pair<Type *, ArrayRef<int>>;
102 using DenseMapInfo<RankedTensorType *>::getHashValue;
103 using DenseMapInfo<RankedTensorType *>::isEqual;
MLIR Team355ec862018-06-23 18:09:09 -0700104
105 static unsigned getHashValue(KeyTy key) {
James Molloy87d81022018-07-23 11:44:40 -0700106 return hash_combine(
107 DenseMapInfo<Type *>::getHashValue(key.first),
108 hash_combine_range(key.second.begin(), key.second.end()));
MLIR Team355ec862018-06-23 18:09:09 -0700109 }
110
111 static bool isEqual(const KeyTy &lhs, const RankedTensorType *rhs) {
112 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
113 return false;
114 return lhs == KeyTy(rhs->getElementType(), rhs->getShape());
115 }
116};
Chris Lattner36b4ed12018-07-04 10:43:29 -0700117
James Molloy87d81022018-07-23 11:44:40 -0700118struct MemRefTypeKeyInfo : DenseMapInfo<MemRefType *> {
MLIR Team718c82f2018-07-16 09:45:22 -0700119 // MemRefs are uniqued based on their element type, shape, affine map
120 // composition, and memory space.
James Molloy87d81022018-07-23 11:44:40 -0700121 using KeyTy =
122 std::tuple<Type *, ArrayRef<int>, ArrayRef<AffineMap *>, unsigned>;
123 using DenseMapInfo<MemRefType *>::getHashValue;
124 using DenseMapInfo<MemRefType *>::isEqual;
MLIR Team718c82f2018-07-16 09:45:22 -0700125
126 static unsigned getHashValue(KeyTy key) {
127 return hash_combine(
James Molloy87d81022018-07-23 11:44:40 -0700128 DenseMapInfo<Type *>::getHashValue(std::get<0>(key)),
MLIR Team718c82f2018-07-16 09:45:22 -0700129 hash_combine_range(std::get<1>(key).begin(), std::get<1>(key).end()),
130 hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
131 std::get<3>(key));
132 }
133
134 static bool isEqual(const KeyTy &lhs, const MemRefType *rhs) {
135 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
136 return false;
137 return lhs == std::make_tuple(rhs->getElementType(), rhs->getShape(),
138 rhs->getAffineMaps(), rhs->getMemorySpace());
139 }
140};
141
James Molloy87d81022018-07-23 11:44:40 -0700142struct ArrayAttrKeyInfo : DenseMapInfo<ArrayAttr *> {
Chris Lattner36b4ed12018-07-04 10:43:29 -0700143 // Array attributes are uniqued based on their elements.
James Molloy87d81022018-07-23 11:44:40 -0700144 using KeyTy = ArrayRef<Attribute *>;
145 using DenseMapInfo<ArrayAttr *>::getHashValue;
146 using DenseMapInfo<ArrayAttr *>::isEqual;
Chris Lattner36b4ed12018-07-04 10:43:29 -0700147
148 static unsigned getHashValue(KeyTy key) {
149 return hash_combine_range(key.begin(), key.end());
150 }
151
152 static bool isEqual(const KeyTy &lhs, const ArrayAttr *rhs) {
153 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
154 return false;
155 return lhs == rhs->getValue();
156 }
157};
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700158
159struct AttributeListKeyInfo : DenseMapInfo<AttributeListStorage *> {
160 // Array attributes are uniqued based on their elements.
161 using KeyTy = ArrayRef<NamedAttribute>;
162 using DenseMapInfo<AttributeListStorage *>::getHashValue;
163 using DenseMapInfo<AttributeListStorage *>::isEqual;
164
165 static unsigned getHashValue(KeyTy key) {
166 return hash_combine_range(key.begin(), key.end());
167 }
168
169 static bool isEqual(const KeyTy &lhs, const AttributeListStorage *rhs) {
170 if (rhs == getEmptyKey() || rhs == getTombstoneKey())
171 return false;
172 return lhs == rhs->getElements();
173 }
174};
175
Chris Lattnerf7e22732018-06-22 22:03:48 -0700176} // end anonymous namespace.
177
Chris Lattnerf7e22732018-06-22 22:03:48 -0700178namespace mlir {
179/// This is the implementation of the MLIRContext class, using the pImpl idiom.
180/// This class is completely private to this file, so everything is public.
181class MLIRContextImpl {
182public:
183 /// We put immortal objects into this allocator.
184 llvm::BumpPtrAllocator allocator;
185
Chris Lattnerff0d5902018-07-05 09:12:11 -0700186 /// This is the set of all operations that are registered with the system.
187 OperationSet operationSet;
188
Chris Lattner95865062018-08-01 10:18:59 -0700189 /// This is the handler to use to report issues, or null if not registered.
190 std::function<void(Attribute *location, StringRef message, bool isError)>
191 issueHandler;
192
Chris Lattnered65a732018-06-28 20:45:33 -0700193 /// These are identifiers uniqued into this MLIRContext.
James Molloy87d81022018-07-23 11:44:40 -0700194 llvm::StringMap<char, llvm::BumpPtrAllocator &> identifiers;
Chris Lattnered65a732018-06-28 20:45:33 -0700195
Chris Lattnerc3251192018-07-27 13:09:58 -0700196 // Uniquing table for 'other' types.
197 OtherType *otherTypes[int(Type::Kind::LAST_OTHER_TYPE) -
198 int(Type::Kind::FIRST_OTHER_TYPE) + 1] = {nullptr};
199
200 // Uniquing table for 'float' types.
201 FloatType *floatTypes[int(Type::Kind::LAST_FLOATING_POINT_TYPE) -
202 int(Type::Kind::FIRST_FLOATING_POINT_TYPE) + 1] = {
James Molloy87d81022018-07-23 11:44:40 -0700203 nullptr};
Chris Lattnerf7e22732018-06-22 22:03:48 -0700204
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700205 // Affine map uniquing.
206 using AffineMapSet = DenseSet<AffineMap *, AffineMapKeyInfo>;
207 AffineMapSet affineMaps;
208
Uday Bondhugula0b80a162018-07-03 21:34:58 -0700209 // Affine binary op expression uniquing. Figure out uniquing of dimensional
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700210 // or symbolic identifiers.
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700211 DenseMap<std::tuple<unsigned, AffineExpr *, AffineExpr *>, AffineExpr *>
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700212 affineExprs;
213
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700214 // Uniqui'ing of AffineDimExpr, AffineSymbolExpr's by their position.
215 std::vector<AffineDimExpr *> dimExprs;
216 std::vector<AffineSymbolExpr *> symbolExprs;
217
218 // Uniqui'ing of AffineConstantExpr using constant value as key.
219 DenseMap<int64_t, AffineConstantExpr *> constExprs;
220
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700221 /// Integer type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700222 DenseMap<unsigned, IntegerType *> integers;
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700223
Chris Lattnerf7e22732018-06-22 22:03:48 -0700224 /// Function type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700225 using FunctionTypeSet = DenseSet<FunctionType *, FunctionTypeKeyInfo>;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700226 FunctionTypeSet functions;
227
228 /// Vector type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700229 using VectorTypeSet = DenseSet<VectorType *, VectorTypeKeyInfo>;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700230 VectorTypeSet vectors;
231
MLIR Team355ec862018-06-23 18:09:09 -0700232 /// Ranked tensor type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700233 using RankedTensorTypeSet =
234 DenseSet<RankedTensorType *, RankedTensorTypeKeyInfo>;
MLIR Team355ec862018-06-23 18:09:09 -0700235 RankedTensorTypeSet rankedTensors;
236
237 /// Unranked tensor type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700238 DenseMap<Type *, UnrankedTensorType *> unrankedTensors;
MLIR Team355ec862018-06-23 18:09:09 -0700239
MLIR Team718c82f2018-07-16 09:45:22 -0700240 /// MemRef type uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700241 using MemRefTypeSet = DenseSet<MemRefType *, MemRefTypeKeyInfo>;
MLIR Team718c82f2018-07-16 09:45:22 -0700242 MemRefTypeSet memrefs;
243
Chris Lattner36b4ed12018-07-04 10:43:29 -0700244 // Attribute uniquing.
James Molloy87d81022018-07-23 11:44:40 -0700245 BoolAttr *boolAttrs[2] = {nullptr};
246 DenseMap<int64_t, IntegerAttr *> integerAttrs;
247 DenseMap<int64_t, FloatAttr *> floatAttrs;
248 StringMap<StringAttr *> stringAttrs;
249 using ArrayAttrSet = DenseSet<ArrayAttr *, ArrayAttrKeyInfo>;
Chris Lattner36b4ed12018-07-04 10:43:29 -0700250 ArrayAttrSet arrayAttrs;
James Molloy87d81022018-07-23 11:44:40 -0700251 DenseMap<AffineMap *, AffineMapAttr *> affineMapAttrs;
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700252 using AttributeListSet =
253 DenseSet<AttributeListStorage *, AttributeListKeyInfo>;
254 AttributeListSet attributeLists;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700255
256public:
Chris Lattnerff0d5902018-07-05 09:12:11 -0700257 MLIRContextImpl() : identifiers(allocator) {
258 registerStandardOperations(operationSet);
259 }
Chris Lattnered65a732018-06-28 20:45:33 -0700260
Chris Lattnerf7e22732018-06-22 22:03:48 -0700261 /// Copy the specified array of elements into memory managed by our bump
262 /// pointer allocator. This assumes the elements are all PODs.
James Molloy72b0cbe2018-08-01 12:55:27 -0700263 template <typename T>
264 ArrayRef<T> copyInto(ArrayRef<T> elements) {
Chris Lattnerf7e22732018-06-22 22:03:48 -0700265 auto result = allocator.Allocate<T>(elements.size());
266 std::uninitialized_copy(elements.begin(), elements.end(), result);
267 return ArrayRef<T>(result, elements.size());
268 }
269};
270} // end namespace mlir
271
James Molloy87d81022018-07-23 11:44:40 -0700272MLIRContext::MLIRContext() : impl(new MLIRContextImpl()) {}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700273
James Molloy87d81022018-07-23 11:44:40 -0700274MLIRContext::~MLIRContext() {}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700275
Chris Lattner95865062018-08-01 10:18:59 -0700276/// Register an issue handler with this LLVM context. The issue handler is
277/// passed location information if present (nullptr if not) along with a
278/// message and a boolean that indicates whether this is an error or warning.
279void MLIRContext::registerDiagnosticHandler(
280 const std::function<void(Attribute *location, StringRef message,
281 bool isError)> &handler) {
282 getImpl().issueHandler = handler;
283}
284
285/// This emits a diagnostic using the registered issue handle if present, or
286/// with the default behavior if not. The MLIR compiler should not generally
287/// interact with this, it should use methods on Operation instead.
288void MLIRContext::emitDiagnostic(Attribute *location,
289 const llvm::Twine &message,
290 bool isError) const {
291 // If we had a handler registered, emit the diagnostic using it.
292 auto handler = getImpl().issueHandler;
293 if (handler)
294 return handler(location, message.str(), isError);
295
296 // The default behavior for warnings is to ignore them.
297 if (!isError)
298 return;
299
300 // The default behavior for errors is to emit them to stderr and exit.
301 llvm::errs() << message.str() << "\n";
302 llvm::errs().flush();
303 exit(1);
304}
305
Chris Lattnerff0d5902018-07-05 09:12:11 -0700306/// Return the operation set associated with the specified MLIRContext object.
307OperationSet &OperationSet::get(MLIRContext *context) {
308 return context->getImpl().operationSet;
309}
Chris Lattnerf7e22732018-06-22 22:03:48 -0700310
Chris Lattner21e67f62018-07-06 10:46:19 -0700311/// If this operation has a registered operation description in the
312/// OperationSet, return it. Otherwise return null.
Chris Lattner95865062018-08-01 10:18:59 -0700313const AbstractOperation *Operation::getAbstractOperation() const {
314 return OperationSet::get(getContext()).lookup(getName().str());
Chris Lattner21e67f62018-07-06 10:46:19 -0700315}
316
Chris Lattnered65a732018-06-28 20:45:33 -0700317//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700318// Identifier uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700319//===----------------------------------------------------------------------===//
320
321/// Return an identifier for the specified string.
322Identifier Identifier::get(StringRef str, const MLIRContext *context) {
323 assert(!str.empty() && "Cannot create an empty identifier");
324 assert(str.find('\0') == StringRef::npos &&
325 "Cannot create an identifier with a nul character");
326
327 auto &impl = context->getImpl();
328 auto it = impl.identifiers.insert({str, char()}).first;
329 return Identifier(it->getKeyData());
330}
331
Chris Lattnered65a732018-06-28 20:45:33 -0700332//===----------------------------------------------------------------------===//
Chris Lattner36b4ed12018-07-04 10:43:29 -0700333// Type uniquing
Chris Lattnered65a732018-06-28 20:45:33 -0700334//===----------------------------------------------------------------------===//
335
Chris Lattnerf958bbe2018-06-29 22:08:05 -0700336IntegerType *IntegerType::get(unsigned width, MLIRContext *context) {
337 auto &impl = context->getImpl();
338
339 auto *&result = impl.integers[width];
340 if (!result) {
341 result = impl.allocator.Allocate<IntegerType>();
342 new (result) IntegerType(width, context);
343 }
344
345 return result;
Chris Lattnerf7e22732018-06-22 22:03:48 -0700346}
347
Chris Lattnerc3251192018-07-27 13:09:58 -0700348FloatType *FloatType::get(Kind kind, MLIRContext *context) {
349 assert(kind >= Kind::FIRST_FLOATING_POINT_TYPE &&
350 kind <= Kind::LAST_FLOATING_POINT_TYPE && "Not an FP type kind");
351 auto &impl = context->getImpl();
352
353 // We normally have these types.
354 auto *&entry =
355 impl.floatTypes[(int)kind - int(Kind::FIRST_FLOATING_POINT_TYPE)];
356 if (entry)
357 return entry;
358
359 // On the first use, we allocate them into the bump pointer.
360 auto *ptr = impl.allocator.Allocate<FloatType>();
361
362 // Initialize the memory using placement new.
363 new (ptr) FloatType(kind, context);
364
365 // Cache and return it.
366 return entry = ptr;
367}
368
369OtherType *OtherType::get(Kind kind, MLIRContext *context) {
370 assert(kind >= Kind::FIRST_OTHER_TYPE && kind <= Kind::LAST_OTHER_TYPE &&
371 "Not an 'other' type kind");
372 auto &impl = context->getImpl();
373
374 // We normally have these types.
375 auto *&entry = impl.otherTypes[(int)kind - int(Kind::FIRST_OTHER_TYPE)];
376 if (entry)
377 return entry;
378
379 // On the first use, we allocate them into the bump pointer.
380 auto *ptr = impl.allocator.Allocate<OtherType>();
381
382 // Initialize the memory using placement new.
383 new (ptr) OtherType(kind, context);
384
385 // Cache and return it.
386 return entry = ptr;
387}
388
James Molloy87d81022018-07-23 11:44:40 -0700389FunctionType *FunctionType::get(ArrayRef<Type *> inputs,
390 ArrayRef<Type *> results,
Chris Lattnerf7e22732018-06-22 22:03:48 -0700391 MLIRContext *context) {
392 auto &impl = context->getImpl();
393
394 // Look to see if we already have this function type.
395 FunctionTypeKeyInfo::KeyTy key(inputs, results);
396 auto existing = impl.functions.insert_as(nullptr, key);
397
398 // If we already have it, return that value.
399 if (!existing.second)
400 return *existing.first;
401
402 // On the first use, we allocate them into the bump pointer.
403 auto *result = impl.allocator.Allocate<FunctionType>();
404
405 // Copy the inputs and results into the bump pointer.
James Molloy87d81022018-07-23 11:44:40 -0700406 SmallVector<Type *, 16> types;
407 types.reserve(inputs.size() + results.size());
Chris Lattnerf7e22732018-06-22 22:03:48 -0700408 types.append(inputs.begin(), inputs.end());
409 types.append(results.begin(), results.end());
James Molloy87d81022018-07-23 11:44:40 -0700410 auto typesList = impl.copyInto(ArrayRef<Type *>(types));
Chris Lattnerf7e22732018-06-22 22:03:48 -0700411
412 // Initialize the memory using placement new.
James Molloy87d81022018-07-23 11:44:40 -0700413 new (result)
414 FunctionType(typesList.data(), inputs.size(), results.size(), context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700415
416 // Cache and return it.
417 return *existing.first = result;
418}
419
Chris Lattnerf7e22732018-06-22 22:03:48 -0700420VectorType *VectorType::get(ArrayRef<unsigned> shape, Type *elementType) {
421 assert(!shape.empty() && "vector types must have at least one dimension");
Chris Lattnerc3251192018-07-27 13:09:58 -0700422 assert((isa<FloatType>(elementType) || isa<IntegerType>(elementType)) &&
Chris Lattnerf7e22732018-06-22 22:03:48 -0700423 "vectors elements must be primitives");
424
425 auto *context = elementType->getContext();
426 auto &impl = context->getImpl();
427
428 // Look to see if we already have this vector type.
429 VectorTypeKeyInfo::KeyTy key(elementType, shape);
430 auto existing = impl.vectors.insert_as(nullptr, key);
431
432 // If we already have it, return that value.
433 if (!existing.second)
434 return *existing.first;
435
436 // On the first use, we allocate them into the bump pointer.
437 auto *result = impl.allocator.Allocate<VectorType>();
438
439 // Copy the shape into the bump pointer.
440 shape = impl.copyInto(shape);
441
442 // Initialize the memory using placement new.
Jacques Pienaar3cdb8542018-07-23 11:48:22 -0700443 new (result) VectorType(shape, elementType, context);
Chris Lattnerf7e22732018-06-22 22:03:48 -0700444
445 // Cache and return it.
446 return *existing.first = result;
447}
MLIR Team355ec862018-06-23 18:09:09 -0700448
James Molloy72b0cbe2018-08-01 12:55:27 -0700449static bool isValidTensorElementType(Type *type, MLIRContext *context) {
450 return isa<FloatType>(type) || isa<VectorType>(type) ||
451 isa<IntegerType>(type) || type == Type::getTFString(context);
452}
453
Chris Lattnereee1a2d2018-07-04 09:13:39 -0700454TensorType::TensorType(Kind kind, Type *elementType, MLIRContext *context)
James Molloy87d81022018-07-23 11:44:40 -0700455 : Type(kind, context), elementType(elementType) {
James Molloy72b0cbe2018-08-01 12:55:27 -0700456 assert(isValidTensorElementType(elementType, context));
MLIR Team355ec862018-06-23 18:09:09 -0700457 assert(isa<TensorType>(this));
458}
459
MLIR Team355ec862018-06-23 18:09:09 -0700460RankedTensorType *RankedTensorType::get(ArrayRef<int> shape,
461 Type *elementType) {
462 auto *context = elementType->getContext();
463 auto &impl = context->getImpl();
464
465 // Look to see if we already have this ranked tensor type.
466 RankedTensorTypeKeyInfo::KeyTy key(elementType, shape);
467 auto existing = impl.rankedTensors.insert_as(nullptr, key);
468
469 // If we already have it, return that value.
470 if (!existing.second)
471 return *existing.first;
472
473 // On the first use, we allocate them into the bump pointer.
474 auto *result = impl.allocator.Allocate<RankedTensorType>();
475
476 // Copy the shape into the bump pointer.
477 shape = impl.copyInto(shape);
478
479 // Initialize the memory using placement new.
480 new (result) RankedTensorType(shape, elementType, context);
481
482 // Cache and return it.
483 return *existing.first = result;
484}
485
486UnrankedTensorType *UnrankedTensorType::get(Type *elementType) {
487 auto *context = elementType->getContext();
488 auto &impl = context->getImpl();
489
490 // Look to see if we already have this unranked tensor type.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700491 auto *&result = impl.unrankedTensors[elementType];
MLIR Team355ec862018-06-23 18:09:09 -0700492
493 // If we already have it, return that value.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700494 if (result)
495 return result;
MLIR Team355ec862018-06-23 18:09:09 -0700496
497 // On the first use, we allocate them into the bump pointer.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700498 result = impl.allocator.Allocate<UnrankedTensorType>();
MLIR Team355ec862018-06-23 18:09:09 -0700499
500 // Initialize the memory using placement new.
501 new (result) UnrankedTensorType(elementType, context);
Chris Lattner36b4ed12018-07-04 10:43:29 -0700502 return result;
503}
504
MLIR Team718c82f2018-07-16 09:45:22 -0700505MemRefType *MemRefType::get(ArrayRef<int> shape, Type *elementType,
James Molloy87d81022018-07-23 11:44:40 -0700506 ArrayRef<AffineMap *> affineMapComposition,
MLIR Team718c82f2018-07-16 09:45:22 -0700507 unsigned memorySpace) {
508 auto *context = elementType->getContext();
509 auto &impl = context->getImpl();
510
511 // Look to see if we already have this memref type.
James Molloy87d81022018-07-23 11:44:40 -0700512 auto key =
513 std::make_tuple(elementType, shape, affineMapComposition, memorySpace);
MLIR Team718c82f2018-07-16 09:45:22 -0700514 auto existing = impl.memrefs.insert_as(nullptr, key);
515
516 // If we already have it, return that value.
517 if (!existing.second)
518 return *existing.first;
519
520 // On the first use, we allocate them into the bump pointer.
521 auto *result = impl.allocator.Allocate<MemRefType>();
522
523 // Copy the shape into the bump pointer.
524 shape = impl.copyInto(shape);
525
526 // Copy the affine map composition into the bump pointer.
527 // TODO(andydavis) Assert that the structure of the composition is valid.
James Molloy87d81022018-07-23 11:44:40 -0700528 affineMapComposition =
529 impl.copyInto(ArrayRef<AffineMap *>(affineMapComposition));
MLIR Team718c82f2018-07-16 09:45:22 -0700530
531 // Initialize the memory using placement new.
532 new (result) MemRefType(shape, elementType, affineMapComposition, memorySpace,
533 context);
534 // Cache and return it.
535 return *existing.first = result;
536}
537
Chris Lattner36b4ed12018-07-04 10:43:29 -0700538//===----------------------------------------------------------------------===//
539// Attribute uniquing
540//===----------------------------------------------------------------------===//
541
542BoolAttr *BoolAttr::get(bool value, MLIRContext *context) {
543 auto *&result = context->getImpl().boolAttrs[value];
544 if (result)
545 return result;
546
547 result = context->getImpl().allocator.Allocate<BoolAttr>();
548 new (result) BoolAttr(value);
549 return result;
550}
551
552IntegerAttr *IntegerAttr::get(int64_t value, MLIRContext *context) {
553 auto *&result = context->getImpl().integerAttrs[value];
554 if (result)
555 return result;
556
557 result = context->getImpl().allocator.Allocate<IntegerAttr>();
558 new (result) IntegerAttr(value);
559 return result;
560}
561
562FloatAttr *FloatAttr::get(double value, MLIRContext *context) {
563 // We hash based on the bit representation of the double to ensure we don't
564 // merge things like -0.0 and 0.0 in the hash comparison.
565 union {
566 double floatValue;
567 int64_t intValue;
568 };
569 floatValue = value;
570
571 auto *&result = context->getImpl().floatAttrs[intValue];
572 if (result)
573 return result;
574
575 result = context->getImpl().allocator.Allocate<FloatAttr>();
576 new (result) FloatAttr(value);
577 return result;
578}
579
580StringAttr *StringAttr::get(StringRef bytes, MLIRContext *context) {
581 auto it = context->getImpl().stringAttrs.insert({bytes, nullptr}).first;
582
583 if (it->second)
584 return it->second;
585
586 auto result = context->getImpl().allocator.Allocate<StringAttr>();
587 new (result) StringAttr(it->first());
588 it->second = result;
589 return result;
590}
591
James Molloy87d81022018-07-23 11:44:40 -0700592ArrayAttr *ArrayAttr::get(ArrayRef<Attribute *> value, MLIRContext *context) {
Chris Lattner36b4ed12018-07-04 10:43:29 -0700593 auto &impl = context->getImpl();
594
595 // Look to see if we already have this.
596 auto existing = impl.arrayAttrs.insert_as(nullptr, value);
597
598 // If we already have it, return that value.
599 if (!existing.second)
600 return *existing.first;
601
602 // On the first use, we allocate them into the bump pointer.
603 auto *result = impl.allocator.Allocate<ArrayAttr>();
604
605 // Copy the elements into the bump pointer.
606 value = impl.copyInto(value);
607
608 // Initialize the memory using placement new.
609 new (result) ArrayAttr(value);
MLIR Team355ec862018-06-23 18:09:09 -0700610
611 // Cache and return it.
Chris Lattner36b4ed12018-07-04 10:43:29 -0700612 return *existing.first = result;
MLIR Team355ec862018-06-23 18:09:09 -0700613}
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700614
James Molloy87d81022018-07-23 11:44:40 -0700615AffineMapAttr *AffineMapAttr::get(AffineMap *value, MLIRContext *context) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700616 auto *&result = context->getImpl().affineMapAttrs[value];
617 if (result)
618 return result;
619
620 result = context->getImpl().allocator.Allocate<AffineMapAttr>();
621 new (result) AffineMapAttr(value);
622 return result;
623}
624
Chris Lattnerdf1a2fc2018-07-05 21:20:59 -0700625/// Perform a three-way comparison between the names of the specified
626/// NamedAttributes.
627static int compareNamedAttributes(const NamedAttribute *lhs,
628 const NamedAttribute *rhs) {
629 return lhs->first.str().compare(rhs->first.str());
630}
631
632/// Given a list of NamedAttribute's, canonicalize the list (sorting
633/// by name) and return the unique'd result. Note that the empty list is
634/// represented with a null pointer.
635AttributeListStorage *AttributeListStorage::get(ArrayRef<NamedAttribute> attrs,
636 MLIRContext *context) {
637 // We need to sort the element list to canonicalize it, but we also don't want
638 // to do a ton of work in the super common case where the element list is
639 // already sorted.
640 SmallVector<NamedAttribute, 8> storage;
641 switch (attrs.size()) {
642 case 0:
643 // An empty list is represented with a null pointer.
644 return nullptr;
645 case 1:
646 // A single element is already sorted.
647 break;
648 case 2:
649 // Don't invoke a general sort for two element case.
650 if (attrs[0].first.str() > attrs[1].first.str()) {
651 storage.push_back(attrs[1]);
652 storage.push_back(attrs[0]);
653 attrs = storage;
654 }
655 break;
656 default:
657 // Check to see they are sorted already.
658 bool isSorted = true;
659 for (unsigned i = 0, e = attrs.size() - 1; i != e; ++i) {
660 if (attrs[i].first.str() > attrs[i + 1].first.str()) {
661 isSorted = false;
662 break;
663 }
664 }
665 // If not, do a general sort.
666 if (!isSorted) {
667 storage.append(attrs.begin(), attrs.end());
668 llvm::array_pod_sort(storage.begin(), storage.end(),
669 compareNamedAttributes);
670 attrs = storage;
671 }
672 }
673
674 // Ok, now that we've canonicalized our attributes, unique them.
675 auto &impl = context->getImpl();
676
677 // Look to see if we already have this.
678 auto existing = impl.attributeLists.insert_as(nullptr, attrs);
679
680 // If we already have it, return that value.
681 if (!existing.second)
682 return *existing.first;
683
684 // Otherwise, allocate a new AttributeListStorage, unique it and return it.
685 auto byteSize =
686 AttributeListStorage::totalSizeToAlloc<NamedAttribute>(attrs.size());
687 auto rawMem = impl.allocator.Allocate(byteSize, alignof(NamedAttribute));
688
689 // Placement initialize the AggregateSymbolicValue.
690 auto result = ::new (rawMem) AttributeListStorage(attrs.size());
691 std::uninitialized_copy(attrs.begin(), attrs.end(),
692 result->getTrailingObjects<NamedAttribute>());
693 return *existing.first = result;
694}
695
Chris Lattner36b4ed12018-07-04 10:43:29 -0700696//===----------------------------------------------------------------------===//
697// AffineMap and AffineExpr uniquing
698//===----------------------------------------------------------------------===//
699
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700700AffineMap *AffineMap::get(unsigned dimCount, unsigned symbolCount,
701 ArrayRef<AffineExpr *> results,
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700702 ArrayRef<AffineExpr *> rangeSizes,
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700703 MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700704 // The number of results can't be zero.
705 assert(!results.empty());
706
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700707 assert(rangeSizes.empty() || results.size() == rangeSizes.size());
708
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700709 auto &impl = context->getImpl();
710
711 // Check if we already have this affine map.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700712 auto key = std::make_tuple(dimCount, symbolCount, results, rangeSizes);
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700713 auto existing = impl.affineMaps.insert_as(nullptr, key);
714
715 // If we already have it, return that value.
716 if (!existing.second)
717 return *existing.first;
718
719 // On the first use, we allocate them into the bump pointer.
720 auto *res = impl.allocator.Allocate<AffineMap>();
721
Uday Bondhugula1e500b42018-07-12 18:04:04 -0700722 // Copy the results and range sizes into the bump pointer.
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700723 results = impl.copyInto(ArrayRef<AffineExpr *>(results));
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700724 rangeSizes = impl.copyInto(ArrayRef<AffineExpr *>(rangeSizes));
725
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700726 // Initialize the memory using placement new.
Uday Bondhugula0115dbb2018-07-11 21:31:07 -0700727 new (res) AffineMap(dimCount, symbolCount, results.size(), results.data(),
728 rangeSizes.empty() ? nullptr : rangeSizes.data());
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700729
730 // Cache and return it.
731 return *existing.first = res;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700732}
733
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700734/// Return a binary affine op expression with the specified op type and
735/// operands: if it doesn't exist, create it and store it; if it is already
736/// present, return from the list. The stored expressions are unique: they are
737/// constructed and stored in a simplified/canonicalized form. The result after
738/// simplification could be any form of affine expression.
739AffineExpr *AffineBinaryOpExpr::get(AffineExpr::Kind kind, AffineExpr *lhs,
740 AffineExpr *rhs, MLIRContext *context) {
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700741 auto &impl = context->getImpl();
742
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700743 // Check if we already have this affine expression, and return it if we do.
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700744 auto keyValue = std::make_tuple((unsigned)kind, lhs, rhs);
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700745 auto cached = impl.affineExprs.find(keyValue);
746 if (cached != impl.affineExprs.end())
747 return cached->second;
Uday Bondhugula3934d4d2018-07-09 09:00:25 -0700748
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700749 // Simplify the expression if possible.
750 AffineExpr *simplified;
751 switch (kind) {
752 case Kind::Add:
753 simplified = AffineBinaryOpExpr::simplifyAdd(lhs, rhs, context);
754 break;
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700755 case Kind::Mul:
756 simplified = AffineBinaryOpExpr::simplifyMul(lhs, rhs, context);
757 break;
758 case Kind::FloorDiv:
759 simplified = AffineBinaryOpExpr::simplifyFloorDiv(lhs, rhs, context);
760 break;
761 case Kind::CeilDiv:
762 simplified = AffineBinaryOpExpr::simplifyCeilDiv(lhs, rhs, context);
763 break;
764 case Kind::Mod:
765 simplified = AffineBinaryOpExpr::simplifyMod(lhs, rhs, context);
766 break;
767 default:
768 llvm_unreachable("unexpected binary affine expr");
Uday Bondhugula015cbb12018-07-03 20:16:08 -0700769 }
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700770
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700771 // The simplified one would have already been cached; just return it.
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700772 if (simplified)
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700773 return simplified;
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700774
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700775 // An expression with these operands will already be in the
776 // simplified/canonical form. Create and store it.
777 auto *result = impl.allocator.Allocate<AffineBinaryOpExpr>();
Uday Bondhugulae082aad2018-07-11 21:19:31 -0700778 // Initialize the memory using placement new.
Uday Bondhugula0dd940c2018-07-26 00:19:21 -0700779 new (result) AffineBinaryOpExpr(kind, lhs, rhs);
780 bool inserted = impl.affineExprs.insert({keyValue, result}).second;
781 assert(inserted && "the expression shouldn't already exist in the map");
782 (void)inserted;
783 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700784}
785
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700786AffineDimExpr *AffineDimExpr::get(unsigned position, MLIRContext *context) {
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700787 auto &impl = context->getImpl();
788
789 // Check if we need to resize.
790 if (position >= impl.dimExprs.size())
791 impl.dimExprs.resize(position + 1, nullptr);
792
793 auto *&result = impl.dimExprs[position];
794 if (result)
795 return result;
796
797 result = impl.allocator.Allocate<AffineDimExpr>();
798 // Initialize the memory using placement new.
799 new (result) AffineDimExpr(position);
800 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700801}
802
803AffineSymbolExpr *AffineSymbolExpr::get(unsigned position,
804 MLIRContext *context) {
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700805 auto &impl = context->getImpl();
806
807 // Check if we need to resize.
808 if (position >= impl.symbolExprs.size())
809 impl.symbolExprs.resize(position + 1, nullptr);
810
811 auto *&result = impl.symbolExprs[position];
812 if (result)
813 return result;
814
815 result = impl.allocator.Allocate<AffineSymbolExpr>();
816 // Initialize the memory using placement new.
817 new (result) AffineSymbolExpr(position);
818 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700819}
820
821AffineConstantExpr *AffineConstantExpr::get(int64_t constant,
822 MLIRContext *context) {
Uday Bondhugula4e5078b2018-07-24 22:34:09 -0700823 auto &impl = context->getImpl();
824 auto *&result = impl.constExprs[constant];
825
826 if (result)
827 return result;
828
829 result = impl.allocator.Allocate<AffineConstantExpr>();
830 // Initialize the memory using placement new.
831 new (result) AffineConstantExpr(constant);
832 return result;
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -0700833}