forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLiftArrayAlloc.cpp
More file actions
317 lines (286 loc) · 11.3 KB
/
LiftArrayAlloc.cpp
File metadata and controls
317 lines (286 loc) · 11.3 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
/*******************************************************************************
* Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates. *
* All rights reserved. *
* *
* This source code and the accompanying materials are made available under *
* the terms of the Apache License 2.0 which accompanies this distribution. *
******************************************************************************/
#include "PassDetails.h"
#include "cudaq/Optimizer/Builder/Intrinsics.h"
#include "cudaq/Optimizer/Dialect/CC/CCOps.h"
#include "cudaq/Optimizer/Dialect/Quake/QuakeOps.h"
#include "cudaq/Optimizer/Transforms/Passes.h"
#include "mlir/Dialect/Complex/IR/Complex.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Dominance.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
namespace cudaq::opt {
#define GEN_PASS_DEF_LIFTARRAYALLOC
#include "cudaq/Optimizer/Transforms/Passes.h.inc"
} // namespace cudaq::opt
#define DEBUG_TYPE "lift-array-alloc"
using namespace mlir;
namespace {
class AllocaPattern : public OpRewritePattern<cudaq::cc::AllocaOp> {
public:
explicit AllocaPattern(MLIRContext *ctx, DominanceInfo &di, StringRef fn)
: OpRewritePattern(ctx), dom(di), funcName(fn) {}
LogicalResult matchAndRewrite(cudaq::cc::AllocaOp alloc,
PatternRewriter &rewriter) const override {
SmallVector<Operation *> stores;
if (!isGoodCandidate(alloc, stores, dom))
return failure();
LLVM_DEBUG(llvm::dbgs() << "Candidate was found\n");
auto allocTy = alloc.getElementType();
auto arrTy = cast<cudaq::cc::ArrayType>(allocTy);
auto eleTy = arrTy.getElementType();
SmallVector<Attribute> values;
// Every element of `stores` must be a cc::StoreOp with a ConstantOp as the
// value argument. Build the array attr to attach to a cc.const_array.
for (auto *op : stores) {
auto store = cast<cudaq::cc::StoreOp>(op);
auto *valOp = store.getValue().getDefiningOp();
if (auto con = dyn_cast<arith::ConstantOp>(valOp))
values.push_back(con.getValueAttr());
else if (auto con = dyn_cast<complex::ConstantOp>(valOp))
values.push_back(con.getValueAttr());
else
return alloc.emitOpError("could not fold");
}
// Create the cc.const_array.
auto valuesAttr = rewriter.getArrayAttr(values);
auto loc = alloc.getLoc();
Value conArr =
rewriter.create<cudaq::cc::ConstantArrayOp>(loc, arrTy, valuesAttr);
assert(conArr && "must have created the constant array");
LLVM_DEBUG(llvm::dbgs() << "constant array is:\n" << conArr << '\n');
bool cannotEraseAlloc = false;
// Collect all the stores, casts, and compute_ptr to be erased safely and in
// topological order.
SmallVector<Operation *> opsToErase;
auto insertOpToErase = [&](Operation *op) {
auto iter = std::find(opsToErase.begin(), opsToErase.end(), op);
if (iter == opsToErase.end())
opsToErase.push_back(op);
};
// Rewalk all the uses of alloc, u, which must be cc.cast or cc.compute_ptr.
// For each u remove a store and replace a load with a cc.extract_value.
for (auto *user : alloc->getUsers()) {
if (!user)
continue;
std::int32_t offset = 0;
if (auto cptr = dyn_cast<cudaq::cc::ComputePtrOp>(user))
offset = cptr.getRawConstantIndices()[0];
bool isLive = false;
if (!isa<cudaq::cc::CastOp, cudaq::cc::ComputePtrOp>(user)) {
cannotEraseAlloc = isLive = true;
} else {
for (auto *useuser : user->getUsers()) {
if (!useuser)
continue;
if (auto load = dyn_cast<cudaq::cc::LoadOp>(useuser)) {
rewriter.setInsertionPointAfter(useuser);
LLVM_DEBUG(llvm::dbgs() << "replaced load\n");
auto extractValue = rewriter.create<cudaq::cc::ExtractValueOp>(
loc, eleTy, conArr,
ArrayRef<cudaq::cc::ExtractValueArg>{offset});
rewriter.replaceAllUsesWith(load, extractValue);
insertOpToErase(load);
continue;
}
if (isa<cudaq::cc::StoreOp>(useuser)) {
insertOpToErase(useuser);
continue;
}
LLVM_DEBUG(llvm::dbgs() << "alloc is live\n");
cannotEraseAlloc = isLive = true;
}
}
if (!isLive)
insertOpToErase(user);
}
for (auto *e : opsToErase)
rewriter.eraseOp(e);
if (cannotEraseAlloc) {
rewriter.setInsertionPointAfter(alloc);
rewriter.create<cudaq::cc::StoreOp>(loc, conArr, alloc);
return success();
}
rewriter.eraseOp(alloc);
return success();
}
// Determine if \p alloc is a legit candidate for promotion to a constant
// array value. \p scoreboard is a vector of store operations. Each element of
// the allocated array must be written to exactly 1 time, and the scoreboard
// is used to track these stores. \p dom is the dominance info for this
// function (to ensure the stores happen before uses).
static bool isGoodCandidate(cudaq::cc::AllocaOp alloc,
SmallVectorImpl<Operation *> &scoreboard,
DominanceInfo &dom) {
LLVM_DEBUG(llvm::dbgs() << "checking candidate\n");
if (alloc.getSeqSize())
return false;
auto arrTy = dyn_cast<cudaq::cc::ArrayType>(alloc.getElementType());
if (!arrTy || arrTy.isUnknownSize())
return false;
auto arrEleTy = arrTy.getElementType();
if (!isa<IntegerType, FloatType, ComplexType>(arrEleTy))
return false;
// There must be at least `size` uses to initialize the entire array.
auto size = arrTy.getSize();
if (std::distance(alloc->getUses().begin(), alloc->getUses().end()) < size)
return false;
// Keep a scoreboard for every element in the array. Every element *must* be
// stored to with a constant exactly one time.
scoreboard.resize(size);
for (int i = 0; i < size; i++)
scoreboard[i] = nullptr;
SmallVector<Operation *> toGlobalUses;
SmallVector<SmallPtrSet<Operation *, 2>> loadSets(size);
SmallVector<SmallPtrSet<Operation *, 2>> storeSets(size);
auto getWriteOp = [&](auto op, std::int32_t index) -> Operation * {
Operation *theStore = nullptr;
for (auto &use : op->getUses()) {
Operation *u = use.getOwner();
if (!u)
return nullptr;
if (auto store = dyn_cast<cudaq::cc::StoreOp>(u)) {
storeSets[index].insert(u);
if (op.getOperation() == store.getPtrvalue().getDefiningOp() &&
isa_and_present<arith::ConstantOp, complex::ConstantOp>(
store.getValue().getDefiningOp())) {
if (theStore) {
LLVM_DEBUG(llvm::dbgs()
<< "more than 1 store to element of array\n");
return nullptr;
}
theStore = u;
}
continue;
}
if (isa<quake::InitializeStateOp>(u)) {
toGlobalUses.push_back(u);
continue;
}
if (isa<cudaq::cc::LoadOp>(u)) {
loadSets[index].insert(u);
continue;
}
return nullptr;
}
return theStore;
};
auto unsizedArrTy = cudaq::cc::ArrayType::get(arrEleTy);
auto ptrUnsizedArrTy = cudaq::cc::PointerType::get(unsizedArrTy);
auto ptrArrEleTy = cudaq::cc::PointerType::get(arrEleTy);
for (auto &use : alloc->getUses()) {
// All uses *must* be a degenerate cc.cast, cc.compute_ptr, or
// cc.init_state.
auto *op = use.getOwner();
if (!op) {
LLVM_DEBUG(llvm::dbgs() << "use was not an op\n");
return false;
}
if (auto cptr = dyn_cast<cudaq::cc::ComputePtrOp>(op)) {
if (auto index = cptr.getConstantIndex(0))
if (auto w = getWriteOp(cptr, *index))
if (!scoreboard[*index]) {
scoreboard[*index] = w;
continue;
}
return false;
}
if (auto cast = dyn_cast<cudaq::cc::CastOp>(op)) {
// Process casts that are used in store ops.
if (cast.getType() == ptrArrEleTy) {
if (auto w = getWriteOp(cast, 0))
if (!scoreboard[0]) {
scoreboard[0] = w;
continue;
}
return false;
}
// Process casts that are used in quake.init_state.
if (cast.getType() == ptrUnsizedArrTy) {
if (cast->hasOneUse()) {
auto &use = *cast->getUses().begin();
Operation *u = use.getOwner();
if (isa_and_present<quake::InitializeStateOp>(u)) {
toGlobalUses.push_back(op);
continue;
}
}
return false;
}
LLVM_DEBUG(llvm::dbgs() << "unexpected cast: " << *op << '\n');
toGlobalUses.push_back(op);
continue;
}
if (isa<quake::InitializeStateOp>(op)) {
toGlobalUses.push_back(op);
continue;
}
LLVM_DEBUG(llvm::dbgs() << "unexpected use: " << *op << '\n');
toGlobalUses.push_back(op);
}
bool ok = std::all_of(scoreboard.begin(), scoreboard.end(),
[](bool b) { return b; });
LLVM_DEBUG(llvm::dbgs() << "all elements of array are set: " << ok << '\n');
if (ok) {
// Verify dominance relations.
// For all stores, the store of an element $e$ must dominate all loads of
// $e$.
for (int i = 0; i < size; ++i) {
for (auto *load : loadSets[i])
if (!dom.dominates(scoreboard[i], load)) {
LLVM_DEBUG(llvm::dbgs()
<< "store " << scoreboard[i]
<< " doesn't dominate load: " << *load << '\n');
return false;
}
for (auto *store : storeSets[i])
if (scoreboard[i] != store && dom.dominates(scoreboard[i], store)) {
LLVM_DEBUG(llvm::dbgs()
<< "store " << scoreboard[i]
<< " dominates another store: " << *store << '\n');
return false;
}
}
// For all global uses, all of the stores must dominate every use.
for (auto *glob : toGlobalUses) {
for (auto *store : scoreboard)
if (!dom.dominates(store, glob)) {
LLVM_DEBUG(llvm::dbgs()
<< "store " << store << " doesn't dominate op: " << *glob
<< '\n');
return false;
}
}
}
return ok;
}
DominanceInfo &dom;
StringRef funcName;
};
class LiftArrayAllocPass
: public cudaq::opt::impl::LiftArrayAllocBase<LiftArrayAllocPass> {
public:
using LiftArrayAllocBase::LiftArrayAllocBase;
void runOnOperation() override {
auto *ctx = &getContext();
auto func = getOperation();
DominanceInfo domInfo(func);
StringRef funcName = func.getName();
RewritePatternSet patterns(ctx);
patterns.insert<AllocaPattern>(ctx, domInfo, funcName);
LLVM_DEBUG(llvm::dbgs()
<< "Before lifting constant array: " << func << '\n');
if (failed(applyPatternsAndFoldGreedily(func, std::move(patterns))))
signalPassFailure();
LLVM_DEBUG(llvm::dbgs()
<< "After lifting constant array: " << func << '\n');
}
};
} // namespace