-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathMicrokernelInvariantCodeMotion.cpp
More file actions
430 lines (385 loc) · 16.1 KB
/
MicrokernelInvariantCodeMotion.cpp
File metadata and controls
430 lines (385 loc) · 16.1 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
//===-- MicrokernelInvariantCodeMotion.cpp - Hoist invariance ---*- C++ -*-===//
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Linalg/Utils/Utils.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Rewrite/FrozenRewritePatternSet.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include <sstream>
#include <utility>
#include "gc/Transforms/Microkernel/BrgemmRuntimeUtils.h"
#include "gc/Transforms/Microkernel/MicrokernelPasses.h"
#include "gc/Transforms/Utils/ValueUtils.h"
#include "oneapi/dnnl/dnnl_types.h"
namespace mlir::microkernel {
#define GEN_PASS_DEF_MICROKERNELINVARIANTCODEMOTION
#include "gc/Transforms/Microkernel/MicrokernelPasses.h.inc"
#define DEBUG_TYPE "microkernel-invariant-code-motion"
enum BrgemmCallType { INAPPLICABLE = -1, DISPATCH, TILECFG, TILERELEASE };
static bool isParallelLoop(Operation *op) {
return llvm::isa<scf::ForallOp>(op) || llvm::isa<scf::ParallelOp>(op) ||
llvm::isa<omp::ParallelOp>(op) || llvm::isa<omp::WsloopOp>(op);
}
static bool isConcernedCF(Operation *op) {
return llvm::isa<scf::ForOp>(op) || llvm::isa<scf::WhileOp>(op) ||
llvm::isa<scf::IfOp>(op) || llvm::isa<scf::IndexSwitchOp>(op);
}
static BrgemmCallType getBrgemmCallType(Operation *op) {
if (!llvm::isa<func::CallOp>(op)) {
return BrgemmCallType::INAPPLICABLE;
}
auto callOp = dyn_cast<func::CallOp>(op);
auto calleeName = callOp.getCalleeAttr().getAttr().getValue();
if (calleeName == DNNL_BRGEMM_DISPATCH_NAME)
return BrgemmCallType::DISPATCH;
if (calleeName == DNNL_BRGEMM_TILECFG_NAME)
return BrgemmCallType::TILECFG;
if (calleeName == DNNL_BRGEMM_TILERELEASE_NAME)
return BrgemmCallType::TILERELEASE;
return BrgemmCallType::INAPPLICABLE;
}
// Tree node of structure info tree, each node represents an Op
// This tree contains only concerned Ops
struct BrgemmContextStructInfo {
// Basic structure info retrieved by first walk
Operation *contextRoot; // Could be parallel loop or func
Operation *self, *parent;
DenseSet<Operation *> child;
SmallVector<bool, 3> containBrgemmCallType;
// Rewrite-time info retrieved by analysing basic structure info
union {
Operation *maxInvariantScope; // Used by BrgemmCallOps for hoisting
bool hasTilereleased; // Used by other Ops as hoisting scopes to
// dedup tilerelease injection
};
BrgemmContextStructInfo() {
contextRoot = nullptr;
self = nullptr;
parent = nullptr;
containBrgemmCallType = {false, false, false};
maxInvariantScope = nullptr;
}
};
using OpStructInfoMap = DenseMap<Operation *, BrgemmContextStructInfo>;
class BrgemmTilecfgRewriter : public OpRewritePattern<func::CallOp> {
private:
OpStructInfoMap &structInfo;
public:
using OpRewritePattern<func::CallOp>::OpRewritePattern;
BrgemmTilecfgRewriter(MLIRContext *context, OpStructInfoMap &si)
: OpRewritePattern(context), structInfo{si} {}
LogicalResult matchAndRewrite(func::CallOp op,
PatternRewriter &rewriter) const final {
ModuleOp module = op->template getParentOfType<ModuleOp>();
StringAttr callee = op.getCalleeAttr().getAttr();
if (!module.lookupSymbol(callee))
return rewriter.notifyMatchFailure(op,
"Invalid CallOp to unknown callee");
if (callee !=
StringAttr::get(rewriter.getContext(), DNNL_BRGEMM_TILECFG_NAME))
return rewriter.notifyMatchFailure(op, "Not call to BRGEMM tilecfg");
auto opInfoIter = structInfo.find(op);
if (opInfoIter == structInfo.end()) {
return rewriter.notifyMatchFailure(op, "Cannot find structInfo for Op");
}
auto &opStructInfo = opInfoIter->second;
// Don't hoist if max invariant scope is itself to reduce
// unnecessary movement
if (opStructInfo.maxInvariantScope == op) {
return rewriter.notifyMatchFailure(op, "No need to hoist");
}
rewriter.moveOpBefore(op, opStructInfo.maxInvariantScope);
// Avoid being hoisted again
opStructInfo.maxInvariantScope = op;
return success();
}
};
static void markScopeAsReleased(OpStructInfoMap &structInfo, Operation *op) {
auto iter = structInfo.find(op);
assert(iter != structInfo.end());
// Don't mark BrgemmCallOps
if (getBrgemmCallType(op) != BrgemmCallType::INAPPLICABLE)
return;
iter->second.hasTilereleased = true;
for (auto ch : iter->second.child) {
markScopeAsReleased(structInfo, ch);
}
}
class BrgemmTilereleaseRewriter : public OpRewritePattern<func::CallOp> {
private:
OpStructInfoMap &structInfo;
public:
using OpRewritePattern<func::CallOp>::OpRewritePattern;
BrgemmTilereleaseRewriter(MLIRContext *context, OpStructInfoMap &si)
: OpRewritePattern(context), structInfo{si} {}
LogicalResult matchAndRewrite(func::CallOp op,
PatternRewriter &rewriter) const final {
ModuleOp module = op->template getParentOfType<ModuleOp>();
StringAttr callee = op.getCalleeAttr().getAttr();
if (!module.lookupSymbol(callee))
return rewriter.notifyMatchFailure(op,
"Invalid CallOp to unknown callee");
if (callee !=
StringAttr::get(rewriter.getContext(), DNNL_BRGEMM_TILERELEASE_NAME))
return rewriter.notifyMatchFailure(op, "Not call to BRGEMM tilerelease");
auto opInfoIter = structInfo.find(op);
if (opInfoIter == structInfo.end()) {
return rewriter.notifyMatchFailure(op, "Cannot find structInfo for Op");
}
auto &opStructInfo = opInfoIter->second;
auto targetInfoIter = structInfo.find(opStructInfo.maxInvariantScope);
assert(opStructInfo.maxInvariantScope);
// Don't hoist if max invariant scope is itself to reduce
// unnecessary movement
if (opStructInfo.maxInvariantScope == op) {
return rewriter.notifyMatchFailure(op, "No need to hoist");
}
assert(targetInfoIter != structInfo.end());
// move last tilerelease to end of contextRoot, and remove all
// others
if (targetInfoIter->second.hasTilereleased) {
rewriter.eraseOp(op);
} else {
// rewriter.moveOpBefore(op, block, enditer);
rewriter.moveOpAfter(op, opStructInfo.maxInvariantScope);
// Mark all sub scope as released to avoid duplicate Tilerelease
markScopeAsReleased(structInfo, opStructInfo.maxInvariantScope);
// Avoid being hoisted again
opStructInfo.maxInvariantScope = op;
}
return success();
}
};
class MicrokernelInvariantCodeMotion
: public impl::MicrokernelInvariantCodeMotionBase<
MicrokernelInvariantCodeMotion> {
private:
// This helper create structInfo tree node along the path from input Op(as
// leaf) to contextRoot(FuncOp or any parallel Op) on demand;
// This tree only contains concerned Ops, including BrgemmCall Ops, parallel
// ops and related SCF Ops etc.;
// Input Op should be a BrgemmCall Op or the op
// depent by BrgemmTilecfg/BrgemmRelease
BrgemmContextStructInfo getOrCreateBrgemmContext(OpStructInfoMap &structInfo,
Operation *op) {
auto resIter = structInfo.find(op);
if (resIter != structInfo.end()) {
return resIter->second;
}
SmallVector<BrgemmContextStructInfo *, 5> createdInfo;
Operation *contextRootForCreatedInfo = nullptr;
auto doCreateStructInfo = [&](Operation *child, Operation *op) {
BrgemmContextStructInfo info;
info.self = op;
if (child) {
auto iter = structInfo.find(child);
assert(iter != structInfo.end());
iter->second.parent = op;
info.child.insert(child);
}
structInfo.insert(std::make_pair(op, std::move(info)));
auto iter = structInfo.find(op);
createdInfo.push_back(&iter->second);
return &iter->second;
};
// Create info for input Op as leaf
auto brgemmInfo = doCreateStructInfo(nullptr, op);
auto callType = getBrgemmCallType(op);
if (callType != BrgemmCallType::INAPPLICABLE) {
brgemmInfo->containBrgemmCallType[callType] = true;
}
auto last = op;
auto current = op->getParentOp();
// Traverse up the IR tree, creating structInfo for each concerned Op
while (current) {
bool isParaLoop = isParallelLoop(current);
bool isCCF = isConcernedCF(current);
if (!llvm::isa<func::FuncOp>(current) && !isParaLoop && !isCCF) {
// Only care about selected Ops
current = current->getParentOp();
continue;
}
auto iter = structInfo.find(current);
if (iter != structInfo.end()) {
// StructInfo exists for current Op, then we don't need to create info
// anymore as all ancestors have been created
// But we still need to propagate containBrgemmCallType if we are
// dealing with BrgemmCall Ops
if (last) {
auto lastIter = structInfo.find(last);
assert(lastIter != structInfo.end());
lastIter->second.parent = current;
iter->second.child.insert(last);
// Invalidate last as we don't create new info anymore
last = nullptr;
}
if (callType != BrgemmCallType::INAPPLICABLE) {
// Propagate containCallType if needed
iter->second.containBrgemmCallType[callType] = true;
} else
break;
} else {
// StructInfo not exist, then create one for current Op and keep
// Traversing up
auto created = doCreateStructInfo(last, current);
if (callType != BrgemmCallType::INAPPLICABLE) {
created->containBrgemmCallType[callType] = true;
}
last = current;
}
if (llvm::isa<func::FuncOp>(current) || isParaLoop) {
// Encounter `contextRoot`, then record and terminate traversing
contextRootForCreatedInfo = current;
break;
}
current = current->getParentOp();
}
// Assign `contextRoot` for newly created structInfo
if (contextRootForCreatedInfo) {
for (auto info : createdInfo)
info->contextRoot = contextRootForCreatedInfo;
}
resIter = structInfo.find(op);
assert(resIter != structInfo.end());
return resIter->second;
}
// This helper expand invariant scope according to two function:
// 1. controlFlowAllow: Whether we can hoist the BrgemmCallOp out of the scope
// of current Op; For example, we won't move TILECFG out of an IfOp as it
// contains underministic control flow.
// 2. peerAllow: Whether we can hoist the BrgemmCallOp out of the scope of
// current Op without violating other peer BrgemmCallOp in the same level; For
// example, one scf.ForOp contains two TILECFG in the same level, then we
// cannot hoist any of them.
// NOLINTBEGIN(performance-unnecessary-value-param)
void expandInvariantScopeWithCond(
OpStructInfoMap &structInfo, Operation *op,
std::function<bool(Operation *)> controlFlowAllow,
std::function<bool(Operation *, const OpStructInfoMap &, Operation *,
const DenseSet<Operation *> &)>
peerAllow) {
// NOLINTEND(performance-unnecessary-value-param)
auto opIter = structInfo.find(op);
assert(opIter != structInfo.end());
auto contextRoot = opIter->second.contextRoot;
auto current = op;
auto currIter = opIter;
auto parent = opIter->second.parent;
while (parent != contextRoot) {
auto parentIter = structInfo.find(parent);
assert(parentIter != structInfo.end());
// Verify whether we can expand the scope to direct parent
bool isControlFlowAllow = controlFlowAllow(parent);
bool isPeerAllow =
peerAllow(op, structInfo, current, parentIter->second.child);
if (!isControlFlowAllow || !isPeerAllow) {
break;
}
current = parent;
currIter = parentIter;
parent = parentIter->second.parent;
}
opIter->second.maxInvariantScope = current;
}
void expandInvariantScope(OpStructInfoMap &structInfo, Operation *op) {
BrgemmCallType brgemmCallType = getBrgemmCallType(op);
assert(brgemmCallType == BrgemmCallType::TILECFG ||
brgemmCallType == BrgemmCallType::TILERELEASE);
if (brgemmCallType == BrgemmCallType::TILECFG) {
expandInvariantScopeWithCond(
structInfo, op,
[](Operation *op) -> bool {
return !llvm::isa<scf::IfOp>(op) &&
!llvm::isa<scf::IndexSwitchOp>(op);
},
[](Operation *self, const OpStructInfoMap &structInfo,
Operation *current, const DenseSet<Operation *> &peers) -> bool {
for (auto peer : peers) {
if (peer == current)
continue;
if (peer == self->getOperand(0).getDefiningOp()) {
// Don't break operand domination
return false;
}
const auto iter = structInfo.find(peer);
assert(iter != structInfo.end());
const auto &containType = iter->second.containBrgemmCallType;
if (containType[BrgemmCallType::DISPATCH] ||
containType[BrgemmCallType::TILECFG]) {
return false;
}
}
return true;
});
} else { // brgemmCallType == BrgemmCallType::TILERELEASE
expandInvariantScopeWithCond(
structInfo, op,
[](Operation *op) -> bool {
return !llvm::isa<scf::IfOp, scf::IndexSwitchOp>(op);
},
[](Operation *self, const OpStructInfoMap &structInfo,
Operation *current,
const DenseSet<Operation *> &peers) -> bool { return true; });
}
}
LogicalResult collectBrgemmContextStructInfo(OpStructInfoMap &structInfo) {
// First walk to collect basic structure
getOperation()->walk<WalkOrder::PreOrder>(
[this, &structInfo](Operation *op) {
BrgemmCallType brgemmCallType = getBrgemmCallType(op);
if (brgemmCallType == BrgemmCallType::INAPPLICABLE) {
return;
}
// Construct the structInfo tree lazily upon encountering BrgemmCall
// Op
auto info = getOrCreateBrgemmContext(structInfo, op);
structInfo.insert(std::make_pair(op, std::move(info)));
if (brgemmCallType == BrgemmCallType::TILECFG) {
// Also contruct tree node for the input of BrgemmTilecfg for
// dependency check in `expandInvariantScope`
auto dependOp = op->getOperand(0).getDefiningOp();
auto dependInfo = getOrCreateBrgemmContext(structInfo, dependOp);
structInfo.insert(std::make_pair(dependOp, std::move(dependInfo)));
}
});
// Second walk to analyse hoist related info
getOperation()->walk<WalkOrder::PreOrder>(
[this, &structInfo](Operation *op) {
BrgemmCallType brgemmCallType = getBrgemmCallType(op);
if (brgemmCallType != BrgemmCallType::TILECFG &&
brgemmCallType != BrgemmCallType::TILERELEASE) {
return;
}
// find the maximal invariant scope for hoisting
expandInvariantScope(structInfo, op);
});
return success();
}
public:
using impl::MicrokernelInvariantCodeMotionBase<
MicrokernelInvariantCodeMotion>::MicrokernelInvariantCodeMotionBase;
void runOnOperation() final {
OpStructInfoMap structInfo;
if (failed(collectBrgemmContextStructInfo(structInfo))) {
signalPassFailure();
}
RewritePatternSet patterns(&getContext());
patterns.add<BrgemmTilecfgRewriter>(&getContext(), structInfo);
patterns.add<BrgemmTilereleaseRewriter>(&getContext(), structInfo);
FrozenRewritePatternSet patternSet(std::move(patterns));
// Ignore newly created Ops
GreedyRewriteConfig config;
config.strictMode = GreedyRewriteStrictness::ExistingOps;
if (failed(applyPatternsGreedily(getOperation(), patternSet, config))) {
signalPassFailure();
}
}
};
} // namespace mlir::microkernel