-
Notifications
You must be signed in to change notification settings - Fork 10
/
sair_op_interfaces.cc
758 lines (648 loc) · 25.3 KB
/
sair_op_interfaces.cc
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// Copyright 2020 Google LLC
//
// 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.
#include "sair_op_interfaces.h"
#include <iterator>
#include <optional>
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Types.h"
#include "mlir/IR/UseDefLists.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "loop_nest.h"
#include "sair_attributes.h"
#include "sair_dialect.h"
#include "sair_ops.h"
#include "sair_types.h"
#include "storage.h"
namespace sair {
mlir::Type ValueAccess::ElementType() const {
return value.getType().cast<ValueType>().ElementType();
}
bool operator==(const ValueAccess &lhs, const ValueAccess &rhs) {
return lhs.value == rhs.value && lhs.mapping == rhs.mapping;
}
bool operator!=(const ValueAccess &lhs, const ValueAccess &rhs) {
return !(lhs == rhs);
}
ValueOperand::ValueOperand(mlir::OpOperand *operand) : operand_(operand) {
auto owner = cast<SairOp>(operand->getOwner());
index_ = operand->getOperandNumber() - owner.getDomain().size();
assert(index_ >= 0 && "expected domain operands before value operands");
}
MappingAttr ValueOperand::Mapping() const {
return cast<SairOp>(operand_->getOwner())
.getMappingArray()
.getValue()[index_]
.template cast<::sair::MappingAttr>();
}
void ValueOperand::SubstituteValue(ValueAccess new_value) {
set_value(new_value.value);
SetMapping(Mapping().Compose(new_value.mapping));
}
void ValueOperand::SetMapping(MappingAttr mapping) {
SairOp op = cast<SairOp>(operand_->getOwner());
op.SetMapping(index_, mapping);
}
ValueOperandRange::ValueOperandRange()
: RangeBaseT(std::make_pair(nullptr, 0), 0) {}
ValueOperandRange::ValueOperandRange(
llvm::MutableArrayRef<mlir::OpOperand> operands)
: RangeBaseT(std::make_pair(operands.data(), 0), operands.size()) {}
ValueOperandRange::PtrPair ValueOperandRange::offset_base(PtrPair base_ptr,
ptrdiff_t offset) {
base_ptr.first += offset;
base_ptr.second += offset;
return base_ptr;
}
ValueOperand ValueOperandRange::dereference_iterator(PtrPair base_ptr,
ptrdiff_t offset) {
return ValueOperand(base_ptr.first + offset);
}
llvm::SmallBitVector ValueOperand::DependingDims() const {
return cast<SairOp>(operand_->getOwner()).DimsDependingOnOperand(index_);
}
bool ValueOperand::AllowUseBeforeDef() const {
return cast<SairOp>(operand_->getOwner()).AllowUseBeforeDef(index_);
}
llvm::SmallBitVector ValueOperand::CarryingDims() const {
return cast<SairOp>(operand_->getOwner()).CarryingDimensions(index_);
}
void UpdateValueUses(mlir::Value value, ValueAccess new_value) {
for (OpOperand &operand : llvm::make_early_inc_range(value.getUses())) {
ValueOperand(&operand).SubstituteValue(new_value);
}
}
ValueOrConstant ValueOrConstant::Map(MappingAttr mapping) const {
if (is_constant()) return *this;
ValueAccess value_access = value();
value_access.mapping = mapping.Compose(value_access.mapping);
return value_access;
}
// Verifies that `decisions` is well formed when used for an operation with the
// given shape and result types.
static mlir::LogicalResult VerifyDecisionsWellFormed(mlir::Location loc,
DomainShapeAttr shape,
TypeRange result_types,
DecisionsAttr decisions) {
auto *sair_dialect = shape.getContext()->getLoadedDialect<SairDialect>();
// Check loop nest.
mlir::ArrayAttr loop_nest = decisions.loop_nest();
llvm::DenseSet<mlir::Attribute> loop_names;
if (loop_nest != nullptr) {
if (mlir::failed(
VerifyLoopNestWellFormed(loc, shape, loop_nest.getValue()))) {
return mlir::failure();
}
loop_names.reserve(loop_nest.size());
for (mlir::Attribute attr : loop_nest.getValue()) {
loop_names.insert(attr.cast<LoopAttr>().name());
}
}
// Check storage.
mlir::ArrayAttr storage = decisions.storage();
if (storage != nullptr &&
mlir::failed(VerifyStorageAttrWellFormed(
loc, sair_dialect, result_types, loop_names, storage.getValue()))) {
return mlir::failure();
}
// Check expansion pattern.
mlir::StringAttr pattern_name = decisions.expansion();
if (pattern_name == nullptr) return mlir::success();
const ExpansionPattern *pattern =
sair_dialect->GetExpansionPattern(pattern_name.getValue());
if (pattern == nullptr) {
return mlir::emitError(loc)
<< "invalid expansion pattern name " << pattern_name;
}
return mlir::success();
}
static mlir::LogicalResult VerifyInstancesAttr(SairOp op) {
if (!op.getInstances().has_value()) return success();
for (int decision_index = 0, e = op.NumInstances(); decision_index < e;
++decision_index) {
// Ignore incorrect types here, they will be caught by the op verifier.
mlir::Attribute decision_attr =
op.getInstances()->getValue()[decision_index];
DecisionsAttr decisions = decision_attr.dyn_cast<DecisionsAttr>();
if (!decisions) continue;
if (decisions.copy_of() != nullptr) {
return op->emitError() << "cannot specify 'copy_of' in 'instances'";
}
if (mlir::failed(VerifyDecisionsWellFormed(
op->getLoc(), op.getShape(), op->getResultTypes(), decisions))) {
return mlir::failure();
}
if (decisions.operands() == nullptr) continue;
if (decisions.operands().size() != op->getNumOperands()) {
return op->emitError()
<< "'operands' attribute expects as many entries as op has "
"operands ("
<< op->getNumOperands() << ", got " << decisions.operands().size()
<< ") in instance #" << decision_index;
}
for (auto en : llvm::enumerate(decisions.operands().getValue())) {
mlir::Attribute operand_instance = en.value();
if (operand_instance.isa<mlir::UnitAttr>()) continue;
if (auto copy = operand_instance.dyn_cast<CopyAttr>()) {
Value operand = op->getOperand(en.index());
auto defining_op = operand.getDefiningOp<ValueProducerOp>();
if (!defining_op) {
return op->emitError() << "operand #" << en.index()
<< " of instance #" << decision_index
<< " refers to a copy, but the producing op "
"cannot have copies";
}
if (copy.getValue() >=
defining_op.GetCopies(operand.cast<OpResult>().getResultNumber())
.size()) {
return op->emitError()
<< "operand #" << en.index() << " of instance #"
<< decision_index << " refers to an undefined copy";
}
continue;
}
// Ignore incorrect attribute types here, they will be caught by the op
// verifier later.
auto instance = operand_instance.dyn_cast<InstanceAttr>();
if (!instance) continue;
// There may be no defining op for operands of some non-compute ops.
auto defining_op = op->getOperand(en.index()).getDefiningOp<SairOp>();
if (!defining_op) continue;
std::optional<mlir::ArrayAttr> defining_op_instances =
defining_op.getInstances();
if (!defining_op_instances) continue;
if (instance.getValue() >= defining_op_instances->size()) {
return op->emitError()
<< "operand #" << en.index() << " of instance #"
<< decision_index << " refers to non-existent instance";
}
}
}
if (isa<ComputeOp>(op.getOperation())) return mlir::success();
for (mlir::Attribute attr : op.getInstances()->getValue()) {
DecisionsAttr decisions = attr.dyn_cast<DecisionsAttr>();
if (!decisions) continue;
if (decisions.sequence() != nullptr || decisions.loop_nest() != nullptr ||
decisions.storage() != nullptr || decisions.expansion() != nullptr) {
return op->emitOpError()
<< "can specify only 'operands' decisions on non-compute Sair ops";
}
}
return mlir::success();
}
mlir::LogicalResult VerifySairOp(Operation *op) {
SairOp sair_op = cast<SairOp>(op);
// Sair operations are only allowed inside a SairProgramOp.
auto program = dyn_cast<SairProgramOp>(op->getParentOp());
if (program == nullptr) {
return op->emitOpError() << "expected to be immediately contained in a '"
<< SairProgramOp::getOperationName() << "'";
}
// Assert that the domain has the right shape.
assert(llvm::size(sair_op.getDomain()) == sair_op.getShape().NumDimensions());
#ifndef NDEBUG
for (auto pair :
llvm::zip(sair_op.getDomain(), sair_op.getShape().Dimensions())) {
assert(std::get<0>(pair).getType() == std::get<1>(pair).type());
}
#endif
// Assert that operands start with the domain.
assert(sair_op.getDomain().empty() ||
sair_op.getDomain().begin() == op->operand_begin());
// Check that the domain is defined locally.
for (mlir::Value dimension : sair_op.getDomain()) {
mlir::Operation *defining_op = dimension.getDefiningOp();
if (defining_op == nullptr || defining_op->getParentOp() != program) {
return op->emitError()
<< "sair dimensions must be defined in the region they are used";
}
}
if (mlir::failed(VerifyInstancesAttr(sair_op))) {
return mlir::failure();
}
if (!sair_op.ValueOperands().empty()) {
// Verify that the "mapping_array" attribute exists.
if (!op->getAttr(SairOp::kMappingAttrName)) {
return mlir::emitError(op->getLoc())
<< "missing " << SairOp::kMappingAttrName << " attribute";
}
for (mlir::Attribute attr : sair_op.getMappingArray()) {
MappingAttr mapping = attr.cast<MappingAttr>();
if (mapping.HasNoneExprs() || mapping.HasUnknownExprs()) {
return mlir::emitError(op->getLoc())
<< "all dimensions of the accessed domain must be mapped";
}
}
}
// Check !sair.value operands.
for (::sair::ValueOperand v : sair_op.ValueOperands()) {
// Verify operands of Sair operands are defined in the same program.
mlir::Operation *defining_op = v.value().getDefiningOp();
if (defining_op == nullptr || defining_op->getParentOp() != program) {
return op->emitError()
<< "sair values must be defined in the region they are used";
}
if (v.Mapping().UseDomainSize() != sair_op.getDomain().size()) {
return mlir::emitError(op->getLoc()) << "invalid use domain size";
}
AttrLocation mapping_loc(op->getLoc(), "operand mapping");
if (mlir::failed(
VerifyMappingShape(mapping_loc, v.Mapping(), sair_op.getShape()))) {
return mlir::failure();
}
auto expected_shape = sair_op.getShape().AccessedShape(v.Mapping());
auto given_shape =
v.value().getType().template cast<::sair::ValueType>().Shape();
if (expected_shape != given_shape) {
return op->emitError() << "invalid operand shape: expected "
<< expected_shape << ", got " << given_shape;
}
llvm::SmallBitVector dependency_mask = v.Mapping().DependencyMask();
if (dependency_mask.anyCommon(v.DependingDims())) {
return op->emitError() << "an operand mapping references a "
"dimension that depends on the operand";
}
}
// Check that returned Sair values have the right shape.
::sair::DomainShapeAttr results_shape =
sair_op.getShape().Prefix(sair_op.results_rank());
for (mlir::Value result : op->getResults()) {
auto type = result.getType().cast<ShapedType>();
if (type.Shape() != results_shape) {
return op->emitError() << "unexpected shape: expected " << results_shape
<< ", got " << type.Shape();
}
}
return ::mlir::success();
}
mlir::LogicalResult VerifyValueProducerOp(mlir::Operation *operation) {
ValueProducerOp op(operation);
SairOp sair_op(operation);
auto copies = operation->getAttrOfType<mlir::ArrayAttr>(
ValueProducerOp::kCopiesAttrName);
if (copies == nullptr) return mlir::success();
if (copies.size() != operation->getNumResults()) {
return op.emitError()
<< "the `copies` attribute must have one entry per operation result";
}
DomainShapeAttr shape = sair_op.getShape().Prefix(sair_op.results_rank());
for (int i = 0, e = op->getNumResults(); i < e; ++i) {
for (mlir::Attribute attr : op.GetCopies(i)) {
auto decisions = attr.cast<DecisionsAttr>();
if (mlir::failed(VerifyDecisionsWellFormed(
op.getLoc(), shape, {op->getResultTypes()[i]}, decisions))) {
return mlir::failure();
}
if (decisions.operands() != nullptr) {
return op.emitError() << "cannot specify 'operands' in 'copies'";
}
if (decisions.copy_of() == nullptr ||
decisions.copy_of().isa<mlir::UnitAttr>()) {
continue;
}
if (auto copy = decisions.copy_of().dyn_cast<CopyAttr>()) {
if (copy.getValue() >= op.GetCopies(i).size()) {
return op.emitError() << "'copy_of' refers to non-existent copy";
}
}
if (auto instance = decisions.copy_of().dyn_cast<InstanceAttr>()) {
std::optional<mlir::ArrayAttr> instances = sair_op.getInstances();
if (instances && instance.getValue() >= instances->size()) {
return op.emitError() << "'copy_of' refers to non-existent instance";
}
}
}
}
return mlir::success();
}
void SetMapping(SairOp op, int position, ::sair::MappingAttr mapping) {
llvm::SmallVector<mlir::Attribute, 4> new_array =
llvm::to_vector<4>(op.getMappingArray());
new_array[position] = mapping;
mlir::ArrayAttr new_attr = mlir::ArrayAttr::get(op.getContext(), new_array);
op->setAttr(SairOp::kMappingAttrName, new_attr);
}
bool HasExactlyOneInstance(SairOp op) {
if (op.NumInstances() != 1) return false;
auto value_producer = dyn_cast<ValueProducerOp>(op.getOperation());
if (value_producer != nullptr && value_producer.HasCopies()) return false;
return true;
}
OpInstance::OpInstance(SairOp op) : OpInstance(op, 0, 0) {
assert(!llvm::isa<ComputeOp>(op.getOperation()));
}
OpInstance OpInstance::Unique(SairOp op) {
assert(op.HasExactlyOneInstance());
return OpInstance(op, 0, 0);
}
OpInstance::operator bool() const { return *this != nullptr; }
mlir::Operation *OpInstance::GetDuplicatedOp() const {
return op_.get<SairOp>().getOperation();
}
mlir::Value OpInstance::GetCopiedValue() const {
ValueProducerOp op = GetValueProducer();
return op->getResult(result_);
}
ValueProducerOp OpInstance::GetValueProducer() const {
return op_.get<ValueProducerOp>();
}
mlir::Operation *OpInstance::getOperation() const {
if (is_copy()) return op_.get<ValueProducerOp>().getOperation();
return op_.get<SairOp>().getOperation();
}
SairOp OpInstance::GetSairOp() const {
return llvm::cast<SairOp>(getOperation());
}
unsigned OpInstance::HashValue() const {
intptr_t key = reinterpret_cast<intptr_t>(op_.getOpaqueValue());
return llvm::hash_combine(llvm::hash_value(key), llvm::hash_value(result_),
llvm::hash_value(index_));
}
mlir::InFlightDiagnostic OpInstance::EmitError() const {
if (auto compute_op = op_.dyn_cast<SairOp>()) {
return compute_op.emitError() << "in instance " << index_;
}
auto value_producer = op_.get<ValueProducerOp>();
return value_producer.emitError()
<< "in copy " << index_ << " of result " << result_ << ": ";
}
mlir::Diagnostic &OpInstance::AttachNote(mlir::InFlightDiagnostic &diag) const {
if (auto compute_op = op_.dyn_cast<SairOp>()) {
return diag.attachNote(compute_op->getLoc()) << "in instance " << index_;
}
auto value_producer = op_.get<ValueProducerOp>();
return diag.attachNote(value_producer->getLoc())
<< "in copy " << index_ << " of result " << result_ << ": ";
}
mlir::Location OpInstance::getLoc() const { return getOperation()->getLoc(); }
mlir::MLIRContext *OpInstance::context() const {
return getOperation()->getContext();
}
SairProgramOp OpInstance::program() const {
return llvm::cast<SairProgramOp>(getOperation()->getParentOp());
}
SairDialect *OpInstance::GetSairDialect() const {
return static_cast<SairDialect *>(getOperation()->getDialect());
}
DomainShapeAttr OpInstance::GetShape() const {
if (is_copy()) {
auto sair_op =
llvm::cast<SairOp>(op_.get<ValueProducerOp>().getOperation());
return sair_op.getShape().Prefix(sair_op.results_rank());
} else {
return op_.get<SairOp>().getShape();
}
}
int OpInstance::domain_size() const {
if (is_copy()) {
auto sair_op =
llvm::cast<SairOp>(op_.get<ValueProducerOp>().getOperation());
return sair_op.results_rank();
} else {
return op_.get<SairOp>().getDomain().size();
}
}
ResultInstance OpInstance::domain(int i) const {
SairOp op;
if (is_copy()) {
op = llvm::cast<SairOp>(GetCopiedValue().getDefiningOp());
} else {
op = llvm::cast<SairOp>(GetDuplicatedOp());
}
mlir::Value dim = op.getDomain()[i];
OpInstance dim_op(llvm::cast<SairOp>(dim.getDefiningOp()));
return ResultInstance(dim_op, dim.cast<OpResult>().getResultNumber());
}
ValueRange OpInstance::GetDomainValues() const {
if (is_copy()) {
auto op = llvm::cast<SairOp>(GetCopiedValue().getDefiningOp());
return op.getDomain().take_front(domain_size());
} else {
return llvm::cast<SairOp>(GetDuplicatedOp()).getDomain();
}
}
OperandInstance OpInstance::Operand(int position) const {
return OperandInstance(*this, position);
}
int OpInstance::num_results() const {
if (is_copy()) return 1;
return GetDuplicatedOp()->getNumResults();
}
ResultInstance OpInstance::Result(int result) const {
return ResultInstance(*this, result);
}
llvm::SmallVector<int> OpInstance::SubDomains() const {
if (is_copy()) {
return {domain_size()};
} else {
return llvm::cast<SairOp>(GetDuplicatedOp()).SubDomains();
}
}
llvm::SmallBitVector OpInstance::ResultsDimDependencies() const {
if (is_copy()) {
return llvm::SmallBitVector(domain_size());
} else {
return llvm::cast<SairOp>(GetDuplicatedOp()).ResultsDimDependencies();
}
}
bool operator==(const OpInstance &lhs, const OpInstance &rhs) {
return lhs.op_ == rhs.op_ && lhs.index_ == rhs.index_ &&
lhs.result_ == rhs.result_;
}
bool operator!=(const OpInstance &lhs, const OpInstance &rhs) {
return !(lhs == rhs);
}
ComputeOpInstance::ComputeOpInstance(const OpInstance &op) : OpInstance(op) {
assert(op.isa<ComputeOpInstance>());
}
ComputeOpInstance ComputeOpInstance::Unique(ComputeOp op) {
assert(llvm::cast<SairOp>(op.getOperation()).HasExactlyOneInstance());
return ComputeOpInstance(op, 0);
}
DecisionsAttr ComputeOpInstance::GetDecisions() const {
if (is_duplicate()) {
return GetSairOp().GetDecisions(index());
}
llvm::ArrayRef<mlir::Attribute> copies =
GetValueProducer().GetCopies(result());
return copies[index()].cast<DecisionsAttr>();
}
void ComputeOpInstance::SetDecisions(DecisionsAttr decisions) {
assert(decisions != nullptr);
if (is_duplicate()) {
GetSairOp().SetDecisions(index(), decisions);
} else {
GetValueProducer().SetCopy(result(), index(), decisions);
}
}
llvm::ArrayRef<mlir::Attribute> ComputeOpInstance::Loops() const {
DecisionsAttr decisions = GetDecisions();
if (decisions.loop_nest() == nullptr) return {};
return decisions.loop_nest().getValue();
}
void ComputeOpInstance::SetLoopNest(mlir::ArrayAttr loop_nest) {
DecisionsAttr new_decisions =
MapLoopNest([=](mlir::ArrayAttr) { return loop_nest; })(GetDecisions());
SetDecisions(new_decisions);
}
BufferAttr ComputeOpInstance::Storage(int result) const {
DecisionsAttr decisions = GetDecisions();
if (decisions.storage() == nullptr ||
decisions.storage()[result].isa<mlir::UnitAttr>()) {
return nullptr;
}
return decisions.storage()[result].cast<BufferAttr>();
}
void ComputeOpInstance::SetStorage(int result, BufferAttr storage) {
DecisionsAttr decisions = GetDecisions();
auto unit_attr = mlir::UnitAttr::get(context());
llvm::SmallVector<mlir::Attribute> array(num_results(), unit_attr);
if (decisions.storage() != nullptr) {
for (int i = 0; i < num_results(); ++i) {
array[i] = decisions.storage()[i];
}
}
array[result] = storage;
mlir::ArrayAttr array_attr = mlir::ArrayAttr::get(context(), array);
DecisionsAttr new_decisions =
MapStorage([=](mlir::ArrayAttr) { return array_attr; })(decisions);
SetDecisions(new_decisions);
}
ComputeOp ComputeOpInstance::GetComputeOp() const {
return llvm::cast<ComputeOp>(GetDuplicatedOp());
}
ResultInstance ResultInstance::Unique(mlir::Value value) {
OpResult result = value.cast<OpResult>();
OpInstance producer = OpInstance::Unique(cast<SairOp>(result.getOwner()));
return ResultInstance(producer, result.getResultNumber());
}
ShapedType ResultInstance::GetType() const {
return GetValue().getType().cast<ShapedType>();
}
mlir::Value ResultInstance::GetValue() const {
if (op_.is_copy()) {
return op_.GetCopiedValue();
} else {
return op_.GetDuplicatedOp()->getResult(result_);
}
}
unsigned ResultInstance::HashValue() const {
return llvm::hash_combine(op_.HashValue(), llvm::hash_value(result_));
}
llvm::SmallVector<std::pair<OpInstance, int>> ResultInstance::GetUses() const {
llvm::SmallVector<std::pair<OpInstance, int>> uses;
// TODO(ulysse): allow specifying the instance used for operands. For now, we
// always use the first instance.
if (op_.is_copy() || op_.index() != 0) return {};
mlir::Operation *def_op = op_.GetDuplicatedOp();
// Register copy uses.
if (auto value_producer = dyn_cast<ValueProducerOp>(def_op)) {
int num_copies = value_producer.GetCopies(op_.result()).size();
// The operand number must account for domain dimensions.
int operand_number = GetType().Shape().NumDimensions();
for (int i = 0; i < num_copies; ++i) {
ComputeOpInstance instance(value_producer, op_.result(), i);
uses.emplace_back(instance, operand_number);
}
}
// Register non-copy uses.
mlir::Value value = def_op->getResult(result_);
for (OpOperand &use : value.getUses()) {
mlir::Operation *user = use.getOwner();
int operand_number = use.getOperandNumber();
auto sair_op = cast<SairOp>(user);
if (auto compute_op = dyn_cast<ComputeOp>(user)) {
for (int i = 0, e = sair_op.NumInstances(); i < e; ++i) {
uses.emplace_back(ComputeOpInstance(compute_op, i), operand_number);
}
} else {
uses.emplace_back(OpInstance(sair_op), operand_number);
}
}
return uses;
}
bool operator==(const ResultInstance &lhs, const ResultInstance &rhs) {
return lhs.op_ == rhs.op_ && lhs.result_ == rhs.result_;
}
bool operator!=(const ResultInstance &lhs, const ResultInstance &rhs) {
return !(lhs == rhs);
}
std::optional<ResultInstance> OperandInstance::GetValue() const {
// Retrieve the MLIR value.
mlir::Value value;
if (op_.is_copy()) {
value = op_.GetCopiedValue();
} else {
auto owner = cast<SairOp>(op_.GetDuplicatedOp());
value = owner.ValueOperands()[operand_position_].value();
}
auto result = value.cast<OpResult>();
mlir::Operation *defining_op = result.getOwner();
// TODO(ulysse): allow specifying the instance use in operands. For now, we
// always use the first instance.
OpInstance def_op;
if (auto compute_op = dyn_cast<ComputeOp>(defining_op)) {
if (cast<SairOp>(defining_op).NumInstances() < 1) return std::nullopt;
def_op = ComputeOpInstance(compute_op, 0);
} else {
def_op = OpInstance(cast<SairOp>(defining_op));
}
return ResultInstance(def_op, result.getResultNumber());
}
std::optional<ValueAccessInstance> OperandInstance::Get() const {
auto value = GetValue();
if (value.has_value()) return ValueAccessInstance({*value, Mapping()});
return std::nullopt;
}
MappingAttr OperandInstance::Mapping() const {
if (op_.is_copy()) {
return MappingAttr::GetIdentity(op_.context(), op_.domain_size());
} else {
return GetOriginalOperand().Mapping();
}
}
llvm::SmallBitVector OperandInstance::DependingDims() const {
if (op_.is_copy()) {
return llvm::SmallBitVector(op_.domain_size());
} else {
return GetOriginalOperand().DependingDims();
}
}
bool OperandInstance::AllowUseBeforeDef() const {
if (op_.is_copy()) return false;
return GetOriginalOperand().AllowUseBeforeDef();
}
llvm::SmallBitVector OperandInstance::CarryingDims() const {
if (op_.is_copy()) {
return llvm::SmallBitVector(op_.domain_size());
} else {
return GetOriginalOperand().CarryingDims();
}
}
ValueOperand OperandInstance::GetOriginalOperand() const {
auto sair_op = cast<SairOp>(op_.GetDuplicatedOp());
return sair_op.ValueOperands()[operand_position_];
}
#include "sair_op_interfaces.cc.inc"
} // namespace sair