1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
|
//===- VectorOps.cpp - MLIR Super Vectorizer Operations -------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
//
// This file implements convenience types for working with super-vectorization
// operations, in particular super-vector loads and stores.
//
//===----------------------------------------------------------------------===//
#include "mlir/VectorOps/VectorOps.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Support/LLVM.h"
using namespace mlir;
using namespace mlir::vector;
//===----------------------------------------------------------------------===//
// VectorOpsDialect
//===----------------------------------------------------------------------===//
mlir::vector::VectorOpsDialect::VectorOpsDialect(MLIRContext *context)
: Dialect(getDialectNamespace(), context) {
addOperations<VectorTransferReadOp, VectorTransferWriteOp,
VectorTypeCastOp>();
addOperations<
#define GET_OP_LIST
#include "mlir/VectorOps/VectorOps.cpp.inc"
>();
}
//===----------------------------------------------------------------------===//
// ExtractElementOp
//===----------------------------------------------------------------------===//
static void print(OpAsmPrinter *p, ExtractElementOp op) {
*p << op.getOperationName() << " " << *op.vector() << op.position();
p->printOptionalAttrDict(op.getAttrs(), {"position"});
*p << " : " << op.vector()->getType();
}
static ParseResult parseExtractElementOp(OpAsmParser *parser,
OperationState *result) {
llvm::SMLoc attributeLoc, typeLoc;
SmallVector<NamedAttribute, 4> attrs;
OpAsmParser::OperandType vector;
Type type;
Attribute attr;
if (parser->parseOperand(vector) ||
parser->getCurrentLocation(&attributeLoc) ||
parser->parseAttribute(attr, "position", attrs) ||
parser->parseOptionalAttributeDict(attrs) ||
parser->getCurrentLocation(&typeLoc) || parser->parseColonType(type))
return failure();
auto vectorType = type.dyn_cast<VectorType>();
if (!vectorType)
return parser->emitError(typeLoc, "expected vector type");
auto positionAttr = attr.dyn_cast<ArrayAttr>();
if (!positionAttr ||
static_cast<int64_t>(positionAttr.size()) > vectorType.getRank())
return parser->emitError(
attributeLoc,
"expected position attribute of rank smaller than vector");
Type resType =
(static_cast<int64_t>(positionAttr.size()) == vectorType.getRank())
? vectorType.getElementType()
: VectorType::get(
vectorType.getShape().drop_front(positionAttr.size()),
vectorType.getElementType());
result->attributes = attrs;
return failure(parser->resolveOperand(vector, type, result->operands) ||
parser->addTypeToList(resType, result->types));
}
static LogicalResult verify(ExtractElementOp op) {
auto positionAttr = op.position().getValue();
if (positionAttr.empty())
return op.emitOpError("expected non-empty position attribute");
if (positionAttr.size() > static_cast<unsigned>(op.getVectorType().getRank()))
return op.emitOpError(
"expected position attribute of rank smaller than vector");
for (auto en : llvm::enumerate(positionAttr)) {
auto attr = en.value().dyn_cast<IntegerAttr>();
if (!attr || attr.getInt() < 0 ||
attr.getInt() > op.getVectorType().getDimSize(en.index()))
return op.emitOpError("expected position attribute #")
<< (en.index() + 1)
<< " to be a positive integer smaller than the corresponding "
"vector dimension";
}
return success();
}
//===----------------------------------------------------------------------===//
// OuterProductOp
//===----------------------------------------------------------------------===//
static void print(OpAsmPrinter *p, OuterProductOp op) {
*p << op.getOperationName() << " " << *op.lhs() << ", " << *op.rhs();
*p << " : " << op.lhs()->getType() << ", " << op.rhs()->getType();
}
static ParseResult parseOuterProductOp(OpAsmParser *parser,
OperationState *result) {
SmallVector<OpAsmParser::OperandType, 2> operandsInfo;
Type t0, t1;
if (parser->parseOperandList(operandsInfo) || parser->parseColonType(t0) ||
parser->parseComma() || parser->parseType(t1))
return failure();
VectorType v0 = t0.dyn_cast<VectorType>();
VectorType v1 = t1.dyn_cast<VectorType>();
if (!v0 || !v1)
return parser->emitError(parser->getNameLoc(), "expected 2 vector types");
VectorType resType = VectorType::get({v0.getDimSize(0), v1.getDimSize(0)},
v0.getElementType());
return failure(parser->resolveOperands(operandsInfo, {t0, t1},
parser->getCurrentLocation(),
result->operands) ||
parser->addTypeToList(resType, result->types));
}
static LogicalResult verify(OuterProductOp op) {
VectorType v1 = op.getOperandVectorTypeLHS(),
v2 = op.getOperandVectorTypeRHS(), res = op.getVectorType();
if (v1.getRank() != 1)
return op.emitOpError("expected 1-d vector for operand #1");
if (v2.getRank() != 1)
return op.emitOpError("expected 1-d vector for operand #2");
if (res.getRank() != 2)
return op.emitOpError("expected 2-d vector result");
if (v1.getDimSize(0) != res.getDimSize(0))
return op.emitOpError(
"expected first operand dim to match first result dim");
if (v2.getDimSize(0) != res.getDimSize(1))
return op.emitOpError(
"expected second operand dim to match second result dim");
return success();
}
//===----------------------------------------------------------------------===//
// VectorTransferReadOp
//===----------------------------------------------------------------------===//
template <typename EmitFun>
static LogicalResult verifyPermutationMap(AffineMap permutationMap,
EmitFun emitOpError) {
SmallVector<bool, 8> seen(permutationMap.getNumInputs(), false);
for (auto expr : permutationMap.getResults()) {
auto dim = expr.dyn_cast<AffineDimExpr>();
auto zero = expr.dyn_cast<AffineConstantExpr>();
if (zero) {
if (zero.getValue() != 0) {
return emitOpError(
"requires a projected permutation_map (at most one dim or the zero "
"constant can appear in each result)");
}
continue;
}
if (!dim) {
return emitOpError("requires a projected permutation_map (at most one "
"dim or the zero constant can appear in each result)");
}
if (seen[dim.getPosition()]) {
return emitOpError(
"requires a permutation_map that is a permutation (found one dim "
"used more than once)");
}
seen[dim.getPosition()] = true;
}
return success();
}
void VectorTransferReadOp::build(Builder *builder, OperationState *result,
VectorType vectorType, Value *srcMemRef,
ArrayRef<Value *> srcIndices,
AffineMap permutationMap,
Optional<Value *> paddingValue) {
result->addOperands(srcMemRef);
result->addOperands(srcIndices);
if (paddingValue) {
result->addOperands({*paddingValue});
}
result->addAttribute(getPermutationMapAttrName(),
builder->getAffineMapAttr(permutationMap));
result->addTypes(vectorType);
}
auto VectorTransferReadOp::getIndices() -> operand_range {
auto begin = getOperation()->operand_begin() + Offsets::FirstIndexOffset;
auto end = begin + getMemRefType().getRank();
return {begin, end};
}
Optional<Value *> VectorTransferReadOp::getPaddingValue() {
auto memRefRank = getMemRefType().getRank();
if (getNumOperands() <= Offsets::FirstIndexOffset + memRefRank) {
return None;
}
return Optional<Value *>(getOperand(Offsets::FirstIndexOffset + memRefRank));
}
AffineMap VectorTransferReadOp::getPermutationMap() {
return getAttrOfType<AffineMapAttr>(getPermutationMapAttrName()).getValue();
}
void VectorTransferReadOp::print(OpAsmPrinter *p) {
*p << getOperationName() << " ";
p->printOperand(getMemRef());
*p << "[";
p->printOperands(getIndices());
*p << "]";
auto optionalPaddingValue = getPaddingValue();
if (optionalPaddingValue) {
*p << ", (";
p->printOperand(*optionalPaddingValue);
*p << ")";
}
p->printOptionalAttrDict(getAttrs());
*p << " : " << getMemRefType();
*p << ", " << getResultType();
}
ParseResult VectorTransferReadOp::parse(OpAsmParser *parser,
OperationState *result) {
OpAsmParser::OperandType memrefInfo;
SmallVector<OpAsmParser::OperandType, 8> indexInfo;
SmallVector<OpAsmParser::OperandType, 8> paddingInfo;
SmallVector<Type, 2> types;
// Parsing with support for optional paddingValue.
if (parser->parseOperand(memrefInfo) ||
parser->parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) ||
parser->parseTrailingOperandList(paddingInfo,
OpAsmParser::Delimiter::Paren) ||
parser->parseOptionalAttributeDict(result->attributes) ||
parser->parseColonTypeList(types))
return failure();
// Resolution.
if (types.size() != 2)
return parser->emitError(parser->getNameLoc(), "expected 2 types");
MemRefType memrefType = types[0].dyn_cast<MemRefType>();
if (!memrefType)
return parser->emitError(parser->getNameLoc(), "memRef type expected");
VectorType vectorType = types[1].dyn_cast<VectorType>();
if (!vectorType)
return parser->emitError(parser->getNameLoc(), "vector type expected");
// Extract optional paddingValue.
// At this point, indexInfo may contain the optional paddingValue, pop it
// out.
if (static_cast<int64_t>(indexInfo.size()) != memrefType.getRank())
return parser->emitError(parser->getNameLoc(),
"expected " + Twine(memrefType.getRank()) +
" indices to the memref");
if (paddingInfo.size() > 1)
return parser->emitError(parser->getNameLoc(),
"expected at most one padding value");
Type paddingType;
bool hasOptionalPaddingValue = !paddingInfo.empty();
if (hasOptionalPaddingValue) {
paddingType = vectorType.getElementType();
}
auto indexType = parser->getBuilder().getIndexType();
return failure(
parser->resolveOperand(memrefInfo, memrefType, result->operands) ||
parser->resolveOperands(indexInfo, indexType, result->operands) ||
(hasOptionalPaddingValue &&
parser->resolveOperand(paddingInfo[0], paddingType, result->operands)) ||
parser->addTypeToList(vectorType, result->types));
}
LogicalResult VectorTransferReadOp::verify() {
// Consistency of memref type in function type.
if (llvm::empty(getOperands())) {
return emitOpError(
"requires at least a memref operand followed by 'rank' indices");
}
if (!getMemRef()->getType().isa<MemRefType>()) {
return emitOpError("requires a memref as first operand");
}
// Consistency of vector type in function type.
if (!getResult()->getType().isa<VectorType>()) {
return emitOpError("should have a vector result type in function type: "
"memref_type<...xelemental_type>, vector_type");
}
// Consistency of elemental types in memref and vector.
MemRefType memrefType = getMemRefType();
VectorType vectorType = getResultType();
if (memrefType.getElementType() != vectorType.getElementType())
return emitOpError(
"requires memref and vector types of the same elemental type");
// Consistency of number of input types.
auto optionalPaddingValue = getPaddingValue();
unsigned expectedNumOperands = Offsets::FirstIndexOffset +
memrefType.getRank() +
(optionalPaddingValue ? 1 : 0);
// Checks on the actual operands and their types.
if (getNumOperands() != expectedNumOperands) {
return emitOpError("expects ")
<< expectedNumOperands << " operands (of which "
<< memrefType.getRank() << " indices)";
}
// Consistency of padding value with vector type.
if (optionalPaddingValue) {
auto paddingValue = *optionalPaddingValue;
auto elementalType = paddingValue->getType();
if (!VectorType::isValidElementType(elementalType)) {
return emitOpError("requires valid padding vector elemental type");
}
if (elementalType != vectorType.getElementType()) {
return emitOpError(
"requires formal padding and vector of the same elemental type");
}
}
// Consistency of indices types.
unsigned numIndices = 0;
for (auto *idx : getIndices()) {
if (!idx->getType().isIndex()) {
return emitOpError(
"index to vector.transfer_read must have 'index' type");
}
++numIndices;
}
if (numIndices != memrefType.getRank()) {
return emitOpError("requires at least a memref operand followed by ")
<< memrefType.getRank() << " indices";
}
// Consistency of AffineMap attribute.
if (!getAttrOfType<AffineMapAttr>(getPermutationMapAttrName())) {
return emitOpError("requires an AffineMapAttr named 'permutation_map'");
}
auto permutationMap = getPermutationMap();
if (permutationMap.getNumSymbols() != 0) {
return emitOpError("requires a permutation_map without symbols");
}
if (permutationMap.getNumInputs() != memrefType.getRank()) {
return emitOpError("requires a permutation_map with input dims of the "
"same rank as the memref type");
}
if (permutationMap.getNumResults() != vectorType.getRank()) {
return emitOpError("requires a permutation_map with result dims of the "
"same rank as the vector type (")
<< permutationMap.getNumResults() << " vs " << vectorType.getRank();
}
return verifyPermutationMap(permutationMap,
[this](Twine t) { return emitOpError(t); });
}
//===----------------------------------------------------------------------===//
// VectorTransferWriteOp
//===----------------------------------------------------------------------===//
void VectorTransferWriteOp::build(Builder *builder, OperationState *result,
Value *srcVector, Value *dstMemRef,
ArrayRef<Value *> dstIndices,
AffineMap permutationMap) {
result->addOperands({srcVector, dstMemRef});
result->addOperands(dstIndices);
result->addAttribute(getPermutationMapAttrName(),
builder->getAffineMapAttr(permutationMap));
}
auto VectorTransferWriteOp::getIndices() -> operand_range {
auto begin = getOperation()->operand_begin() + Offsets::FirstIndexOffset;
auto end = begin + getMemRefType().getRank();
return {begin, end};
}
AffineMap VectorTransferWriteOp::getPermutationMap() {
return getAttrOfType<AffineMapAttr>(getPermutationMapAttrName()).getValue();
}
void VectorTransferWriteOp::print(OpAsmPrinter *p) {
*p << getOperationName();
*p << " " << *getVector();
*p << ", " << *getMemRef();
*p << "[";
p->printOperands(getIndices());
*p << "]";
p->printOptionalAttrDict(getAttrs());
*p << " : ";
p->printType(getVectorType());
*p << ", ";
p->printType(getMemRefType());
}
ParseResult VectorTransferWriteOp::parse(OpAsmParser *parser,
OperationState *result) {
OpAsmParser::OperandType storeValueInfo;
OpAsmParser::OperandType memrefInfo;
SmallVector<OpAsmParser::OperandType, 4> indexInfo;
SmallVector<Type, 2> types;
auto indexType = parser->getBuilder().getIndexType();
if (parser->parseOperand(storeValueInfo) || parser->parseComma() ||
parser->parseOperand(memrefInfo) ||
parser->parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) ||
parser->parseOptionalAttributeDict(result->attributes) ||
parser->parseColonTypeList(types))
return failure();
if (types.size() != 2)
return parser->emitError(parser->getNameLoc(), "expected 2 types");
VectorType vectorType = types[Offsets::VectorOffset].dyn_cast<VectorType>();
if (!vectorType)
return parser->emitError(parser->getNameLoc(), "vector type expected");
MemRefType memrefType = types[Offsets::MemRefOffset].dyn_cast<MemRefType>();
if (!memrefType)
return parser->emitError(parser->getNameLoc(), "memRef type expected");
return failure(
parser->resolveOperands(storeValueInfo, vectorType, result->operands) ||
parser->resolveOperands(memrefInfo, memrefType, result->operands) ||
parser->resolveOperands(indexInfo, indexType, result->operands));
}
LogicalResult VectorTransferWriteOp::verify() {
// Consistency of memref type in function type.
if (llvm::empty(getOperands())) {
return emitOpError(
"requires at least a memref operand followed by 'rank' indices");
}
if (!getMemRef()->getType().isa<MemRefType>()) {
return emitOpError("requires a memref first operand");
}
// Consistency of vector type in function type.
if (!getVector()->getType().isa<VectorType>()) {
return emitOpError("should have a vector input type in function type: "
"(vector_type, memref_type [, elemental_type]) -> ()");
}
// Consistency of elemental types in memref and vector.
MemRefType memrefType = getMemRefType();
VectorType vectorType = getVectorType();
if (memrefType.getElementType() != vectorType.getElementType())
return emitOpError(
"requires memref and vector types of the same elemental type");
// Consistency of number of input types.
unsigned expectedNumOperands =
Offsets::FirstIndexOffset + memrefType.getRank();
// Checks on the actual operands and their types.
if (getNumOperands() != expectedNumOperands) {
return emitOpError() << "expects " << expectedNumOperands
<< " operands (of which " << memrefType.getRank()
<< " indices)";
}
// Consistency of indices types.
unsigned numIndices = 0;
for (auto *idx : getIndices()) {
if (!idx->getType().isIndex()) {
return emitOpError(
"index to vector.transfer_write must have 'index' type");
}
numIndices++;
}
if (numIndices != memrefType.getRank()) {
return emitOpError("requires at least a memref operand followed by ")
<< memrefType.getRank() << " indices";
}
// Consistency of AffineMap attribute.
if (!getAttrOfType<AffineMapAttr>(getPermutationMapAttrName())) {
return emitOpError("requires an AffineMapAttr named 'permutation_map'");
}
auto permutationMap = getPermutationMap();
if (permutationMap.getNumSymbols() != 0) {
return emitOpError("requires a permutation_map without symbols");
}
if (permutationMap.getNumInputs() != memrefType.getRank()) {
return emitOpError("requires a permutation_map with input dims of the "
"same rank as the memref type");
}
if (permutationMap.getNumResults() != vectorType.getRank()) {
return emitOpError("requires a permutation_map with result dims of the "
"same rank as the vector type (")
<< permutationMap.getNumResults() << " vs " << vectorType.getRank();
}
return verifyPermutationMap(permutationMap,
[this](Twine t) { return emitOpError(t); });
}
//===----------------------------------------------------------------------===//
// VectorTypeCastOp
//===----------------------------------------------------------------------===//
void VectorTypeCastOp::build(Builder *builder, OperationState *result,
Value *srcVector, Type dstType) {
result->addOperands(srcVector);
result->addTypes(dstType);
}
ParseResult VectorTypeCastOp::parse(OpAsmParser *parser,
OperationState *result) {
OpAsmParser::OperandType operand;
Type srcType, dstType;
return failure(parser->parseOperand(operand) ||
parser->parseOptionalAttributeDict(result->attributes) ||
parser->parseColonType(srcType) || parser->parseComma() ||
parser->parseType(dstType) ||
parser->addTypeToList(dstType, result->types) ||
parser->resolveOperand(operand, srcType, result->operands));
}
void VectorTypeCastOp::print(OpAsmPrinter *p) {
*p << getOperationName() << ' ' << *getOperand() << " : "
<< getOperand()->getType() << ", " << getType();
}
LogicalResult VectorTypeCastOp::verify() {
auto dstMemrefType = getType().dyn_cast<MemRefType>();
if (!dstMemrefType)
return emitOpError("expects target type to be a memref type");
auto dstVectorType = dstMemrefType.getElementType().dyn_cast<VectorType>();
if (!dstVectorType)
return emitOpError(
"expects vector as an element of the target memref type");
if (!dstMemrefType.hasStaticShape())
return emitOpError("does not support dynamic shapes");
if (!getOperand()->getType().isa<MemRefType>())
return emitOpError("expects source type to be a memref type");
return success();
}
namespace mlir {
#define GET_OP_CLASSES
#include "mlir/VectorOps/VectorOps.cpp.inc"
} // namespace mlir
|