-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathDependency.cpp
More file actions
3280 lines (3050 loc) · 126 KB
/
Dependency.cpp
File metadata and controls
3280 lines (3050 loc) · 126 KB
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- Dependency.cpp -------------------------------------------*- C++ -*-===//
//
// Copyright (C) 2022, Xilinx Inc. All rights reserved.
// Copyright (C) 2022, Advanced Micro Devices, Inc. All rights reserved.
// SPDX-License-Identifier: MIT
//
//===----------------------------------------------------------------------===//
#include "air/Util/Dependency.h"
#include "air/Util/Util.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/Utils/Utils.h"
#include "mlir/IR/Iterators.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#define DEBUG_TYPE "air-dependency-util"
using namespace mlir;
namespace xilinx {
namespace air {
using Graph = dependencyGraph::Graph;
bool areEqualIndices(mlir::Value index_0, mlir::Value index_1) {
if (index_0 == nullptr || index_1 == nullptr) {
// Note: memref with index is subset to memref without index (i.e. the
// entire memref)
return true;
} else {
if (index_0 == index_1)
return true;
else if (!index_0.getDefiningOp())
return false;
else if (!index_1.getDefiningOp())
return false;
else {
if (auto index_0_const_op =
dyn_cast_if_present<arith::ConstantOp>(index_0.getDefiningOp())) {
if (auto index_1_const_op = dyn_cast_if_present<arith::ConstantOp>(
index_1.getDefiningOp())) {
if (index_0_const_op.getValue() == index_1_const_op.getValue())
return true;
}
}
return false;
}
}
}
void traceDependentInductionVar(SmallVector<Value, 1> candidate_scalar_operands,
SmallVector<Value, 1> &loop_dep_history,
std::vector<Operation *> &op_history) {
for (auto operand : candidate_scalar_operands) {
if (!llvm::isa<IndexType, IntegerType, FloatType>(operand.getType()))
continue; // Only tracing scalar operands
// If parent loop op is an scf.for
if (auto for_op = mlir::scf::getForInductionVarOwner(operand)) {
loop_dep_history.push_back(for_op.getInductionVar());
}
// If parent loop op is an scf.parallel
if (auto par_op = mlir::scf::getParallelForInductionVarOwner(operand)) {
for (auto ind_var : par_op.getInductionVars())
if (ind_var == operand)
loop_dep_history.push_back(ind_var);
}
// If parent loop op is an air.herd
if (auto hl_op = getHerdArgOwner(operand)) {
for (auto id : hl_op.getIds()) {
if (operand == id) {
loop_dep_history.push_back(id);
}
}
}
}
// Recursively trace dependency to loop induction vars
for (auto operand : candidate_scalar_operands) {
if (!llvm::isa<IndexType, IntegerType, FloatType>(operand.getType()))
continue; // Only tracing scalar operands
auto defOp = operand.getDefiningOp();
if (defOp) {
op_history.push_back(defOp);
traceDependentInductionVar(defOp, loop_dep_history, op_history);
} else {
// Trace dependency through a for loop
if (auto for_op = getForRegionIterArgsOwner(operand)) {
for (auto iter_arg : for_op.getInitArgs()) {
if (operand == iter_arg) {
loop_dep_history.push_back(iter_arg);
}
}
}
// Trace dependency through a parallel loop
// TODO: decide if parallel should exist in herd launch
}
}
}
// Recursively check for dependency to loop induction vars arising from dma
void traceDependentInductionVar(air::MemcpyInterface memcpyif_op,
SmallVector<Value, 1> &loop_dep_history,
std::vector<Operation *> &op_history) {
// Check for immediate dependency to loop induction vars
SmallVector<Value, 1> candidate_scalar_operands;
if (memcpyif_op.getSrcMemref()) {
for (unsigned i = 0; i < memcpyif_op.getSrcOffsets().size(); i++) {
candidate_scalar_operands.push_back(memcpyif_op.getSrcOffsets()[i]);
candidate_scalar_operands.push_back(memcpyif_op.getSrcSizes()[i]);
candidate_scalar_operands.push_back(memcpyif_op.getSrcStrides()[i]);
}
}
if (memcpyif_op.getDstMemref()) {
for (unsigned i = 0; i < memcpyif_op.getDstOffsets().size(); i++) {
candidate_scalar_operands.push_back(memcpyif_op.getDstOffsets()[i]);
candidate_scalar_operands.push_back(memcpyif_op.getDstSizes()[i]);
candidate_scalar_operands.push_back(memcpyif_op.getDstStrides()[i]);
}
}
// Check for dependency through any parent affine if guards
if (auto parentAffineIf =
memcpyif_op->getParentOfType<affine::AffineIfOp>()) {
if (parentAffineIf->getParentOfType<air::HerdOp>()) {
candidate_scalar_operands.insert(candidate_scalar_operands.end(),
parentAffineIf.getOperands().begin(),
parentAffineIf.getOperands().end());
}
}
// Start recursion.
traceDependentInductionVar(candidate_scalar_operands, loop_dep_history,
op_history);
}
// Recursively check for dependency to any loop induction vars
void traceDependentInductionVar(Operation *op,
SmallVector<Value, 1> &loop_dep_history,
std::vector<Operation *> &op_history) {
SmallVector<Value, 1> candidate_scalar_operands;
// Get child op if op is air.execute
if (auto air_region_op = dyn_cast_if_present<air::ExecuteOp>(op)) {
if (air_region_op.getRegion().front().getOperations().size() != 2) {
air_region_op->emitOpError("air::ExecuteOp should have only one child "
"operation beside the terminator");
return;
}
for (auto &child_op : air_region_op.getRegion().front().getOperations()) {
if (!dyn_cast_if_present<air::ExecuteTerminatorOp>(child_op))
op = &child_op;
}
}
candidate_scalar_operands.insert(candidate_scalar_operands.end(),
op->getOperands().begin(),
op->getOperands().end());
// Check for dependency through any parent affine if guards
if (auto parentAffineIf = op->getParentOfType<affine::AffineIfOp>()) {
if (parentAffineIf->getParentOfType<air::HerdOp>()) {
candidate_scalar_operands.insert(candidate_scalar_operands.end(),
parentAffineIf.getOperands().begin(),
parentAffineIf.getOperands().end());
}
}
// Start recursion.
traceDependentInductionVar(op->getOperands(), loop_dep_history, op_history);
}
// Recursively check for dependency to any air.herd induction variables.
void traceDependentHerdId(Operation *async_op,
SmallVector<Value> &loop_dep_history,
SmallVector<Operation *> &op_history) {
if (!isAsyncOp(async_op))
return;
// Get child op if async_op is air.execute
Operation *op = nullptr;
if (auto air_execute_op = dyn_cast_if_present<air::ExecuteOp>(async_op)) {
op = &air_execute_op.getChildOps().front();
} else {
op = async_op;
}
// Check for immediate dependency to loop induction vars
for (auto operand : op->getOperands()) {
// If parent loop op is an air.launch_herd
if (auto hl_op = air::getHerdArgOwner(operand)) {
for (auto id : hl_op.getIds()) {
if (operand == id) {
loop_dep_history.push_back(id);
}
}
}
}
// Recursively trace dependency to loop induction vars
for (auto operand : op->getOperands()) {
if (operand && llvm::isa<IndexType>(
operand.getType())) { // Only tracing scalar operands
if (operand.getDefiningOp() &&
mlir::dyn_cast_if_present<air::AsyncOpInterface>(
operand.getDefiningOp())) {
op_history.push_back(operand.getDefiningOp());
traceDependentHerdId(operand.getDefiningOp(), loop_dep_history,
op_history);
} else if (auto scf_for = scf::getForInductionVarOwner(operand)) {
op_history.push_back(scf_for);
traceDependentHerdId(scf_for, loop_dep_history, op_history);
}
}
}
}
// Recursively check for dependency to air herd op induction vars.
std::vector<std::tuple<Value, SmallVector<Value>, SmallVector<Operation *>>>
traceDependentHerdId(air::DmaMemcpyNdOp dmaNd_op) {
// Tuple fields: value, ancestors and producers to those ancestors.
std::vector<std::tuple<Value, SmallVector<Value>, SmallVector<Operation *>>>
loop_dep_history;
for (unsigned i = 0; i < dmaNd_op.getSrcOffsets().size(); i++) {
loop_dep_history.push_back(std::make_tuple(dmaNd_op.getSrcOffsets()[i],
SmallVector<Value>{},
SmallVector<Operation *>{}));
loop_dep_history.push_back(std::make_tuple(dmaNd_op.getSrcSizes()[i],
SmallVector<Value>{},
SmallVector<Operation *>{}));
loop_dep_history.push_back(std::make_tuple(dmaNd_op.getSrcStrides()[i],
SmallVector<Value>{},
SmallVector<Operation *>{}));
}
for (unsigned i = 0; i < dmaNd_op.getDstOffsets().size(); i++) {
loop_dep_history.push_back(std::make_tuple(dmaNd_op.getDstOffsets()[i],
SmallVector<Value>{},
SmallVector<Operation *>{}));
loop_dep_history.push_back(std::make_tuple(dmaNd_op.getDstSizes()[i],
SmallVector<Value>{},
SmallVector<Operation *>{}));
loop_dep_history.push_back(std::make_tuple(dmaNd_op.getDstStrides()[i],
SmallVector<Value>{},
SmallVector<Operation *>{}));
}
for (auto &elem : loop_dep_history) {
// If parent loop op is an air.launch_herd
if (auto hl_op = air::getHerdArgOwner(std::get<0>(elem))) {
for (auto id : hl_op.getIds()) {
if (std::get<0>(elem) == id) {
std::get<1>(elem).push_back(id);
}
}
}
}
// Recursively trace dependency to loop induction vars
for (auto &elem : loop_dep_history) {
if (std::get<0>(elem) &&
llvm::isa<IndexType>(
std::get<0>(elem).getType())) { // Only tracing scalar operands
if (std::get<0>(elem).getDefiningOp() &&
mlir::dyn_cast_if_present<air::AsyncOpInterface>(
std::get<0>(elem).getDefiningOp())) {
auto ancestor_async_op = std::get<0>(elem).getDefiningOp();
std::get<2>(elem).push_back(ancestor_async_op);
traceDependentHerdId(ancestor_async_op, std::get<1>(elem),
std::get<2>(elem));
}
}
}
return loop_dep_history;
}
void eraseAsyncDependencyFromAsyncOp(xilinx::air::AsyncOpInterface op,
Value token) {
if (!token)
return;
if (!llvm::isa<air::AsyncTokenType>(token.getType()))
return;
auto dependency_list = op.getAsyncDependencies();
if (!dependency_list.size())
return;
for (int i = dependency_list.size() - 1; i >= 0; i--) {
if (dependency_list[i] == token) {
op.eraseAsyncDependency(i);
}
}
}
void clearAsyncDependenciesOfAsyncOpImpl(xilinx::air::AsyncOpInterface op) {
auto dependency_list = op.getAsyncDependencies();
if (!dependency_list.size())
return;
for (int i = dependency_list.size() - 1; i >= 0; i--) {
op.eraseAsyncDependency(i);
}
}
void clearAsyncDependenciesOfAsyncOpImpl(scf::ForOp op) {
SmallVector<Value> operands_without_wait_all;
for (auto iter_oper : op.getInitArgs()) {
// Push to vec if unique
if (std::find(operands_without_wait_all.begin(),
operands_without_wait_all.end(),
iter_oper) == operands_without_wait_all.end()) {
operands_without_wait_all.push_back(iter_oper);
}
}
for (auto v : operands_without_wait_all) {
OpBuilder builder(op);
SmallVector<Value> dep_list = {};
air::WaitAllOp wait_all_op_before_loop = xilinx::air::WaitAllOp::create(
builder, builder.getUnknownLoc(),
air::AsyncTokenType::get(op->getContext()), dep_list);
op->replaceUsesOfWith(v, wait_all_op_before_loop.getAsyncToken());
}
}
void clearAsyncDependenciesOfAsyncOpImpl(scf::ParallelOp op) {
SmallVector<Value> operands_without_wait_all;
for (auto init_val : op.getInitVals()) {
if (auto wa_op =
dyn_cast_if_present<air::WaitAllOp>(init_val.getDefiningOp())) {
clearAsyncDependenciesOfAsyncOpImpl(wa_op);
} else {
// Push to vec if unique
if (std::find(operands_without_wait_all.begin(),
operands_without_wait_all.end(),
init_val) == operands_without_wait_all.end()) {
operands_without_wait_all.push_back(init_val);
}
}
}
for (auto v : operands_without_wait_all) {
OpBuilder builder(op);
SmallVector<Value> dep_list = {};
air::WaitAllOp wait_all_op_before_loop = xilinx::air::WaitAllOp::create(
builder, builder.getUnknownLoc(),
air::AsyncTokenType::get(op->getContext()), dep_list);
op->replaceUsesOfWith(v, wait_all_op_before_loop.getAsyncToken());
}
}
void clearAsyncDependenciesOfAsyncOp(Operation *op) {
if (!isAsyncOp(op)) {
return;
}
if (auto async_op = dyn_cast_if_present<air::AsyncOpInterface>(op)) {
clearAsyncDependenciesOfAsyncOpImpl(async_op);
} else if (auto for_op = dyn_cast_if_present<scf::ForOp>(op)) {
clearAsyncDependenciesOfAsyncOpImpl(for_op);
} else if (auto parallel_op = dyn_cast_if_present<scf::ParallelOp>(op)) {
clearAsyncDependenciesOfAsyncOpImpl(parallel_op);
} else
op->emitOpError("unknown async op");
}
// Get loop-carried dependency token from scf loop op
Value getLoopCarriedTokenFromScfOp(scf::ParallelOp op) {
if (!op.getInitVals().size()) {
op->emitOpError("has no init_val");
return nullptr;
}
auto token = op.getInitVals()[0];
if (!llvm::isa<air::AsyncTokenType>(token.getType())) {
op->emitOpError("init_val is not an async token");
return nullptr;
}
return token;
}
Value getLoopCarriedTokenFromScfOp(scf::ForOp op,
std::string operand_or_argument) {
if (operand_or_argument == "operand") {
if (!op.getInitArgs().size()) {
return nullptr;
}
for (auto initArg : op.getInitArgs()) {
if (isa<air::AsyncTokenType>(initArg.getType()))
return initArg;
}
// No async token found - return nullptr without error
return nullptr;
} else if (operand_or_argument == "argument") {
if (!op.getRegionIterArgs().size()) {
return nullptr;
}
for (auto iterArg : op.getRegionIterArgs()) {
if (isa<air::AsyncTokenType>(iterArg.getType())) {
return iterArg;
}
}
// No async token found - return nullptr without error
return nullptr;
} else {
op->emitOpError("unknown string in operand_or_argument");
return nullptr;
}
}
air::WaitAllOp assignEmptyWaitAllAtScfForIterArg(OpBuilder builder,
scf::ForOp &op) {
auto checkpoint = builder.saveInsertionPoint();
builder.setInsertionPoint(op);
air::WaitAllOp sink_wait_all_op = air::WaitAllOp::create(
builder, op->getLoc(), air::AsyncTokenType::get(builder.getContext()),
SmallVector<Value>{});
op->getOpOperand(op.getNumControlOperands())
.assign(sink_wait_all_op.getAsyncToken());
builder.restoreInsertionPoint(checkpoint);
return sink_wait_all_op;
}
// Create scf.reduce op to reduce all async tokens in an scf.parallel
scf::ReduceOp createSCFReduceForAsyncSCFParallel(OpBuilder builder,
Location loc, Value token,
MLIRContext *ctx) {
auto reduce_op = scf::ReduceOp::create(builder, loc, token);
builder.setInsertionPointToStart(&reduce_op.getRegion(0).front());
SmallVector<Value, 4> reduce_tokens;
reduce_tokens.push_back(reduce_op.getRegion(0).front().getArgument(0));
reduce_tokens.push_back(reduce_op.getRegion(0).front().getArgument(1));
auto reduce_res = xilinx::air::WaitAllOp::create(
builder, builder.getUnknownLoc(), air::AsyncTokenType::get(ctx),
reduce_tokens);
scf::ReduceReturnOp::create(builder, builder.getUnknownLoc(),
reduce_res.getResult(0));
return reduce_op;
}
// Get dependency list of op
SmallVector<Value> getAsyncDependenciesFromOpImpl(air::AsyncOpInterface op) {
return op.getAsyncDependencies();
}
SmallVector<Value> getAsyncDependenciesFromOpImpl(scf::ForOp op) {
return op.getInitArgs();
}
SmallVector<Value> getAsyncDependenciesFromOpImpl(scf::ParallelOp op) {
return op.getInitVals();
}
SmallVector<Value> getAsyncDependenciesFromOpImpl(affine::AffineIfOp op) {
SmallVector<Value> depList;
for (auto operand : op->getOperands()) {
if (!isa<air::AsyncTokenType>(operand.getType()))
continue;
depList.push_back(operand);
}
return depList;
}
SmallVector<Value> getAsyncDependenciesFromOpImpl(scf::IfOp op) {
// Collect async token values used inside the scf.if but defined outside.
// This allows areAsyncDependent to detect that an scf.if implicitly depends
// on async tokens consumed by ops in its then/else branches.
SmallVector<Value> depList;
for (auto ®ion : op->getRegions()) {
region.walk([&](Operation *innerOp) {
for (auto operand : innerOp->getOperands()) {
if (!isa<air::AsyncTokenType>(operand.getType()))
continue;
// Check if defined outside the scf.if.
if (auto *defOp = operand.getDefiningOp()) {
if (op->isAncestor(defOp))
continue;
} else {
// Block argument: check if the owning block is inside the scf.if.
auto blockArg = cast<BlockArgument>(operand);
if (auto *ownerOp = blockArg.getOwner()->getParentOp())
if (op->isAncestor(ownerOp))
continue;
}
if (llvm::find(depList, operand) == depList.end())
depList.push_back(operand);
}
});
}
return depList;
}
SmallVector<Value> getAsyncDependenciesFromOp(Operation *op) {
if (auto async_op = dyn_cast_if_present<air::AsyncOpInterface>(op))
return getAsyncDependenciesFromOpImpl(async_op);
else if (auto for_op = dyn_cast_if_present<scf::ForOp>(op))
return getAsyncDependenciesFromOpImpl(for_op);
else if (auto par_op = dyn_cast_if_present<scf::ParallelOp>(op))
return getAsyncDependenciesFromOpImpl(par_op);
else if (auto aif_op = dyn_cast_if_present<affine::AffineIfOp>(op))
return getAsyncDependenciesFromOpImpl(aif_op);
else if (auto if_op = dyn_cast_if_present<scf::IfOp>(op))
return getAsyncDependenciesFromOpImpl(if_op);
else
return SmallVector<Value>();
}
// Get returned async token from op
Value getAsyncTokenFromOpImpl(air::AsyncOpInterface op) {
return op.getAsyncToken();
}
Value getAsyncTokenFromOpImpl(Operation *op) {
for (auto res : op->getResults()) {
if (isa<air::AsyncTokenType>(res.getType()))
return res;
}
return nullptr;
}
Value getAsyncTokenFromOp(Operation *op) {
if (auto async_op = dyn_cast_if_present<air::AsyncOpInterface>(op))
return getAsyncTokenFromOpImpl(async_op);
else
return getAsyncTokenFromOpImpl(op);
}
// Convert scf.for op to async, by adding an async token iter arg.
struct MakeAsyncScfForPattern : public OpRewritePattern<scf::ForOp> {
using OpRewritePattern<scf::ForOp>::OpRewritePattern;
MakeAsyncScfForPattern(MLIRContext *ctx, Value token)
: OpRewritePattern(ctx), token(token) {}
LogicalResult matchAndRewrite(scf::ForOp forOp,
PatternRewriter &rewriter) const override {
if (!air::getAsyncDependenciesFromOp(forOp).empty())
return failure();
if (!isa<air::AsyncTokenType>(token.getType()))
return failure();
if (failed(forOp.replaceWithAdditionalIterOperands(
rewriter, SmallVector<Value>{token}, true)))
return failure();
return success();
}
private:
Value token;
};
// Add async dependency to op if unique
void addAsyncDependencyIfNewImpl(air::AsyncOpInterface op, Value token) {
if (!llvm::isa<air::AsyncTokenType>(token.getType())) {
op->emitOpError("value is not an async token");
return;
}
bool foundTokenInDepList = false;
if (op.getAsyncDependencies().size()) {
for (auto old_dep : op.getAsyncDependencies())
if (old_dep == token)
foundTokenInDepList = true;
if (!foundTokenInDepList) {
op.addAsyncDependency(token);
}
} else {
op.addAsyncDependency(token);
}
}
void addAsyncDependencyIfNewImpl(scf::ForOp op, Value token) {
auto ctx = op->getContext();
llvm::SetVector<Value> operands_without_wait_all;
for (auto iter_oper : op.getInitArgs()) {
if (!isa_and_present<air::AsyncTokenType>(iter_oper.getType()))
continue;
auto wa_op = dyn_cast_if_present<air::WaitAllOp>(iter_oper.getDefiningOp());
if (wa_op && wa_op.getAsyncToken().hasOneUse())
addAsyncDependencyIfNewImpl(wa_op, token);
else
operands_without_wait_all.insert(iter_oper);
}
for (auto v : operands_without_wait_all) {
OpBuilder builder(op);
SmallVector<Value> dep_list = {token, v};
air::WaitAllOp wait_all_op_before_loop =
xilinx::air::WaitAllOp::create(builder, builder.getUnknownLoc(),
air::AsyncTokenType::get(ctx), dep_list);
op->replaceUsesOfWith(v, wait_all_op_before_loop.getAsyncToken());
}
// If scf.for loop isn't async, then make it async.
if (!isAsyncOp(op)) {
RewritePatternSet patterns(ctx);
patterns.insert<MakeAsyncScfForPattern>(ctx, token);
(void)applyOpPatternsGreedily(ArrayRef<Operation *>{op},
std::move(patterns));
}
}
void addAsyncDependencyIfNewImpl(scf::ParallelOp op, Value token) {
SmallVector<Value> operands_without_wait_all;
for (auto init_val : op.getInitVals()) {
if (init_val.getDefiningOp() &&
isa<air::WaitAllOp>(init_val.getDefiningOp())) {
auto wa_op =
dyn_cast_if_present<air::WaitAllOp>(init_val.getDefiningOp());
addAsyncDependencyIfNewImpl(wa_op, token);
} else {
// Push to vec if unique
if (std::find(operands_without_wait_all.begin(),
operands_without_wait_all.end(),
init_val) == operands_without_wait_all.end()) {
operands_without_wait_all.push_back(init_val);
}
}
}
for (auto v : operands_without_wait_all) {
OpBuilder builder(op);
SmallVector<Value> dep_list = {};
air::WaitAllOp wait_all_op_before_loop = xilinx::air::WaitAllOp::create(
builder, builder.getUnknownLoc(),
air::AsyncTokenType::get(op->getContext()), dep_list);
op->replaceUsesOfWith(v, wait_all_op_before_loop.getAsyncToken());
replaceAllUsesInRegionWith(v, wait_all_op_before_loop.getAsyncToken(),
op.getRegion());
addAsyncDependencyIfNewImpl(wait_all_op_before_loop, v);
addAsyncDependencyIfNewImpl(wait_all_op_before_loop, token);
}
}
void addAsyncDependencyIfNewImpl(affine::AffineIfOp op, Value token) {
// Process operations in the then block
for (auto &nested_op : op.getThenBlock()->getOperations()) {
// Skip affine.yield terminators
if (isa<affine::AffineYieldOp>(nested_op))
continue;
// Recursively process nested affine.if operations
if (auto nested_affine_if =
dyn_cast_if_present<affine::AffineIfOp>(nested_op)) {
addAsyncDependencyIfNewImpl(nested_affine_if, token);
} else {
// For non-affine.if operations, call addAsyncDependencyIfNew
addAsyncDependencyIfNew(&nested_op, token);
}
}
// Process operations in the else block if it exists
if (op.hasElse()) {
for (auto &nested_op : op.getElseBlock()->getOperations()) {
// Skip affine.yield terminators
if (isa<affine::AffineYieldOp>(nested_op))
continue;
// Recursively process nested affine.if operations
if (auto nested_affine_if =
dyn_cast_if_present<affine::AffineIfOp>(nested_op)) {
addAsyncDependencyIfNewImpl(nested_affine_if, token);
} else {
// For non-affine.if operations, call addAsyncDependencyIfNew
addAsyncDependencyIfNew(&nested_op, token);
}
}
}
}
void addAsyncDependencyIfNew(Operation *op, Value token) {
if (!op)
return;
if (!isAsyncOp(op))
return;
if (!token)
return;
if (token.getDefiningOp() && token.getDefiningOp() == op)
return;
if (auto async_op = dyn_cast_if_present<air::AsyncOpInterface>(op)) {
addAsyncDependencyIfNewImpl(async_op, token);
} else if (auto for_op = dyn_cast_if_present<scf::ForOp>(op)) {
addAsyncDependencyIfNewImpl(for_op, token);
} else if (auto parallel_op = dyn_cast_if_present<scf::ParallelOp>(op)) {
addAsyncDependencyIfNewImpl(parallel_op, token);
} else if (auto affine_if_op = dyn_cast_if_present<affine::AffineIfOp>(op)) {
addAsyncDependencyIfNewImpl(affine_if_op, token);
} else
op->emitOpError("unknown async op");
}
bool isAsyncOp(Operation *op) {
if (!op)
return false;
if (llvm::any_of(op->getResults(), [](Value r) {
return isa<air::AsyncTokenType>(r.getType());
}))
return true;
return false;
}
// Air dependency comes in two forms: production and consumption of the same
// async token, and usage of the same air.channel.
bool areAsyncDependent(Operation *a, Operation *b) {
SmallVector<Value> dep_a = getAsyncDependenciesFromOp(a);
Value token_a = getAsyncTokenFromOp(a);
SmallVector<Value> dep_b = getAsyncDependenciesFromOp(b);
Value token_b = getAsyncTokenFromOp(b);
if (!token_a)
return false;
if (!token_b)
return false;
for (auto dep : dep_a)
if (dep == token_b)
return true;
for (auto dep : dep_b)
if (dep == token_a)
return true;
// Deep async dependency tracing through air.wait_all.
if (isAsyncDependent(a, b))
return true;
if (isAsyncDependent(b, a))
return true;
auto chanA = dyn_cast_if_present<air::ChannelInterface>(a);
auto chanB = dyn_cast_if_present<air::ChannelInterface>(b);
if (chanA && chanB)
if (chanA.getChanName() == chanB.getChanName()) {
if (chanA.getIndices().size() != chanB.getIndices().size())
return true;
// Check all index positions. If ANY position has two different constant
// values, we can prove independence regardless of other positions.
for (unsigned i = 0; i < chanA.getIndices().size(); i++) {
auto constIdxA = getConstantIntValue(chanA.getIndices()[i]);
auto constIdxB = getConstantIntValue(chanB.getIndices()[i]);
// If BOTH are constants AND they differ → INDEPENDENT
if (constIdxA && constIdxB && (*constIdxA != *constIdxB))
return false;
}
// After checking all indices, if none were provably different →
// DEPENDENT
return true;
}
return false;
}
// Returns true if b is asynchronously dependent on a. This function performs a
// deep dependency tracing that propagates through air.wait_all ops.
bool isAsyncDependent(Operation *a, Operation *b) {
if (a == b)
return true;
Value token_a = getAsyncTokenFromOp(a);
SmallVector<Value> dep_b = getAsyncDependenciesFromOp(b);
if (!token_a)
return false;
if (dep_b.empty())
return false;
for (auto dep : dep_b) {
if (dep == token_a)
return true;
else if (dep.getDefiningOp() && air::isAsyncOp(dep.getDefiningOp())) {
if (isAsyncDependent(a, dep.getDefiningOp()))
return true;
}
}
return false;
}
// Generate a wait_all at the end of block, which gathers all dangling async
// tokens.
air::WaitAllOp generateWaitAllToTerminateBlock(Block &block, OpBuilder &b,
bool isBlocking) {
llvm::SetVector<Value> blockTokens, danglingTokens;
blockTokens.insert(block.getArguments().begin(), block.getArguments().end());
for (auto &o : block.getOperations())
blockTokens.insert(o.getResults().begin(), o.getResults().end());
for (auto t : blockTokens) {
if (!t.use_empty())
continue;
if (!isa<air::AsyncTokenType>(t.getType()))
continue;
danglingTokens.insert(t);
}
if (block.mightHaveTerminator())
b.setInsertionPoint(block.getTerminator());
else
b.setInsertionPointToEnd(&block);
if (isBlocking)
return air::WaitAllOp::create(b, b.getUnknownLoc(),
/*result_type*/ Type(),
danglingTokens.takeVector());
else
return air::WaitAllOp::create(b, b.getUnknownLoc(),
air::AsyncTokenType::get(b.getContext()),
danglingTokens.takeVector());
}
// Splits an SCF for loop into two for loops, by hoisting target operations in
// for loop to a new for loop located at the same scope.
scf::ForOp hoistTargetOpsToNewSCFFor(PatternRewriter &rewriter,
scf::ForOp for_op,
SmallVector<Operation *> target_ops) {
auto loc = for_op->getLoc();
// If target ops are already perfectly nested, then skip
auto hasNChannelOps = [target_ops](Block *block, unsigned N) {
unsigned counter = 0;
block->walk<WalkOrder::PreOrder, ForwardDominanceIterator<>>(
[target_ops, &counter](Operation *op) {
if (op->hasTrait<OpTrait::IsIsolatedFromAbove>())
return WalkResult::skip();
if (llvm::is_contained(target_ops, op)) {
counter++;
return WalkResult::skip();
}
if (isa<air::ChannelInterface>(op))
counter++;
counter++;
return WalkResult::advance();
});
return counter == N;
};
if (hasNChannelOps(for_op.getBody(), 1))
return for_op;
rewriter.setInsertionPoint(for_op);
IRMapping remap;
auto new_for_op = scf::ForOp::create(rewriter, loc, for_op.getLowerBound(),
for_op.getUpperBound(), for_op.getStep(),
for_op.getInitArgs());
// Copy select attributes from old loop (sym_name, etc.)
// Don't copy "unroll" — the new loop is the hoisted subset,
// not the one targeted for ping-pong.
if (auto attr =
for_op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()))
new_for_op->setAttr(SymbolTable::getSymbolAttrName(), attr);
remap.map(for_op.getInductionVar(), new_for_op.getInductionVar());
remap.map(getLoopCarriedTokenFromScfOp(for_op, "argument"),
getLoopCarriedTokenFromScfOp(new_for_op, "argument"));
rewriter.setInsertionPointToStart(new_for_op.getBody());
// Build up a log of ops to be cloned; using SetVector to avoid repetition.
llvm::SetVector<Operation *> ops_to_be_cloned;
for (auto op : target_ops) {
if (op->getParentOp() != for_op.getOperation())
continue;
// Clone defining ops of both the target_op's operands, and any used values
// within its regions.
llvm::SetVector<Value> region_opers;
for (auto ®ion : op->getRegions())
getUsedValuesDefinedAbove(region, region_opers);
region_opers.insert(op->getOperands().begin(), op->getOperands().end());
SmallVector<Value> region_opers_vec = region_opers.takeVector();
llvm::SetVector<Operation *> backwardSlices;
air::getBackwardSliceInRegion(rewriter, &for_op.getRegion(),
region_opers_vec, backwardSlices);
ops_to_be_cloned.insert(backwardSlices.begin(), backwardSlices.end());
ops_to_be_cloned.insert(op);
}
// Clone all collected operations into the new for loop body
for (auto o : ops_to_be_cloned)
rewriter.clone(*o, remap);
SmallVector<Value> yield_operands;
// If the new for loop is async, we need to properly terminate it with async
// tokens
if (air::isAsyncOp(new_for_op)) {
// Generate a wait_all op that collects all dangling async tokens in the
// loop body. This ensures all async operations within the loop are properly
// synchronized.
auto waitAllOp = generateWaitAllToTerminateBlock(
*new_for_op.getBody(), rewriter, /*isBlocking*/ false);
yield_operands.push_back(getAsyncTokenFromOp(waitAllOp));
// Create the scf.yield operation for the loop, yielding a wait_all token.
// The yielded wait_all synchronizes on all operations collected by
// waitAllOp, allowing the for loop to properly propagate async dependencies
// to subsequent iterations.
scf::YieldOp::create(
rewriter, loc,
SmallVector<Value>{air::WaitAllOp::create(
rewriter, loc,
air::AsyncTokenType::get(rewriter.getContext()),
yield_operands)
->getResult(0)});
}
return new_for_op;
}
// Walk the body of an scf.for loop and attaches an attribute (e.g.,
// "scf.for_result_id") to each operation that defines a value yielded by
// scf.yield. Each label includes the index of the result it corresponds to
// (e.g., 0 for the first result, etc.).
void labelYieldDefiningOpsOfForLoop(scf::ForOp forOp, StringRef attrName) {
// Get the yield operation in the loop body.
auto yieldOp =
dyn_cast_if_present<scf::YieldOp>(forOp.getBody()->getTerminator());
if (!yieldOp)
return;
for (auto it : llvm::enumerate(yieldOp.getOperands())) {
Value yieldedValue = it.value();
Operation *defOp = yieldedValue.getDefiningOp();
// Only label ops that are defined within the loop body
if (defOp && forOp.getRegion().isAncestor(defOp->getParentRegion())) {
defOp->setAttr(attrName,
IntegerAttr::get(IntegerType::get(forOp->getContext(), 32),
static_cast<int32_t>(it.index())));
}
}
}
// Collect operations with the integer attribute "scf.for_result_id" and
// groups them into vectors by the attribute value. Result is a vector of
// vectors Operation*, where each sub-vector corresponds to a specific result
// index.
SmallVector<SmallVector<Operation *>>
collectOpsByScfForResultId(Block &block, StringRef attrName) {
llvm::DenseMap<int64_t, SmallVector<Operation *>> resultAsMap;
block.walk([&](Operation *op) {
auto attr = op->getAttrOfType<IntegerAttr>(attrName);
if (!attr)
return;
int64_t resultId = attr.getInt();
resultAsMap[resultId].push_back(op);
op->removeAttr(attrName);
});
// Convert to a vector of vectors.
SmallVector<SmallVector<Operation *>> groupedOps;
for (auto &entry : resultAsMap) {
groupedOps.push_back(entry.second);
}
return groupedOps;
}
llvm::SmallDenseSet<OpOperand *>
getUsesOfAsyncTokens(const SmallVector<Operation *> &ops) {
llvm::SmallDenseSet<OpOperand *> uses;
for (Operation *op : ops) {
if (!air::isAsyncOp(op))
continue;
Value token = air::getAsyncTokenFromOp(op);
for (OpOperand &use : token.getUses()) {
uses.insert(&use);
}
}
return uses;
}
// Maintain async token dependencies for unrolled loop ops.
void preserveAsyncDependenciesAfterUnroll(Block &parentBlock) {
// Collect unrolled ops corresponding to each original loop result
SmallVector<SmallVector<Operation *>> unrolledOps =
collectOpsByScfForResultId(parentBlock, "scf.for_result_id");
for (auto &vec : unrolledOps) {
auto tokenUses = getUsesOfAsyncTokens(vec);
for (OpOperand *use : tokenUses) {
Operation *user = use->getOwner();
if (auto yieldUser = dyn_cast_if_present<scf::YieldOp>(user)) {
OpBuilder builder(yieldUser);
user = air::WaitAllOp::create(
builder, yieldUser->getLoc(),
air::AsyncTokenType::get(yieldUser->getContext()),
SmallVector<Value>{use->get()});
use->assign(user->getResult(0));
}
air::AsyncOpInterface asyncUser =
dyn_cast_if_present<air::AsyncOpInterface>(user);
if (!asyncUser) {
user->emitWarning(
"An async token returned by an unrolled scf.for loop is used by "
"an op not in AsyncOpInterface type. Only the last unrolled "
"iteration's dependency is preserved.");
continue;
}
for (Operation *op : vec) {
if (!air::isAsyncOp(op))
continue;
// Only add dependency if SSA dominance is preserved
DominanceInfo domInfo(op);
if (!domInfo.properlyDominates(op, asyncUser))
continue;
air::addAsyncDependencyIfNew(asyncUser, air::getAsyncTokenFromOp(op));
}
}
}
}
// Returns the set of ops in herdBody that must be kept when performing a
// lightweight herd clone: channel ops, allocs, deallocations, wait_alls, the
// terminator, and any ops that transitively define operands consumed by those.
static SmallPtrSet<Operation *, 16> collectHerdBodyOpsToKeep(Block &herdBody) {
SmallPtrSet<Operation *, 16> toKeep;
// Always keep the block terminator.
if (!herdBody.empty())
toKeep.insert(herdBody.getTerminator());
// Seed: channel ops, allocs, deallocations, and wait_alls.
for (Operation &op : herdBody.without_terminator()) {
if (isa<air::ChannelInterface, memref::AllocOp, memref::DeallocOp,
air::WaitAllOp>(op))
toKeep.insert(&op);
}
// Expand: add ops whose results are consumed by any kept op (within block).
// Use a worklist to avoid redundant re-processing of already-kept ops.
SmallVector<Operation *> worklist(toKeep.begin(), toKeep.end());
while (!worklist.empty()) {
Operation *op = worklist.pop_back_val();
for (Value operand : op->getOperands()) {
if (Operation *defOp = operand.getDefiningOp()) {
if (defOp->getBlock() == &herdBody && toKeep.insert(defOp).second)
worklist.push_back(defOp);
}
}
}
return toKeep;
}
// Lightweight clone of air.HerdOp: creates a new herd shell via OperationState