-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathcontrol_flow_graph.cc
1641 lines (1387 loc) · 57.5 KB
/
control_flow_graph.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
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* \file control_flow_graph.cc
* \brief Utility to deduce bound of expression
*/
#include "control_flow_graph.h"
#include <tvm/runtime/registry.h>
#include <tvm/tir/analysis.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/op.h>
#include <tvm/tir/stmt_functor.h>
#include <numeric>
#include <optional>
#include <queue>
#include <set>
#include <sstream>
#include <unordered_set>
#include "../../arith/conjunctive_normal_form.h"
#include "../../arith/constraint_extract.h"
#include "../../arith/ir_mutator_with_analyzer.h"
#include "../../arith/ir_visitor_with_analyzer.h"
#include "../../arith/narrow_predicate_expression.h"
#include "../../arith/unwrap_vector_expr.h"
namespace tvm {
namespace tir {
using namespace arith;
namespace {
bool HasBufferLoad(PrimExpr expr) {
struct Visitor : public ExprVisitor {
void VisitExpr_(const BufferLoadNode* node) override { found_buffer_load = true; }
bool found_buffer_load{false};
};
Visitor visitor;
visitor(expr);
return visitor.found_buffer_load;
}
Optional<PrimExpr> SubstituteParamValues(const Array<Var>& param_vars,
const Array<PrimExpr>& param_values,
const PrimExpr& expr) {
ICHECK_EQ(param_vars.size(), param_values.size())
<< "Expression was defined as having " << param_vars.size() << " parameters, but received "
<< param_values.size() << " arguments.";
Map<tir::Var, PrimExpr> var_map;
for (size_t i = 0; i < param_values.size(); i++) {
var_map.Set(param_vars[i], param_values[i]);
}
return Substitute(expr, var_map);
}
} // namespace
PrimExpr BufferTouch::BeforeLoopIteration() const {
PrimExpr loop_predicate = Bool(true);
for (auto it = loop_var_expressions.rbegin(); it != loop_var_expressions.rend(); it++) {
const Var& loop_var = it->first;
const PrimExpr& loop_expr = it->second;
loop_predicate = (loop_var <= loop_expr) || ((loop_var == loop_expr) && loop_predicate);
}
return loop_predicate;
}
PrimExpr BufferTouch::AtLoopIteration() const {
PrimExpr loop_predicate = Bool(true);
for (auto it = loop_var_expressions.rbegin(); it != loop_var_expressions.rend(); it++) {
const Var& loop_var = it->first;
const PrimExpr& loop_expr = it->second;
loop_predicate = (loop_var == loop_expr) && loop_predicate;
}
return loop_predicate;
}
PrimExpr BufferTouch::AfterLoopIteration() const {
PrimExpr loop_predicate = Bool(true);
for (auto it = loop_var_expressions.rbegin(); it != loop_var_expressions.rend(); it++) {
const Var& loop_var = it->first;
const PrimExpr& loop_expr = it->second;
loop_predicate = (loop_var >= loop_expr) || ((loop_var == loop_expr) && loop_predicate);
}
return loop_predicate;
}
bool BufferTouch::IsSubsetOf(const BufferTouch& other, Analyzer* analyzer) const {
if (this->buffer.same_as(other.buffer)) {
With<ConstraintContext> constraint(analyzer, predicate);
return analyzer->CanProve(other.predicate);
} else {
return false;
}
}
bool BufferTouch::IsDistinctFrom(const BufferTouch& other, Analyzer* analyzer) const {
if (this->buffer.same_as(other.buffer)) {
With<ConstraintContext> constraint(analyzer, predicate);
return analyzer->CanProve(!other.predicate);
} else {
return true;
}
}
std::ostream& operator<<(std::ostream& os, const BufferTouch& tp) {
auto touch_type = [&]() {
if (tp.touch_type == BufferTouch::AccessType::Read) {
return "read";
} else if (tp.touch_type == BufferTouch::AccessType::Write) {
return "write";
} else if (tp.touch_type == BufferTouch::AccessType::Assume) {
return "assume";
} else {
return "???";
}
}();
os << "BufferTouch(" << tp.buffer->name << ", " << touch_type << ", " << tp.predicate
<< ", value = " << tp.value << ")";
return os;
}
class BufferConstraintApply : public IRMutatorWithAnalyzer {
public:
using Parent = IRMutatorWithAnalyzer;
BufferConstraintApply(const Map<Buffer, Array<Var>>& axis_var_lookup,
const std::vector<BufferTouch>& knowns, Analyzer* analyzer)
: Parent(analyzer), axis_var_lookup_(axis_var_lookup), knowns_(knowns) {}
using Parent::VisitExpr_;
PrimExpr VisitExpr_(const BufferLoadNode* op) override {
for (const auto& known : knowns_) {
if (!op->buffer.same_as(known.buffer)) {
continue;
}
Optional<Var> lane_var = NullOpt;
IntImm num_lanes;
Array<PrimExpr> indices = op->indices.Map([&](const auto& index) {
if (index.dtype().lanes() == 1) {
return index;
} else {
ICHECK(!lane_var) << "Multiple indices found with non-scalar values";
lane_var = Var("lane", index.dtype().element_of());
num_lanes = IntImm(index.dtype().element_of(), index.dtype().lanes());
return UnwrapVectorExpr(index, lane_var.value());
}
});
auto axis_vars = axis_var_lookup_.at(op->buffer);
PrimExpr predicate = SubstituteParamValues(axis_vars, indices, known.predicate).value();
std::optional<With<ConstraintContext>> context;
if (lane_var.defined()) {
Var lanes = lane_var.value();
PrimExpr known = (IntImm(lanes.dtype(), 0) <= lanes) && (lanes < num_lanes);
context.emplace(analyzer_, known);
}
if (analyzer_->CanProve(predicate)) {
return SubstituteParamValues(axis_vars, op->indices, known.value).value();
}
}
return GetRef<PrimExpr>(op);
}
private:
const Map<Buffer, Array<Var>>& axis_var_lookup_;
const std::vector<BufferTouch>& knowns_;
};
/*! \brief Extract the control-flow graph
*
* Walk through a statement, populating the control-flow graph.
*/
class ControlFlowGraphBuilder final : public IRVisitorWithAnalyzer {
public:
static void Build(ControlFlowGraph* out, const Stmt& stmt) {
ControlFlowGraphBuilder extractor(out);
extractor.AppendControlBlock();
extractor(stmt);
}
private:
ControlFlowGraphBuilder(ControlFlowGraph* out) : out_(out) {}
using Parent = IRVisitorWithAnalyzer;
using Parent::VisitExpr_;
using Parent::VisitStmt_;
void VisitStmt(const Stmt& stmt) override {
// Update the lookup table to determine which control-flow block
// contains the start of the specified statement. This is used
// later to determine which set of known values should be used to
// simplify a statement.
out_->control_flow_lookup_[stmt.get()] = CurrentControlBlock();
Stmt prev_stmt = current_stmt_;
current_stmt_ = stmt;
Parent::VisitStmt(stmt);
current_stmt_ = prev_stmt;
}
void VisitStmt_(const EvaluateNode* op) override {
if (auto* call = op->value.as<CallNode>()) {
if (call->op.same_as(builtin::assume())) {
Assume(call->args[0], true);
return;
}
}
Parent::VisitStmt_(op);
}
void Assume(PrimExpr assumption, bool from_assume_statement) {
for (const auto& expr : ExtractConstraints(assumption, false)) {
AssumeConstraintComponent(expr, from_assume_statement);
}
}
void AssumeConstraintComponent(PrimExpr assumption, bool from_assume_statement) {
PrimExpr additional_predicate = Bool(true);
std::vector<PrimExpr> buffer_exprs;
for (const auto& expr : ExtractComponents(assumption)) {
auto side_effect = tir::SideEffect(expr);
if (side_effect <= tir::CallEffectKind::kPure) {
// Pulling out portions of the assumption that do not depend
// on a buffer value allows the following two forms to be
// treated identically.
//
// if i < 3: T.assume(buf[i] == value)
// T.assume(i>=3 or buf[i] == value)
additional_predicate = additional_predicate && logical_not(expr);
} else if (side_effect == tir::CallEffectKind::kReadState) {
buffer_exprs.push_back(expr);
} else {
LOG(FATAL) << "Assumption must be pure or read-only";
}
}
if (buffer_exprs.empty()) {
out_->non_buffer_assumptions_.push_back(!CurrentScopePredicate() || assumption);
return;
}
CHECK_EQ(buffer_exprs.size(), 1) << "T.assume must contain only a single buffer expression";
auto* as_equal_node = buffer_exprs[0].as<tir::EQNode>();
CHECK(as_equal_node || !from_assume_statement)
<< "T.assume buffer constraint must be of the form 'buffer[indices] == "
"value', but received "
<< assumption;
if (!as_equal_node) {
// This assumption is an inequality a data-dependent
// conditional. Not an error for this to occur, but also not
// something that is currently supported.
return;
}
tir::BufferLoad load;
PrimExpr value;
if (auto* as_load = as_equal_node->a.as<tir::BufferLoadNode>()) {
load = GetRef<tir::BufferLoad>(as_load);
value = as_equal_node->b;
} else if (auto* as_load = as_equal_node->b.as<tir::BufferLoadNode>()) {
load = GetRef<tir::BufferLoad>(as_load);
value = as_equal_node->a;
} else if (!from_assume_statement) {
return;
} else {
LOG(FATAL) << "T.assume buffer constraint must be of the form 'buffer[indices] == value'";
}
auto has_side_effect = tir::SideEffect(value) > tir::CallEffectKind::kPure;
CHECK(!has_side_effect || !from_assume_statement)
<< "Buffer value in constraint must be pure expression, but was " << value;
if (has_side_effect) {
return;
}
{
InternalConstraintContext context(this, additional_predicate);
VisitAccess(load, BufferTouch::AccessType::Assume, value);
}
// Appending a control block ensures that all control blocks have
// at most one statement that changes the known buffer contents.
auto prev_block = CurrentControlBlock();
auto new_block = AppendControlBlock();
MarkControlFlow(prev_block, new_block);
}
void VisitExpr_(const LetNode* op) override {
std::optional<BindLetVar> binding;
if (UsesLoopVar(op->value)) {
binding.emplace(this, op->var, op->value);
}
Parent::VisitExpr_(op);
}
void VisitStmt_(const LetStmtNode* op) override {
std::optional<BindLetVar> binding;
if (UsesLoopVar(op->value)) {
binding.emplace(this, op->var, op->value);
}
Parent::VisitStmt_(op);
}
void VisitExpr_(const BufferLoadNode* op) override {
Parent::VisitExpr_(op);
BufferLoad load = GetRef<BufferLoad>(op);
VisitAccess(load, BufferTouch::AccessType::Read, load);
}
void VisitStmt_(const BufferStoreNode* op) override {
Parent::VisitStmt_(op);
VisitAccess(GetRef<BufferStore>(op), BufferTouch::AccessType::Write, op->value);
// Appending a control block ensures that all control blocks have
// at most one statement that changes the buffer contents.
auto prev_block = CurrentControlBlock();
auto new_block = AppendControlBlock();
MarkControlFlow(prev_block, new_block);
}
void VisitStmt_(const ForNode* op) override {
out_->iterator_ranges_.Set(op->loop_var, Range::FromMinExtent(op->min, op->extent));
auto before_loop = CurrentControlBlock();
size_t loop_start = -1;
{
BindActiveLoopVar binding(this, op->loop_var, op->min, op->extent);
loop_start = AppendControlBlock();
Parent::VisitStmt_(op);
}
auto loop_end = CurrentControlBlock();
auto after_loop = AppendControlBlock();
PrimExpr max_iterator_value = analyzer_.Simplify(op->min + op->extent - 1);
{
auto [forward, backward] = MarkControlFlow(before_loop, loop_start);
backward.post_condition = (op->loop_var == op->min);
forward.var_remap = {{op->loop_var, op->min}};
}
{
auto [forward, backward] = MarkControlFlow(loop_end, after_loop);
backward.var_remap = {{op->loop_var, max_iterator_value}};
forward.post_condition = (op->loop_var == max_iterator_value);
}
{
auto [forward, backward] = MarkControlFlow(loop_end, loop_start);
backward.var_remap = {{op->loop_var, op->loop_var - 1}};
forward.var_remap = {{op->loop_var, op->loop_var + 1}};
backward.post_condition = (op->loop_var > op->min);
forward.post_condition = (op->loop_var < max_iterator_value);
}
}
void VisitStmt_(const IfThenElseNode* op) override {
this->VisitExpr(op->condition);
PrimExpr real_condition = ExtractRealCondition(op->condition);
auto before_branching = CurrentControlBlock();
auto branch_start = AppendControlBlock();
MarkControlFlow(before_branching, branch_start);
{
InternalConstraintContext context(this, real_condition);
auto then_start = AppendControlBlock();
if (context.assume.defined()) {
Assume(context.assume.value(), false);
}
auto [forward, backward] = MarkControlFlow(branch_start, then_start);
backward.post_condition = real_condition;
forward.post_condition = real_condition;
this->VisitStmt(op->then_case);
}
auto then_end = CurrentControlBlock();
auto negation = analyzer_.rewrite_simplify(!real_condition);
{
InternalConstraintContext context(this, negation);
auto else_start = AppendControlBlock();
if (context.assume.defined()) {
Assume(context.assume.value(), false);
}
auto [forward, backward] = MarkControlFlow(branch_start, else_start);
backward.post_condition = negation;
forward.post_condition = negation;
if (op->else_case.defined()) {
this->VisitStmt(op->else_case.value());
}
}
auto else_end = CurrentControlBlock();
auto after_branching = AppendControlBlock();
if (HasBufferLoad(real_condition)) {
// The buffer value may have changed during the body of the
// condition, so we can't provide it as a post-condition.
MarkControlFlow(then_end, after_branching);
MarkControlFlow(else_end, after_branching);
} else {
{
auto [forward, backward] = MarkControlFlow(then_end, after_branching);
backward.post_condition = real_condition;
forward.post_condition = real_condition;
}
{
auto [forward, backward] = MarkControlFlow(else_end, after_branching);
backward.post_condition = negation;
forward.post_condition = negation;
}
}
}
/*! \brief Internal utility, returns true if the expression depends
* on a loop iterator
*/
bool UsesLoopVar(const PrimExpr& expr) {
return UsesVar(expr, [&](const VarNode* expr_var) {
return loop_dependent_vars_.find(expr_var) != loop_dependent_vars_.end();
});
}
/*! \brief Record the interaction with the buffer.
*
* \param node The TIR node that accesses the buffer. Should be
* either a BufferLoad or BufferStore node.
*
* \param touch_type The type of buffer access being performed. A
* BufferStore should always use AccessType::Write. A BufferLoad
* may use either AccessType::Read or AccessType::Assume, depending
* on whether the BufferLoad occurs within `builtin::assume`.
*
* \param known_value_expr The value in the buffer following the access.
*/
template <typename BufferAccess>
void VisitAccess(const BufferAccess& node, BufferTouch::AccessType touch_type,
PrimExpr known_value_expr) {
auto& current_block = out_->control_flow_.back();
BufferTouch buffer_touch = current_block.MakeBufferTouch(out_, node->buffer, node->indices,
touch_type, known_value_expr);
current_block.touch_points.push_back(buffer_touch);
}
/*! \brief Return a predicate for having reached the current
* control-flow block
*
* For example, while inside an IfThenElse, will return the
* IfThenElse's condition.
*/
PrimExpr CurrentScopePredicate() const {
PrimExpr predicate = Bool(true);
for (const auto& condition : conditions_) {
predicate = predicate && condition;
}
return predicate;
}
/* \brief Add a new control block, returning its index */
size_t AppendControlBlock() {
size_t index = out_->control_flow_.size();
auto& block = out_->control_flow_.emplace_back();
block.active_loop_iterators = active_loop_iterators_;
block.let_bindings_using_loop = let_bindings_using_loop_;
block.scope_predicate = CurrentScopePredicate();
return index;
}
/* \brief The index of the current control block */
size_t CurrentControlBlock() { return out_->control_flow_.size() - 1; }
/* \brief Mark a possible control from one block to another
*
* \param from_block The block from which control leaves
*
* \param to_block The block to which control enters
*
* \param var_remap Variable replacements that should be made in
* known expression while traversing this edge. For example,
* replacing `i` with `i-1` when entering the next loop iteration,
* or replacing `i` with `n-1` when concluding a loop.
*/
std::pair<ControlFlowGraph::ControlFlowEdge&, ControlFlowGraph::ControlFlowEdge&> MarkControlFlow(
size_t from_block, size_t to_block) {
ICHECK_LE(from_block, out_->control_flow_.size());
ICHECK_LE(to_block, out_->control_flow_.size());
auto& forward = out_->control_flow_[from_block].successors.emplace_back(
ControlFlowGraph::ControlFlowEdge{to_block, {}, NullOpt});
auto& backward = out_->control_flow_[to_block].predecessors.emplace_back(
ControlFlowGraph::ControlFlowEdge{from_block, {}, NullOpt});
return {forward, backward};
}
// Internal utility, context manager for entering/leaving a scoped constraint
struct InternalConstraintContext {
InternalConstraintContext(ControlFlowGraphBuilder* self, PrimExpr constraint)
: self(self), analyzer_context(&self->analyzer_, constraint) {
old_num_constraints = self->conditions_.size();
auto side_effect = tir::SideEffect(constraint);
if (side_effect <= tir::CallEffectKind::kPure) {
self->conditions_.push_back(constraint);
} else if (side_effect <= tir::CallEffectKind::kReadState) {
assume = constraint;
}
new_num_constraints = self->conditions_.size();
}
~InternalConstraintContext() {
ICHECK_EQ(self->conditions_.size(), new_num_constraints)
<< "Internal error: Each condition should only be popped once.";
self->conditions_.erase(self->conditions_.begin() + old_num_constraints,
self->conditions_.end());
}
ControlFlowGraphBuilder* self{nullptr};
With<ConstraintContext> analyzer_context;
size_t old_num_constraints{0};
size_t new_num_constraints{0};
Optional<PrimExpr> assume{NullOpt};
// Disable default-generated copy/move assignment and constructors
InternalConstraintContext(const InternalConstraintContext&) = delete;
InternalConstraintContext& operator=(const InternalConstraintContext&) = delete;
InternalConstraintContext(InternalConstraintContext&&) = delete;
InternalConstraintContext& operator=(InternalConstraintContext&&) = delete;
};
// Internal utility, context manager for tracking a loop
struct BindActiveLoopVar {
BindActiveLoopVar(ControlFlowGraphBuilder* self, Var var, PrimExpr loop_min,
PrimExpr loop_extent)
: self(self), var(var) {
PrimExpr loop_max = loop_min + (loop_extent - 1);
auto loop_range = Range::FromMinExtent(loop_min, loop_extent);
self->active_loop_iterators_.push_back({var, loop_min, loop_max, loop_range});
self->loop_dependent_vars_.insert(var.get());
}
~BindActiveLoopVar() { self->active_loop_iterators_.pop_back(); }
ControlFlowGraphBuilder* self;
Var var;
// Disable default-generated copy/move assignment and constructors
BindActiveLoopVar(const BindActiveLoopVar&) = delete;
BindActiveLoopVar& operator=(const BindActiveLoopVar&) = delete;
BindActiveLoopVar(BindActiveLoopVar&&) = delete;
BindActiveLoopVar& operator=(BindActiveLoopVar&&) = delete;
};
// Internal utility, context manager for tracking a variable binding
struct BindLetVar {
BindLetVar(ControlFlowGraphBuilder* self, Var var, PrimExpr value) : self(self), var(var) {
self->let_bindings_using_loop_.Set(var, value);
self->loop_dependent_vars_.insert(var.get());
}
~BindLetVar() {
self->loop_dependent_vars_.erase(var.get());
self->let_bindings_using_loop_.erase(var);
}
ControlFlowGraphBuilder* self;
Var var;
// Disable default-generated copy/move assignment and constructors
BindLetVar(const BindLetVar&) = delete;
BindLetVar& operator=(const BindLetVar&) = delete;
BindLetVar(BindLetVar&&) = delete;
BindLetVar& operator=(BindLetVar&&) = delete;
};
struct LoopEntry {
Var loop_var;
PrimExpr loop_min;
PrimExpr loop_max;
Range loop_range;
};
// Track in order to know which Vars to write in terms of the buffer
// indices and substitute out of the predicate.
std::vector<ControlFlowGraph::ControlFlowBlock::LoopEntry> active_loop_iterators_;
// Track all loop iterators, along with values derived from loop iterators.
std::unordered_set<const VarNode*> loop_dependent_vars_;
// Any let binding that depends, directly or indirectly, on a loop
// binding. When making a predicate in terms of the buffer indices,
// these need to be substituted out.
// std::unordered_map<const VarNode*, PrimExpr> let_bindings_using_loop_;
Map<Var, PrimExpr> let_bindings_using_loop_;
// Track in order to know what conditions limit the buffer access
std::vector<PrimExpr> conditions_;
// Track in order to know what statement initiated the buffer access
Stmt current_stmt_;
// Output data structure
ControlFlowGraph* out_;
};
std::pair<BufferTouch, Map<Var, Range>> ControlFlowGraph::ControlFlowBlock::MakeBufferTouch(
const tir::Buffer& buf, Array<Var> index_variables, Array<PrimExpr> indices,
BufferTouch::AccessType touch_type, PrimExpr known_value_expr) const {
const auto& current_block = *this;
Analyzer local_analyzer;
Optional<Var> lane_var = NullOpt;
IntImm num_lanes;
Array<PrimExpr> index_expressions = indices.Map([&](const auto& index) {
if (index.dtype().lanes() == 1) {
return index;
} else {
ICHECK(!lane_var) << "Multiple indices found with non-scalar values";
lane_var = Var("lane", index.dtype().element_of());
num_lanes = IntImm(index.dtype().element_of(), index.dtype().lanes());
return UnwrapVectorExpr(index, lane_var.value());
}
});
Array<Var> loop_vars;
Map<Var, Range> loop_ranges;
for (const auto& loop_entry : current_block.active_loop_iterators) {
loop_vars.push_back(loop_entry.loop_var);
loop_ranges.Set(loop_entry.loop_var, loop_entry.loop_range);
}
// If the indices contain multiple lanes, treat the lane variable
// as an additional loop iterator to be solved for and substituted
// out.
if (lane_var) {
loop_vars.push_back(lane_var.value());
loop_ranges.Set(lane_var.value(), Range::FromMinExtent(0, num_lanes));
}
IntConstraintsTransform transform = [&]() {
ICHECK_EQ(index_variables.size(), index_expressions.size());
Array<PrimExpr> relations;
for (size_t i = 0; i < index_expressions.size(); i++) {
PrimExpr expr = index_expressions[i];
Var var = index_variables[i];
expr = Substitute(expr, current_block.let_bindings_using_loop);
relations.push_back(var == expr);
}
IntConstraints system(loop_vars, loop_ranges, relations);
return arith::SolveLinearEquations(system);
}();
Map<Var, PrimExpr> loop_var_to_axis_var = transform->src_to_dst;
Map<Var, Range> free_params = transform->dst->ranges;
PrimExpr transform_predicate =
std::accumulate(transform->dst->relations.begin(), transform->dst->relations.end(),
PrimExpr(Bool(true)), [](PrimExpr a, PrimExpr b) { return a && b; });
transform_predicate = SimplifyAsAndOfOrs(transform_predicate, &local_analyzer);
auto find_removable_params = [&]() -> Map<Var, PrimExpr> {
Map<Var, PrimExpr> removable_params;
// The arith::SolveLinearEquations is more general than the
// utilities in iter_affine_map.h, but can introduce free
// parameters that could later be determined with the known
// constraints. This step removes all such free parameters.
for (const auto& expr : ExtractConstraints(transform_predicate)) {
if (auto* as_equal = expr.as<EQNode>()) {
auto check_expr = [&](const PrimExpr& a, const PrimExpr& b) {
auto* var_ptr = a.as<VarNode>();
if (!var_ptr) {
return;
}
Var var = GetRef<Var>(var_ptr);
if (free_params.count(var) == 0) {
return;
}
bool uses_free_param =
UsesVar(b, [&](const VarNode* v) { return free_params.count(GetRef<Var>(v)) > 0; });
if (uses_free_param) {
return;
}
removable_params.Set(var, b);
};
check_expr(as_equal->a, as_equal->b);
check_expr(as_equal->b, as_equal->a);
}
}
// In addition, the arith::SolveLinearEquation can introduce
// free parameters with an extent of one. Filtering them out here
// avoids needing to track them through later simplifications.
for (const auto [var, range] : free_params) {
if (is_one(range->extent)) {
removable_params.Set(var, range->min);
}
}
return removable_params;
};
for (auto removable_params = find_removable_params(); removable_params.size() > 0;
removable_params = find_removable_params()) {
auto update = [&](const PrimExpr& expr) {
return local_analyzer.Simplify(Substitute(expr, removable_params));
};
Map<Var, PrimExpr> new_map;
for (const auto [loop_var, expr] : loop_var_to_axis_var) {
static_cast<void>(expr); // gcc 7.x bug, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81767
new_map.Set(loop_var, update(expr));
}
loop_var_to_axis_var = new_map;
transform_predicate = update(transform_predicate);
for (const auto [var, expr] : removable_params) {
static_cast<void>(expr); // gcc 7.x bug, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81767
free_params.erase(var);
}
}
// Normalization function, applied to both the predicate and the
// known value. Converts from an expression in terms of loop
// iterators to an expression in terms of buffer indices.
auto normalize_expr = [&](PrimExpr expr) -> PrimExpr {
expr = Substitute(expr, current_block.let_bindings_using_loop);
if (lane_var) {
expr = UnwrapVectorExpr(expr, lane_var.value());
}
expr = Substitute(expr, loop_var_to_axis_var);
return expr;
};
// Collect the current loop variables, along with an expression for
// the loop variables in terms of the buffer axis variables. This
// is used during forward/backward propagation to generate predicate
// tracking whether a loop iteration has been reached.
std::vector<std::pair<Var, PrimExpr>> loop_var_expressions;
for (const auto& entry : current_block.active_loop_iterators) {
auto expr_it = loop_var_to_axis_var.find(entry.loop_var);
ICHECK(expr_it != loop_var_to_axis_var.end());
loop_var_expressions.push_back({entry.loop_var, (*expr_it).second});
}
// The full predicate is composed of the values required to reach
// the scope of the BufferStore or builtin::assume(), any bounds
// implied by solving for the axis variables, and any additional
// statements resulting from unpacking the expression contained in
// builtin::assume().
PrimExpr scope_predicate = normalize_expr(current_block.scope_predicate);
transform_predicate = normalize_expr(transform_predicate);
known_value_expr = local_analyzer.Simplify(normalize_expr(known_value_expr));
// Deliberately use an analyzer without scope-based information,
// to avoid simplifying `scope_predicate` to True.
PrimExpr predicate_expr = local_analyzer.Simplify(transform_predicate && scope_predicate);
BufferTouch buffer_touch = {buf, predicate_expr, known_value_expr, loop_var_expressions,
touch_type};
return {buffer_touch, free_params};
}
BufferTouch ControlFlowGraph::ControlFlowBlock::MakeBufferTouch(ControlFlowGraph* graph,
const tir::Buffer& buf,
const Array<PrimExpr>& indices,
BufferTouch::AccessType touch_type,
PrimExpr known_value_expr) const {
ICHECK(graph);
auto [buffer_touch, free_params] = MakeBufferTouch(buf, graph->GetIndexVariables(buf, indices),
indices, touch_type, known_value_expr);
for (const auto& pair : free_params) {
graph->free_predicate_parameters_.Set(pair.first, pair.second);
}
return buffer_touch;
}
ControlFlowGraph::ControlFlowGraph(const tir::Stmt& stmt, size_t max_revisits) {
ControlFlowGraphBuilder::Build(this, stmt);
ForwardPropagateKnownValues(max_revisits);
BackwardPropagateUnusedValues(max_revisits);
}
std::ostream& operator<<(std::ostream& os, const ControlFlowGraph::ControlFlowEdge& edge) {
os << edge.index;
if (edge.var_remap.size()) {
os << " with remap " << edge.var_remap;
}
if (edge.post_condition) {
os << " with postcondition " << edge.post_condition;
}
return os;
}
std::ostream& operator<<(std::ostream& os, const ControlFlowGraph::ControlFlowBlock& block) {
os << "Predecessors: [";
for (size_t i = 0; i < block.predecessors.size(); i++) {
if (i) {
os << ", ";
}
os << block.predecessors[i];
}
os << "]\n";
os << "Active loop iterators: [";
for (size_t i = 0; i < block.active_loop_iterators.size(); i++) {
if (i) {
os << ", ";
}
os << block.active_loop_iterators[i].loop_var;
}
os << "]\n";
os << "Before block knowns: " << block.known_at_block_start << "\n";
os << "Before block unused: " << block.unused_at_block_start << "\n";
for (size_t i = 0; i < block.touch_points.size(); i++) {
os << "Touch[" << i << "] = " << block.touch_points[i] << "\n";
}
os << "After block: " << block.known_at_block_end << "\n";
os << "After block unused: " << block.unused_at_block_end << "\n";
os << "Successors: [";
for (size_t i = 0; i < block.successors.size(); i++) {
if (i) {
os << ", ";
}
os << block.successors[i];
}
os << "]";
return os;
}
std::ostream& operator<<(std::ostream& os, const ControlFlowGraph& pattern) {
os << "Touch pattern contains " << pattern.control_flow_.size() << " control blocks."
<< (pattern.control_flow_.size() ? "\n" : "");
for (size_t i = 0; i < pattern.control_flow_.size(); i++) {
os << "\t"
<< "ControlBlock[" << i << "] = " << pattern.control_flow_[i] << "\n";
}
return os;
}
bool BufferTouch::IsEquivalentTo(const BufferTouch& other, Analyzer* analyzer) const {
// Constraints must apply to the same buffer to be equivalent
if (!buffer.same_as(other.buffer) || touch_type != other.touch_type) {
return false;
}
ExprDeepEqual deep_equal;
auto implies = [&](const PrimExpr& a, const PrimExpr& b) -> bool {
With<ConstraintContext> context(analyzer, a);
return analyzer->CanProve(b);
};
// Predicates must be equivalent expressions, or must both be undefined
bool equivalent_predicates =
deep_equal(predicate, other.predicate) ||
(implies(predicate, other.predicate) && implies(other.predicate, predicate));
if (!equivalent_predicates) {
return false;
}
// The known value must be equal
if (!deep_equal(value, other.value) && !analyzer->CanProveEqual(value, other.value)) {
return false;
}
return true;
}
std::ostream& operator<<(std::ostream& os, const BufferState& state) {
for (size_t i = 0; i < state.constraints.size(); i++) {
os << "constraints[" << i << "] = " << state.constraints[i]
<< (i + 1 == state.constraints.size() ? "" : "\n");
}
return os;
}
PrimExpr BufferState::SubstituteKnownBufferValues(
PrimExpr expr, const Map<tir::Buffer, Array<tir::Var>>& axis_var_lookup,
Analyzer* analyzer) const {
BufferConstraintApply mutator(axis_var_lookup, constraints, analyzer);
return mutator(std::move(expr));
}
void BufferState::AddCondition(const PrimExpr& condition) {
for (auto& constraint : constraints) {
constraint.predicate = constraint.predicate && condition;
}
}
void BufferState::Substitute(const Map<Var, PrimExpr>& var_remap, Analyzer* analyzer) {
if (var_remap.size()) {
for (auto& prior : constraints) {
PrimExpr updated = tvm::tir::Substitute(prior.predicate, var_remap);
if (!updated.same_as(prior.predicate)) {
prior.predicate = SimplifyAsAndOfOrs(updated, analyzer);
}
}
}
}
void BufferState::Simplify(Analyzer* analyzer) {
for (auto& constraint : constraints) {
constraint.predicate = SimplifyAsAndOfOrs(constraint.predicate, analyzer);
}
}
void BufferState::Union(const BufferState& b, Analyzer* analyzer) {
for (const auto& b_constraint : b.constraints) {
bool used = false;
for (auto& a_constraint : constraints) {
if (a_constraint.buffer.same_as(b_constraint.buffer) &&
analyzer->CanProveEqual(a_constraint.value, b_constraint.value)) {
a_constraint.predicate =
SimplifyAsAndOfOrs(a_constraint.predicate || b_constraint.predicate, analyzer);
used = true;
break;
}
}
if (!used) {
constraints.push_back(b_constraint);
}
}
}
void BufferState::Intersection(const BufferState& b, Analyzer* analyzer) {
// For a constraint to be in the output, it must be present in both
// inputs.
std::vector<BufferTouch> new_constraints;
for (const auto& ai : constraints) {
for (const auto& bi : b.constraints) {
if (ai.buffer.same_as(bi.buffer)) {
PrimExpr predicate = SimplifyAsAndOfOrs(ai.predicate && bi.predicate, analyzer);
if (!is_zero(predicate)) {
With<ConstraintContext> context(analyzer, predicate);
PrimExpr known_value_a = ai.value;
PrimExpr known_value_b = bi.value;
bool is_consistent = analyzer->CanProveEqual(known_value_a, known_value_b);
if (is_consistent) {
new_constraints.push_back({ai.buffer, predicate, known_value_a});
}
}
}
}
}
constraints = std::move(new_constraints);
}