-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathLevelAnalysis.cpp
More file actions
307 lines (275 loc) · 11.5 KB
/
LevelAnalysis.cpp
File metadata and controls
307 lines (275 loc) · 11.5 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
#include "lib/Analysis/LevelAnalysis/LevelAnalysis.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <optional>
#include "lib/Analysis/Utils.h"
#include "lib/Dialect/HEIRInterfaces.h"
#include "lib/Dialect/Mgmt/IR/MgmtAttributes.h"
#include "lib/Dialect/Mgmt/IR/MgmtOps.h"
#include "lib/Dialect/ModuleAttributes.h"
#include "lib/Dialect/Secret/IR/SecretTypes.h"
#include "lib/Target/CompilationTarget/CompilationTarget.h"
#include "lib/Utils/AttributeUtils.h"
#include "lib/Utils/Utils.h"
#include "llvm/include/llvm/ADT/TypeSwitch.h" // from @llvm-project
#include "llvm/include/llvm/Support/Debug.h" // from @llvm-project
#include "mlir/include/mlir/Analysis/DataFlowFramework.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
#include "mlir/include/mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinAttributes.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "mlir/include/mlir/IR/Operation.h" // from @llvm-project
#include "mlir/include/mlir/IR/Value.h" // from @llvm-project
#include "mlir/include/mlir/IR/Visitors.h" // from @llvm-project
#include "mlir/include/mlir/Interfaces/CallInterfaces.h" // from @llvm-project
#include "mlir/include/mlir/Support/LLVM.h" // from @llvm-project
#define DEBUG_TYPE "level-analysis"
namespace mlir {
namespace heir {
//===----------------------------------------------------------------------===//
// LevelAnalysis (Forward)
//===----------------------------------------------------------------------===//
static void debugLog(StringRef opName, ArrayRef<const LevelLattice*> operands,
const LevelState& result) {
LLVM_DEBUG({
llvm::dbgs() << "transferForward: " << opName << "(";
for (auto* operand : operands) {
operand->getValue().print(llvm::dbgs());
llvm::dbgs() << ", ";
}
llvm::dbgs() << ") = ";
result.print(llvm::dbgs());
llvm::dbgs() << "\n";
});
};
LevelState transferForward(mgmt::ModReduceOp op,
ArrayRef<const LevelLattice*> operands) {
LevelState result = std::visit(
Overloaded{
[](MaxLevel) -> LevelState { return LevelState(Invalid{}); },
[](Uninit) -> LevelState { return LevelState(Invalid{}); },
[](Invalid) -> LevelState { return LevelState(Invalid{}); },
[](int val) -> LevelState { return LevelState(val + 1); },
},
operands[0]->getValue().get());
LLVM_DEBUG(debugLog("mod_reduce", operands, result));
return result;
}
LevelState transferForward(mgmt::LevelReduceOp op,
ArrayRef<const LevelLattice*> operands) {
LevelState result = std::visit(
Overloaded{
[](MaxLevel) -> LevelState { return LevelState(Invalid{}); },
[](Uninit) -> LevelState { return LevelState(Invalid{}); },
[](Invalid) -> LevelState { return LevelState(Invalid{}); },
[&](int val) -> LevelState {
return LevelState(val + (int)op.getLevelToDrop());
},
},
operands[0]->getValue().get());
LLVM_DEBUG(debugLog("level_reduce", operands, result));
return result;
}
LevelState transferForward(mgmt::LevelReduceMinOp op,
ArrayRef<const LevelLattice*> operands) {
LevelState result = std::visit(
Overloaded{
// MaxLevel -> MaxLevel should result in a no-op, so technically
// acceptable.
[](MaxLevel) -> LevelState { return LevelState(MaxLevel{}); },
[](Uninit) -> LevelState { return LevelState(Invalid{}); },
[](Invalid) -> LevelState { return LevelState(Invalid{}); },
[](int val) -> LevelState { return LevelState(MaxLevel{}); },
},
operands[0]->getValue().get());
LLVM_DEBUG(debugLog("level_reduce_min", operands, result));
return result;
}
LevelState transferForward(mgmt::BootstrapOp op,
ArrayRef<const LevelLattice*> operands) {
auto module = op->getParentOfType<ModuleOp>();
const CompilationTarget* target = getTargetConfig(module);
int levelsConsumed = target ? target->bootstrapLevelsConsumed : 0;
LevelState result = std::visit(
Overloaded{
[=](MaxLevel) -> LevelState { return LevelState(levelsConsumed); },
[](Uninit) -> LevelState { return LevelState(Invalid{}); },
[](Invalid) -> LevelState { return LevelState(Invalid{}); },
[=](int val) -> LevelState { return LevelState(levelsConsumed); },
},
operands[0]->getValue().get());
LLVM_DEBUG(debugLog("bootstrap", operands, result));
return result;
}
LevelState deriveResultLevel(Operation* op,
ArrayRef<const LevelLattice*> operands) {
return llvm::TypeSwitch<Operation&, LevelState>(*op)
.Case<mgmt::ModReduceOp, mgmt::LevelReduceOp, mgmt::BootstrapOp,
mgmt::LevelReduceMinOp>(
[&](auto op) -> LevelState { return transferForward(op, operands); })
.Default([&](auto& op) -> LevelState {
LevelState result;
for (auto* operandState : operands) {
result = LevelState::join(result, operandState->getValue());
}
LLVM_DEBUG(debugLog(op.getName().getStringRef(), operands, result));
return result;
});
}
LogicalResult LevelAnalysis::visitOperation(
Operation* op, ArrayRef<const LevelLattice*> operands,
ArrayRef<LevelLattice*> results) {
auto propagate = [&](Value value, const LevelState& state) {
auto* lattice = getLatticeElement(value);
ChangeResult changed = lattice->join(state);
propagateIfChanged(lattice, changed);
};
LevelState resultLevel = deriveResultLevel(op, operands);
SmallVector<OpResult> secretResults;
getSecretResults(op, secretResults);
for (auto result : secretResults) {
propagate(result, resultLevel);
}
return success();
}
void LevelAnalysis::visitExternalCall(
CallOpInterface call, ArrayRef<const LevelLattice*> argumentLattices,
ArrayRef<LevelLattice*> resultLattices) {
auto callback = std::bind(&LevelAnalysis::propagateIfChangedWrapper, this,
std::placeholders::_1, std::placeholders::_2);
::mlir::heir::visitExternalCall<LevelState, LevelLattice>(
call, argumentLattices, resultLattices, callback);
}
//===----------------------------------------------------------------------===//
// LevelAnalysis (Backward)
//===----------------------------------------------------------------------===//
static void debugLogBackwards(StringRef opName,
ArrayRef<const LevelLattice*> results,
const LevelState& operand, unsigned operandNum) {
LLVM_DEBUG({
llvm::dbgs() << "transferBackward: " << opName << " results(";
for (auto* result : results) {
result->getValue().print(llvm::dbgs());
llvm::dbgs() << ", ";
}
llvm::dbgs() << ") -> operand " << operandNum << " = ";
operand.print(llvm::dbgs());
llvm::dbgs() << "\n";
});
};
LogicalResult LevelAnalysisBackward::visitOperation(
Operation* op, ArrayRef<LevelLattice*> operands,
ArrayRef<const LevelLattice*> results) {
auto propagate = [&](Value value, const LevelState& state) {
auto* lattice = getLatticeElement(value);
ChangeResult changed = lattice->join(state);
if (changed == ChangeResult::Change) {
LLVM_DEBUG(llvm::dbgs() << "Back Propagating (changed) " << state
<< " to " << value << "\n");
}
propagateIfChanged(lattice, changed);
};
// Operations that cannot have a plaintext operand do not get backward
// propagation, since this backward pass is primarily to assign a level
// to plaintext operands of ct-pt ops so they can be encoded properly.
auto plaintextOperandInterface = dyn_cast<PlaintextOperandInterface>(op);
if (!plaintextOperandInterface) {
LLVM_DEBUG(llvm::dbgs()
<< "Not back propagating for " << op->getName()
<< " because it does not implement PlaintextOperandInterface\n");
return success();
}
SmallVector<unsigned> secretResultIndices;
getSecretResultIndices(op, secretResultIndices);
if (secretResultIndices.empty()) {
LLVM_DEBUG(llvm::dbgs() << "Not back propagating for " << op->getName()
<< " because no results are secret\n");
return success();
}
LLVM_DEBUG(llvm::dbgs() << "Back propagating for PlaintextOperandInterface "
<< op->getName() << "\n");
LevelState levelResult;
for (unsigned i : secretResultIndices) {
LevelState state = results[i]->getValue();
if (state.isInt() || state.isMaxLevel())
levelResult = LevelState::join(levelResult, state);
}
SmallVector<OpOperand*> plaintextOperands;
getPlaintextOperands(op, plaintextOperands);
for (auto* operand : plaintextOperands) {
LLVM_DEBUG(debugLogBackwards(op->getName().getStringRef(), results,
levelResult, operand->getOperandNumber()));
propagate(operand->get(), levelResult);
}
return success();
}
//===----------------------------------------------------------------------===//
// Utils
//===----------------------------------------------------------------------===//
// Walk the entire IR and return the maximum assigned level of all secret
// Values.
int getMaxLevel(Operation* top, DataFlowSolver* solver) {
auto maxLevel = 0;
walkValues(top, [&](Value value) {
if (mgmt::shouldHaveMgmtAttribute(value, solver)) {
auto levelState = solver->lookupState<LevelLattice>(value)->getValue();
if (levelState.isInt()) {
int level = levelState.getInt();
maxLevel = std::max(maxLevel, level);
}
}
});
return maxLevel;
}
/// baseLevel is for B/FV scheme, where all the analysis result would be 0
void annotateLevel(Operation* top, DataFlowSolver* solver, int baseLevel) {
auto maxLevel = getMaxLevel(top, solver);
auto getIntegerAttr = [&](int level) {
return IntegerAttr::get(IntegerType::get(top->getContext(), 64), level);
};
// use L to 0 instead of 0 to L
auto getLevel = [&](Value value) -> int {
LevelState levelState =
solver->lookupState<LevelLattice>(value)->getValue();
// The analysis uses 0 to L for ease of analysis, and then we materialize
// it in the IR in reverse, from L to 0.
if (levelState.isMaxLevel()) {
return 0; // reversing, the "max" level becomes level 0
}
if (!levelState.isInt()) {
return maxLevel + baseLevel;
}
return maxLevel - levelState.getInt() + baseLevel;
};
walkValues(top, [&](Value value) {
if (mgmt::shouldHaveMgmtAttribute(value, solver)) {
int level = getLevel(value);
setAttributeAssociatedWith(value, kArgLevelAttrName,
getIntegerAttr(level));
}
});
}
LevelState getLevelFromMgmtAttr(Value value) {
auto mgmtAttr = mgmt::findMgmtAttrAssociatedWith(value);
if (!mgmtAttr) {
assert(false && "MgmtAttr not found");
}
return mgmtAttr.getLevel();
}
std::optional<int> getMaxLevel(Operation* root) {
int maxLevel = 0;
root->walk([&](func::FuncOp funcOp) {
if (isClientHelper(funcOp)) {
return;
}
for (BlockArgument arg : funcOp.getArguments()) {
if (isa<secret::SecretType>(arg.getType())) {
maxLevel = std::max(maxLevel, (int)getLevelFromMgmtAttr(arg).getInt());
}
}
});
return maxLevel;
}
} // namespace heir
} // namespace mlir