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) 2017 Fabian Schuiki

use crate::{Aggregate, Const, Type};
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};

pub trait Value {
    /// Get the unique ID of the value.
    fn id(&self) -> ValueId;
    /// Get the type of the value.
    fn ty(&self) -> Type;
    /// Get the optional name of the value.
    fn name(&self) -> Option<&str> {
        None
    }
    /// Whether this value is global or not. Global values are considered during
    /// linking, and are visible in a module's symbol table. Local values are
    /// not, and are only visible within the surrounding context (module or
    /// unit).
    fn is_global(&self) -> bool {
        false
    }
}

/// A reference to a value in a module.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueRef {
    Inst(InstRef),
    Block(BlockRef),
    Argument(ArgumentRef),
    Function(FunctionRef),
    Process(ProcessRef),
    Entity(EntityRef),
    Global,
    Const(Const),
    Aggregate(Aggregate),
}

impl ValueRef {
    /// Return a static string describing the nature of the value reference.
    fn desc(&self) -> &'static str {
        match *self {
            ValueRef::Inst(_) => "ValueRef::Inst",
            ValueRef::Block(_) => "ValueRef::Block",
            ValueRef::Argument(_) => "ValueRef::Argument",
            ValueRef::Function(_) => "ValueRef::Function",
            ValueRef::Process(_) => "ValueRef::Process",
            ValueRef::Entity(_) => "ValueRef::Entity",
            ValueRef::Global => "ValueRef::Global",
            ValueRef::Const(_) => "ValueRef::Const",
            ValueRef::Aggregate(_) => "ValueRef::Aggregate",
        }
    }

    /// Convert this value reference into the constant it contains. Panics if
    /// the value reference does not contain a constant.
    pub fn into_const(self) -> Const {
        match self {
            ValueRef::Const(k) => k,
            x => panic!("into_const called on {}", x.desc()),
        }
    }

    /// Unwrap and return a reference to the constant represented by this value
    /// reference. Panics if the value reference does not contain a constant.
    pub fn as_const(&self) -> &Const {
        match *self {
            ValueRef::Const(ref k) => k,
            _ => panic!("as_const called on {}", self.desc()),
        }
    }

    /// Try to unwrap this value reference as a constant.
    pub fn maybe_const(&self) -> Option<&Const> {
        match *self {
            ValueRef::Const(ref k) => Some(k),
            _ => None,
        }
    }

    /// Obtain the ID of the value this reference points to, or None if the
    /// value has no ID (e.g. if it is a constant).
    pub fn id(&self) -> Option<ValueId> {
        match *self {
            ValueRef::Inst(InstRef(id))
            | ValueRef::Block(BlockRef(id))
            | ValueRef::Argument(ArgumentRef(id))
            | ValueRef::Function(FunctionRef(id))
            | ValueRef::Process(ProcessRef(id))
            | ValueRef::Entity(EntityRef(id)) => Some(id),
            _ => None,
        }
    }

    /// Unwrap this reference as an instruction.
    ///
    /// Panics if this is not an instruction.
    pub fn unwrap_inst(&self) -> InstRef {
        match *self {
            ValueRef::Inst(x) => x,
            _ => panic!("unwrap_inst called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as a block.
    ///
    /// Panics if this is not a block.
    pub fn unwrap_block(&self) -> BlockRef {
        match *self {
            ValueRef::Block(x) => x,
            _ => panic!("unwrap_block called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as an argument.
    ///
    /// Panics if this is not an argument.
    pub fn unwrap_argument(&self) -> ArgumentRef {
        match *self {
            ValueRef::Argument(x) => x,
            _ => panic!("unwrap_argument called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as a function.
    ///
    /// Panics if this is not a function.
    pub fn unwrap_function(&self) -> FunctionRef {
        match *self {
            ValueRef::Function(x) => x,
            _ => panic!("unwrap_function called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as a process.
    ///
    /// Panics if this is not a process.
    pub fn unwrap_process(&self) -> ProcessRef {
        match *self {
            ValueRef::Process(x) => x,
            _ => panic!("unwrap_process called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as an entity.
    ///
    /// Panics if this is not an entity.
    pub fn unwrap_entity(&self) -> EntityRef {
        match *self {
            ValueRef::Entity(x) => x,
            _ => panic!("unwrap_entity called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as a constant.
    ///
    /// Panics if this is not a constant.
    pub fn unwrap_const(&self) -> &Const {
        match *self {
            ValueRef::Const(ref x) => x,
            _ => panic!("unwrap_const called on {}", self.desc()),
        }
    }

    /// Unwrap this reference as an aggregate.
    ///
    /// Panics if this is not an aggregate.
    pub fn unwrap_aggregate(&self) -> &Aggregate {
        match *self {
            ValueRef::Aggregate(ref x) => x,
            _ => panic!("unwrap_aggregate called on {}", self.desc()),
        }
    }
}

/// A unique identifier assigned to each value node in the graph. These IDs are
/// wrapped specific ValueRef variants to refer to values in the graph.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ValueId(usize);

impl ValueId {
    /// Allocate a new unique value ID.
    pub fn alloc() -> ValueId {
        ValueId(NEXT_VALUE_ID.fetch_add(1, Ordering::SeqCst) + 1)
    }

    /// Get the underlying integer ID.
    pub fn as_usize(self) -> usize {
        self.0
    }
}

impl std::fmt::Debug for ValueId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl std::fmt::Display for ValueId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.as_usize())
    }
}

/// The next ID to be allocated in `ValueId::alloc()`. Incremented atomically.
static NEXT_VALUE_ID: AtomicUsize = ATOMIC_USIZE_INIT;

/// The ID of inline values such as constants.
pub const INLINE_VALUE_ID: ValueId = ValueId(0);
// TODO: Maybe we want to get rid of this in favor of removing `id()` from the
// `Value` trait and adding it to a `HasId` trait. Where the ID is needed, we
// would use a `Value + HasId` bound.

/// Declares a new wrapper type around ValueRef, allowing the target of the
/// reference to be encoded in the type, e.g. `ArgumentRef` or `InstRef`.
macro_rules! declare_ref {
    ($name:ident, $variant:ident) => {
        #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
        pub struct $name(ValueId);

        impl $name {
            pub fn new(id: ValueId) -> $name {
                $name(id)
            }
        }

        impl Into<ValueRef> for $name {
            fn into(self) -> ValueRef {
                ValueRef::$variant(self)
            }
        }

        impl Into<ValueId> for $name {
            fn into(self) -> ValueId {
                self.0
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{}", self.0)
            }
        }

        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{}({})", stringify!($name), self.0)
            }
        }
    };
}

declare_ref!(FunctionRef, Function);
declare_ref!(ProcessRef, Process);
declare_ref!(EntityRef, Entity);
declare_ref!(ArgumentRef, Argument);
declare_ref!(BlockRef, Block);
declare_ref!(InstRef, Inst);

/// A context is anything that can resolve the name and type of a ValueRef.
/// Contexts are expected to form a hierarchy, such that a context wrapping e.g.
/// a function falls back to a parent context wrapping the module if a value
/// cannot be appropriately resolved.
pub trait Context: AsContext {
    /// Try to resolve a `ValueRef` to an actual `&Value` reference. May fail if
    /// the value is not known to the context.
    fn try_value(&self, value: &ValueRef) -> Option<&Value>;

    /// Get the parent context to which value resolution shall escalate. May
    /// return `None` for the context at the top of the hierarchy.
    fn parent(&self) -> Option<&Context> {
        None
    }

    /// Resolve a `ValueRef` to an actual `&Value` reference. Panics if the
    /// value is unknown to this context and its parents.
    fn value(&self, value: &ValueRef) -> &Value {
        self.try_value(value)
            .or_else(|| self.parent().map(|p| p.value(value)))
            .expect("unable to resolve ValueRef")
    }

    /// Get the type of a value.
    fn ty(&self, value: &ValueRef) -> Type {
        value
            .maybe_const()
            .map(|k| k.ty())
            .unwrap_or_else(|| self.value(value).ty())
    }

    /// Get the name of a value.
    fn name(&self, value: &ValueRef) -> Option<&str> {
        self.value(value).name()
    }
}

pub trait AsContext {
    fn as_context(&self) -> &Context;
}

impl<T: Context> AsContext for T {
    fn as_context(&self) -> &Context {
        self
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn type_of_const() {
        let m = Module::new();
        let ctx = ModuleContext::new(&m);
        let value: ValueRef = const_int(32, 0.into()).into();
        assert_eq!(ctx.ty(&value), int_ty(32));
    }
}