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
#![expect(unused_assignments)]
mod name;
mod path;
mod symbol;
mod symbol_use;
mod table;
use alloc::{collections::VecDeque, format, vec};
use core::ptr::{DynMetadata, Pointee};
use midenc_session::diagnostics::{Diagnostic, miette};
use smallvec::SmallVec;
pub use self::{
name::*,
path::*,
symbol::{Symbol, SymbolRef},
symbol_use::*,
table::*,
};
use super::{Region, RegionRef, WalkResult};
use crate::{Operation, OperationRef, UnsafeIntrusiveEntityRef};
#[derive(Debug, thiserror::Error, Diagnostic)]
pub enum InvalidSymbolRefError {
#[error("invalid symbol reference: no symbol table available")]
NoSymbolTable {
#[label("cannot resolve this symbol")]
symbol: crate::SourceSpan,
#[label(
"because this operation has no parent symbol table with which to resolve the reference"
)]
user: crate::SourceSpan,
},
#[error("invalid symbol reference: undefined symbol")]
UnknownSymbol {
#[label("failed to resolve this symbol")]
symbol: crate::SourceSpan,
#[label("in the nearest symbol table from this operation")]
user: crate::SourceSpan,
},
#[error("invalid symbol reference: undefined component '{component}' of symbol")]
UnknownSymbolComponent {
#[label("failed to resolve this symbol")]
symbol: crate::SourceSpan,
#[label("from the root symbol table of this operation")]
user: crate::SourceSpan,
component: &'static str,
},
#[error("invalid symbol reference: expected callable")]
NotCallable {
#[label("expected this symbol to implement the CallableOpInterface")]
symbol: crate::SourceSpan,
},
#[error("invalid symbol reference: symbol is not the correct type")]
InvalidType {
#[label(
"expected this symbol to be a '{expected}', but symbol referenced a '{got}' operation"
)]
symbol: crate::SourceSpan,
expected: &'static str,
got: crate::OperationName,
},
}
/// A trait which allows multiple types to be coerced into a [SymbolRef].
///
/// This is primarily intended for use in operation builders.
pub trait AsSymbolRef {
fn as_symbol_ref(&self) -> SymbolRef;
}
impl<T: Symbol> AsSymbolRef for &T {
#[inline]
fn as_symbol_ref(&self) -> SymbolRef {
self.as_symbol_operation()
.as_symbol_ref()
.expect("symbol implementations must provide a symbol operation")
}
}
impl<T: Symbol> AsSymbolRef for UnsafeIntrusiveEntityRef<T> {
#[inline]
fn as_symbol_ref(&self) -> SymbolRef {
self.borrow()
.as_symbol_operation()
.as_symbol_ref()
.expect("symbol handles must point at symbol operations")
}
}
impl AsSymbolRef for SymbolRef {
#[inline(always)]
fn as_symbol_ref(&self) -> SymbolRef {
*self
}
}
impl UnsafeIntrusiveEntityRef<dyn Symbol> {
/// Returns this symbol as a handle to an implemented trait object, if supported.
pub fn as_trait_ref<Trait>(self) -> Option<UnsafeIntrusiveEntityRef<Trait>>
where
Trait: ?Sized + Pointee<Metadata = DynMetadata<Trait>> + 'static,
{
let symbol = self.borrow();
symbol.as_symbol_operation().as_operation_ref().as_trait_ref::<Trait>()
}
}
impl Operation {
/// Returns true if this operation implements [Symbol]
#[inline]
pub fn is_symbol(&self) -> bool {
self.implements::<dyn Symbol>()
}
/// Returns the symbol name of this operation, if it implements [Symbol]
pub fn symbol_name_if_symbol(&self) -> Option<SymbolName> {
self.as_symbol().map(|symbol| symbol.name())
}
/// Get this operation as a [Symbol], if this operation implements the trait.
#[inline]
pub fn as_symbol(&self) -> Option<&dyn Symbol> {
self.as_trait::<dyn Symbol>()
}
/// Get this operation as a [SymbolRef], if this operation implements the trait.
#[inline]
pub fn as_symbol_ref(&self) -> Option<SymbolRef> {
self.as_operation_ref().as_trait_ref::<dyn Symbol>()
}
/// Get this operation as a [SymbolTable], if this operation implements the trait.
#[inline]
pub fn as_symbol_table(&self) -> Option<&dyn SymbolTable> {
self.as_trait::<dyn SymbolTable>()
}
/// Return the root symbol table in which this symbol is contained, if one exists.
///
/// The root symbol table is always the top-level ancestor (i.e. has no parent). In general
/// when we refer to the root symbol table, we are referring to an anonymous symbol table that
/// represents the global namespace in which all symbols are rooted. However, it may be the
/// case that the top-level ancestor is actually a symbol, in which case it is presumed that
/// it is a symbol in the global namespace, and that only symbols nested within it are
/// resolvable.
///
/// Callers are expected to know this difference.
pub fn root_symbol_table(&self) -> Option<OperationRef> {
let mut parent = Some(self.as_operation_ref());
while let Some(ancestor) = parent.take() {
let ancestor_op = ancestor.borrow();
let next = ancestor_op.parent_op();
if next.is_none() {
parent = if ancestor_op.implements::<dyn SymbolTable>() {
Some(ancestor)
} else {
None
};
break;
} else {
parent = next;
}
}
parent
}
/// Returns the nearest [SymbolTable] from this operation.
///
/// Returns `None` if no parent of this operation is a valid symbol table.
pub fn nearest_symbol_table(&self) -> Option<OperationRef> {
self.as_operation_ref().nearest_symbol_table()
}
/// Returns the operation registered with the given symbol name within the closest symbol table
/// including `self`.
///
/// Returns `None` if the symbol is not found.
pub fn nearest_symbol(&self, symbol: SymbolName) -> Option<SymbolRef> {
if let Some(sym) = self.as_symbol()
&& sym.name() == symbol
{
return self.as_symbol_ref();
}
let symbol_table_op = self.nearest_symbol_table()?;
let op = symbol_table_op.borrow();
let symbol_table = op.as_trait::<dyn SymbolTable>().unwrap();
symbol_table.get(symbol)
}
/// Walks all symbol table operations nested within this operation, including itself.
///
/// For each symbol table operation, the provided callback is invoked with the op and a boolean
/// signifying if the symbols within that symbol table can be treated as if all uses within the
/// IR are visible to the caller.
pub fn walk_symbol_tables<F>(&self, all_symbol_uses_visible: bool, mut callback: F)
where
F: FnMut(&dyn SymbolTable, bool),
{
self.prewalk_all(|op: &Operation| {
if let Some(sym) = op.as_symbol_table() {
callback(sym, all_symbol_uses_visible);
}
});
}
/// Walk all of the operations nested under, and including this operation, without traversing
/// into any nested symbol tables (including this operation, if it is a symbol table).
///
/// Stops walking if the result of the callback is anything other than `WalkResult::Continue`.
pub fn walk_symbol_table<F>(&self, mut callback: F) -> WalkResult
where
F: FnMut(&Operation) -> WalkResult,
{
callback(self)?;
if self.implements::<dyn SymbolTable>() {
return WalkResult::Continue(());
}
for region in self.regions() {
Self::walk_symbol_table_region(®ion, &mut callback)?;
}
WalkResult::Continue(())
}
/// Walk all of the operations within the given set of regions, without traversing into any
/// nested symbol tables. If `WalkResult::Skip` is returned for an op, none of that op's regions
/// will be visited.
pub fn walk_symbol_table_region<F>(region: &Region, mut callback: F) -> WalkResult
where
F: FnMut(&Operation) -> WalkResult,
{
let mut regions = SmallVec::<[RegionRef; 4]>::from_iter([region.as_region_ref()]);
while let Some(region) = regions.pop() {
let region = region.borrow();
for block in region.body() {
for op in block.body() {
match callback(&op) {
WalkResult::Continue(_) => {
// If this op defines a new symbol table scope, we can't traverse. Any symbol
// references nested within this op are different semantically.
if !op.implements::<dyn SymbolTable>() {
regions.extend(op.regions().iter().map(|r| r.as_region_ref()));
}
}
err @ WalkResult::Break(_) => return err,
WalkResult::Skip => (),
}
}
}
}
WalkResult::Continue(())
}
/// Walk all of the uses, for any symbol, that are nested within this operation, invoking the
/// provided callback for each use.
///
/// This does not traverse into any nested symbol tables.
pub fn walk_symbol_uses<F>(&self, mut callback: F) -> WalkResult
where
F: FnMut(SymbolUseRef) -> WalkResult,
{
// Walk the uses on this operation.
Self::walk_symbol_refs(self, &mut callback)?;
// Only recurse if this operation is not a symbol table. A symbol table defines a new scope,
// so we can't walk the attributes from within the symbol table op.
if !self.implements::<dyn SymbolTable>() {
for region in self.regions() {
Self::walk_symbol_table_region(®ion, |op| {
Self::walk_symbol_refs(op, &mut callback)
})?;
}
}
WalkResult::Continue(())
}
/// Walk all of the uses, for any symbol, that are nested within the given region, invoking the
/// provided callback for each use.
///
/// This does not traverse into any nested symbol tables.
pub fn walk_symbol_uses_in_region<F>(from: &Region, mut callback: F) -> WalkResult
where
F: FnMut(SymbolUseRef) -> WalkResult,
{
Self::walk_symbol_table_region(from, |op| Self::walk_symbol_refs(op, &mut callback))
}
/// Get an iterator over all of the uses, for any symbol, that are nested within the current
/// operation.
///
/// This does not traverse into any nested symbol tables, and will also only return uses on
/// the current operation if it does not also define a symbol table. This is because we treat
/// the region as the boundary of the symbol table, and not the op itself.
pub fn all_symbol_uses(&self) -> SymbolUseRefsIter {
let mut uses = VecDeque::new();
if self.implements::<dyn SymbolTable>() {
return SymbolUseRefsIter::from(uses);
}
let _ = Self::walk_symbol_refs(self, |symbol_use| {
uses.push_back(symbol_use);
WalkResult::Continue(())
});
for region in self.regions() {
let _ = Self::walk_symbol_uses_in_region(®ion, |symbol_use| {
uses.push_back(symbol_use);
WalkResult::Continue(())
});
}
SymbolUseRefsIter::from(uses)
}
/// Get an iterator over all of the uses, for any symbol, that are nested within the given
/// region 'from'.
///
/// This does not traverse into any nested symbol tables.
pub fn all_symbol_uses_in_region(from: &Region) -> SymbolUseRefsIter {
let mut uses = VecDeque::new();
let _ = Self::walk_symbol_uses_in_region(from, |symbol_use| {
uses.push_back(symbol_use);
WalkResult::Continue(())
});
SymbolUseRefsIter::from(uses)
}
/// Walk all of the symbol references within the given operation, invoking the provided callback
/// for each found use.
///
/// The callbacks takes the symbol use.
pub fn walk_symbol_refs<F>(op: &Operation, mut callback: F) -> WalkResult
where
F: FnMut(SymbolUseRef) -> WalkResult,
{
use crate::dialects::builtin::attributes::SymbolRefAttr;
for attr in op.properties() {
let attr = attr.value();
if let Some(attr) = attr.downcast_ref::<SymbolRefAttr>() {
callback(attr.user())?;
}
}
for attr in op.attributes() {
let attr = attr.as_named_attribute();
let attr = attr.value();
if let Some(attr) = attr.downcast_ref::<SymbolRefAttr>() {
callback(attr.user())?;
}
}
WalkResult::Continue(())
}
}