Skip to main content

wings_ir/validate/
function.rs

1use super::*;
2
3impl Function {
4    pub(super) fn validate(
5        &self,
6        state: ValueType,
7        parameters: &[(String, ValueType)],
8        reply: ValueType,
9        allow_state: bool,
10        allow_loops: bool,
11    ) -> Result<(), String> {
12        if self.instructions.len() > MAX_OPERATIONS {
13            return Err("too many operations for the scalar prototype".into());
14        }
15        let mut types = Vec::new();
16        let mut available = Vec::new();
17        let mut branches = Vec::new();
18        let mut expected_phis: std::collections::VecDeque<(usize, ValueType)> =
19            std::collections::VecDeque::new();
20        let mut seen_proc_gc_point = false;
21        for instruction in &self.instructions {
22            if let Some((expected_index, expected_ty)) = expected_phis.pop_front() {
23                if !matches!(instruction.operation, Operation::PhiValue(actual) if actual == expected_index)
24                    || instruction.ty != expected_ty
25                {
26                    return Err("invalid or missing phi result instruction".into());
27                }
28                types.push(instruction.ty);
29                available.push(true);
30                continue;
31            }
32            if matches!(instruction.operation, Operation::PhiValue(_)) {
33                return Err("unexpected phi result instruction".into());
34            }
35            let operands = operands(&instruction.operation);
36            if operands
37                .into_iter()
38                .any(|register| available.get(register) != Some(&true))
39            {
40                return Err(
41                    "invalid scalar IR operand, type or forward reference, or branch scope".into(),
42                );
43            }
44            let valid = match instruction.operation {
45                Operation::Constant(value) => instruction.ty.accepts(value),
46                Operation::StringLiteral(ref value) => {
47                    instruction.ty == ValueType::StringRef && value.len() <= 65536
48                }
49                Operation::FormatString {
50                    ref blob,
51                    ref pieces,
52                    ref arguments,
53                } => {
54                    instruction.ty == ValueType::StringRef
55                        && !pieces.is_empty()
56                        && pieces.len() <= wings_abi::MAX_FORMAT_PIECES
57                        && arguments.len() <= pieces.len()
58                        && blob.len() <= 65536
59                        && pieces.iter().all(|piece| match *piece {
60                            FormatPiece::Literal { offset, len } => (offset as usize)
61                                .checked_add(len as usize)
62                                .is_some_and(|end| {
63                                    end <= blob.len()
64                                        && blob.is_char_boundary(offset as usize)
65                                        && blob.is_char_boundary(end)
66                                }),
67                            FormatPiece::String(idx) => {
68                                arguments.get(idx).and_then(|&r| types.get(r))
69                                    == Some(&ValueType::StringRef)
70                            }
71                            FormatPiece::Int(idx) => {
72                                arguments.get(idx).and_then(|&r| types.get(r))
73                                    == Some(&ValueType::Int)
74                            }
75                            FormatPiece::Bool(idx) => {
76                                arguments.get(idx).and_then(|&r| types.get(r))
77                                    == Some(&ValueType::Bool)
78                            }
79                        })
80                }
81                Operation::BytesLiteral(ref value) => {
82                    instruction.ty == ValueType::BytesRef && value.len() <= 65536
83                }
84                Operation::IntToString(value) => {
85                    instruction.ty == ValueType::StringRef
86                        && types.get(value) == Some(&ValueType::Int)
87                }
88                Operation::BoolToString(value) => {
89                    instruction.ty == ValueType::StringRef
90                        && types.get(value) == Some(&ValueType::Bool)
91                }
92                Operation::RecordNew { .. } | Operation::RecordField { .. } => true,
93                Operation::State => allow_state && instruction.ty == state,
94                Operation::Argument(index) => {
95                    (!instruction.ty.is_reference() || allow_state || !seen_proc_gc_point)
96                        && parameters
97                            .get(index)
98                            .is_some_and(|parameter| parameter.1 == instruction.ty)
99                }
100                Operation::Negate(value) => {
101                    instruction.ty == ValueType::Int && types.get(value) == Some(&ValueType::Int)
102                }
103                Operation::Binary(_, left, right) => {
104                    instruction.ty == ValueType::Int
105                        && types.get(left) == Some(&ValueType::Int)
106                        && types.get(right) == Some(&ValueType::Int)
107                }
108                Operation::Compare(comparison, left, right) => {
109                    instruction.ty == ValueType::Bool
110                        && types.get(left) == types.get(right)
111                        && match comparison {
112                            Comparison::Equal | Comparison::NotEqual => matches!(
113                                types.get(left),
114                                Some(
115                                    ValueType::Int
116                                        | ValueType::Bool
117                                        | ValueType::Unit
118                                        | ValueType::Pid
119                                )
120                            ),
121                            _ => types.get(left) == Some(&ValueType::Int),
122                        }
123                }
124                Operation::Collect => instruction.ty == ValueType::Unit,
125                Operation::EmptyInts => instruction.ty == ValueType::ListRef,
126                Operation::PrependInt(value, tail) => {
127                    instruction.ty == ValueType::ListRef
128                        && types.get(value) == Some(&ValueType::Int)
129                        && types.get(tail) == Some(&ValueType::ListRef)
130                }
131                Operation::HeadInt(value) => {
132                    instruction.ty == ValueType::Int
133                        && types.get(value) == Some(&ValueType::ListRef)
134                }
135                Operation::TailInts(value) => {
136                    instruction.ty == ValueType::ListRef
137                        && types.get(value) == Some(&ValueType::ListRef)
138                }
139                Operation::IsEmptyInts(value) => {
140                    instruction.ty == ValueType::Bool
141                        && types.get(value) == Some(&ValueType::ListRef)
142                }
143                Operation::FillBytes(length, value) => {
144                    instruction.ty == ValueType::BytesRef
145                        && types.get(length) == Some(&ValueType::Int)
146                        && types.get(value) == Some(&ValueType::Int)
147                }
148                Operation::BytesLen(value) => {
149                    instruction.ty == ValueType::Int
150                        && types.get(value) == Some(&ValueType::BytesRef)
151                }
152                Operation::StringFromBytes(value) => {
153                    instruction.ty == ValueType::StringRef
154                        && types.get(value) == Some(&ValueType::BytesRef)
155                }
156                Operation::StringBytes(value) => {
157                    instruction.ty == ValueType::BytesRef
158                        && types.get(value) == Some(&ValueType::StringRef)
159                }
160                Operation::StringLen(value) => {
161                    instruction.ty == ValueType::Int
162                        && types.get(value) == Some(&ValueType::StringRef)
163                }
164                Operation::StringAt(value, index) => {
165                    instruction.ty == ValueType::Int
166                        && types.get(value) == Some(&ValueType::StringRef)
167                        && types.get(index) == Some(&ValueType::Int)
168                }
169                Operation::StringSlice([value, start, length]) => {
170                    instruction.ty == ValueType::StringRef
171                        && types.get(value) == Some(&ValueType::StringRef)
172                        && types.get(start) == Some(&ValueType::Int)
173                        && types.get(length) == Some(&ValueType::Int)
174                }
175                Operation::ConcatStrings(left, right) => {
176                    instruction.ty == ValueType::StringRef
177                        && types.get(left) == Some(&ValueType::StringRef)
178                        && types.get(right) == Some(&ValueType::StringRef)
179                }
180                Operation::EqualStrings(left, right) => {
181                    instruction.ty == ValueType::Bool
182                        && types.get(left) == Some(&ValueType::StringRef)
183                        && types.get(right) == Some(&ValueType::StringRef)
184                }
185                Operation::ByteAt(value, index) | Operation::ReadI64Be(value, index) => {
186                    instruction.ty == ValueType::Int
187                        && types.get(value) == Some(&ValueType::BytesRef)
188                        && types.get(index) == Some(&ValueType::Int)
189                }
190                Operation::ReplaceByte([value, index, byte])
191                | Operation::ReplaceI64Be([value, index, byte]) => {
192                    instruction.ty == ValueType::BytesRef
193                        && types.get(value) == Some(&ValueType::BytesRef)
194                        && types.get(index) == Some(&ValueType::Int)
195                        && types.get(byte) == Some(&ValueType::Int)
196                }
197                Operation::SendSelf { ref arguments, .. } => {
198                    instruction.ty == ValueType::Unit
199                        && arguments.len() <= MAX_PARAMETERS
200                        && arguments.iter().all(|register| {
201                            types.get(*register).is_some_and(|ty| {
202                                matches!(
203                                    ty,
204                                    ValueType::Int
205                                        | ValueType::Bool
206                                        | ValueType::Unit
207                                        | ValueType::ListRef
208                                        | ValueType::BytesRef
209                                        | ValueType::StringRef
210                                        | ValueType::Pid
211                                )
212                            })
213                        })
214                }
215                Operation::SendAfterSelf {
216                    delay,
217                    ref arguments,
218                    ..
219                } => {
220                    instruction.ty == ValueType::Unit
221                        && types.get(delay) == Some(&ValueType::Int)
222                        && arguments.len() <= MAX_PARAMETERS
223                        && arguments.iter().all(|register| {
224                            types.get(*register).is_some_and(|ty| {
225                                matches!(
226                                    ty,
227                                    ValueType::Int
228                                        | ValueType::Bool
229                                        | ValueType::Unit
230                                        | ValueType::ListRef
231                                        | ValueType::BytesRef
232                                        | ValueType::StringRef
233                                        | ValueType::Pid
234                                )
235                            })
236                        })
237                }
238                Operation::NullPid
239                | Operation::SelfPid
240                | Operation::SpawnSelf
241                | Operation::SpawnActor(_) => instruction.ty == ValueType::Pid,
242                Operation::Monitor { target, .. } => {
243                    instruction.ty == ValueType::Unit && types.get(target) == Some(&ValueType::Pid)
244                }
245                Operation::Hostcall {
246                    timeout,
247                    ref arguments,
248                } => {
249                    instruction.ty == ValueType::BytesRef
250                        && types.get(timeout) == Some(&ValueType::Int)
251                        && arguments.len() == 2
252                        && types.get(arguments[0]) == Some(&ValueType::StringRef)
253                        && types.get(arguments[1]) == Some(&ValueType::BytesRef)
254                }
255                Operation::Request {
256                    target,
257                    timeout,
258                    ref arguments,
259                    ..
260                }
261                | Operation::RequestActor {
262                    target,
263                    timeout,
264                    ref arguments,
265                    ..
266                } => {
267                    instruction.ty == ValueType::RequestId
268                        && types.get(target) == Some(&ValueType::Pid)
269                        && types.get(timeout) == Some(&ValueType::Int)
270                        && arguments.len() <= MAX_PARAMETERS
271                        && arguments.iter().all(|register| {
272                            types.get(*register).is_some_and(|ty| {
273                                matches!(
274                                    ty,
275                                    ValueType::Int
276                                        | ValueType::Bool
277                                        | ValueType::Unit
278                                        | ValueType::ListRef
279                                        | ValueType::BytesRef
280                                        | ValueType::StringRef
281                                        | ValueType::Pid
282                                )
283                            })
284                        })
285                }
286                Operation::CancelRequest(value) => {
287                    instruction.ty == ValueType::Unit
288                        && types.get(value) == Some(&ValueType::RequestId)
289                }
290                Operation::Call { ref arguments, .. } => arguments.len() <= MAX_PARAMETERS,
291                Operation::Send {
292                    target,
293                    ref arguments,
294                    ..
295                }
296                | Operation::SendActor {
297                    target,
298                    ref arguments,
299                    ..
300                } => {
301                    instruction.ty == ValueType::Unit
302                        && types.get(target) == Some(&ValueType::Pid)
303                        && arguments.len() <= MAX_PARAMETERS
304                        && arguments.iter().all(|register| {
305                            types.get(*register).is_some_and(|ty| {
306                                matches!(
307                                    ty,
308                                    ValueType::Int
309                                        | ValueType::Bool
310                                        | ValueType::Unit
311                                        | ValueType::ListRef
312                                        | ValueType::BytesRef
313                                        | ValueType::StringRef
314                                        | ValueType::Pid
315                                )
316                            })
317                        })
318                }
319                Operation::SendAfter {
320                    target,
321                    delay,
322                    ref arguments,
323                    ..
324                }
325                | Operation::SendAfterActor {
326                    target,
327                    delay,
328                    ref arguments,
329                    ..
330                } => {
331                    instruction.ty == ValueType::Unit
332                        && types.get(target) == Some(&ValueType::Pid)
333                        && types.get(delay) == Some(&ValueType::Int)
334                        && arguments.len() <= MAX_PARAMETERS
335                        && arguments.iter().all(|register| {
336                            types.get(*register).is_some_and(|ty| {
337                                matches!(
338                                    ty,
339                                    ValueType::Int
340                                        | ValueType::Bool
341                                        | ValueType::Unit
342                                        | ValueType::ListRef
343                                        | ValueType::BytesRef
344                                        | ValueType::StringRef
345                                        | ValueType::Pid
346                                )
347                            })
348                        })
349                }
350                Operation::If(condition) => {
351                    if branches.len() == 64 {
352                        return Err("conditional nesting exceeds 64 branches".into());
353                    }
354                    branches.push(Region::Branch(types.len(), None));
355                    instruction.ty == ValueType::Unit
356                        && types.get(condition) == Some(&ValueType::Bool)
357                }
358                Operation::Else(ref values) => {
359                    let Some(Region::Branch(start, arm)) = branches.last_mut() else {
360                        return Err("else without matching if".into());
361                    };
362                    if arm.is_some() {
363                        return Err("duplicate else in conditional".into());
364                    }
365                    if values.is_empty() || values.len() > MAX_PARAMETERS {
366                        return Err("invalid branch arity".into());
367                    }
368                    let then_types: Vec<ValueType> = values.iter().map(|&reg| types[reg]).collect();
369                    *arm = Some(then_types);
370                    available[start.saturating_add(1)..].fill(false);
371                    instruction.ty == ValueType::Unit
372                }
373                Operation::EndIf(ref values) => {
374                    let Some(Region::Branch(start, Some(then_types))) = branches.pop() else {
375                        return Err("end-if without matching if/else".into());
376                    };
377                    available[start.saturating_add(1)..].fill(false);
378                    let valid = values.len() == then_types.len()
379                        && instruction.ty == then_types[0]
380                        && values
381                            .iter()
382                            .zip(&then_types)
383                            .all(|(&reg, &ty)| types.get(reg) == Some(&ty));
384                    for (idx, &ty) in then_types.iter().enumerate().skip(1) {
385                        expected_phis.push_back((idx, ty));
386                    }
387                    valid
388                }
389                Operation::Loop(ref initials) => {
390                    if branches.len() == 64 {
391                        return Err("control nesting exceeds 64 regions".into());
392                    }
393                    if !allow_loops || initials.is_empty() || initials.len() > MAX_PARAMETERS {
394                        false
395                    } else {
396                        let phi_types: Vec<ValueType> =
397                            initials.iter().map(|&reg| types[reg]).collect();
398                        let valid = instruction.ty == phi_types[0];
399                        for (idx, &ty) in phi_types.iter().enumerate().skip(1) {
400                            expected_phis.push_back((idx, ty));
401                        }
402                        branches.push(Region::Loop(types.len(), phi_types, false));
403                        valid
404                    }
405                }
406                Operation::While(condition, ref exit_values) => {
407                    let Some(Region::Loop(_, phi_types, tested)) = branches.last_mut() else {
408                        return Err("while without matching loop".into());
409                    };
410                    if *tested {
411                        return Err("duplicate while in loop".into());
412                    }
413                    *tested = true;
414                    instruction.ty == ValueType::Unit
415                        && types.get(condition) == Some(&ValueType::Bool)
416                        && exit_values.len() == phi_types.len()
417                        && exit_values
418                            .iter()
419                            .zip(phi_types.iter())
420                            .all(|(&reg, &ty)| types.get(reg) == Some(&ty))
421                }
422                Operation::EndLoop(ref values) => {
423                    let Some(Region::Loop(start, phi_types, true)) = branches.pop() else {
424                        return Err("end-loop without matching loop/while".into());
425                    };
426                    available[start..].fill(false);
427                    let valid = values.len() == phi_types.len()
428                        && instruction.ty == phi_types[0]
429                        && values
430                            .iter()
431                            .zip(&phi_types)
432                            .all(|(&reg, &ty)| types.get(reg) == Some(&ty));
433                    for (idx, &ty) in phi_types.iter().enumerate().skip(1) {
434                        expected_phis.push_back((idx, ty));
435                    }
436                    valid
437                }
438                Operation::PhiValue(_) => false,
439            };
440            if !valid {
441                return Err("invalid scalar IR operand, type or forward reference".into());
442            }
443            if !allow_state
444                && !matches!(
445                    instruction.operation,
446                    Operation::Constant(_)
447                        | Operation::NullPid
448                        | Operation::Argument(_)
449                        | Operation::Negate(_)
450                        | Operation::Binary(_, _, _)
451                        | Operation::Compare(_, _, _)
452                        | Operation::PhiValue(_)
453                        | Operation::RecordField { .. }
454                        | Operation::HeadInt(_)
455                        | Operation::TailInts(_)
456                        | Operation::IsEmptyInts(_)
457                        | Operation::BytesLen(_)
458                        | Operation::StringLen(_)
459                        | Operation::ByteAt(_, _)
460                        | Operation::ReadI64Be(_, _)
461                )
462            {
463                seen_proc_gc_point = true;
464            }
465            types.push(instruction.ty);
466            available.push(!matches!(
467                instruction.operation,
468                Operation::If(_) | Operation::Else(_) | Operation::While(_, _)
469            ));
470        }
471        if !expected_phis.is_empty() {
472            return Err("missing phi result instruction".into());
473        }
474        if !branches.is_empty() {
475            return Err("unterminated conditional in scalar IR".into());
476        }
477        if types.get(self.state) != Some(&state)
478            || types.get(self.reply) != Some(&reply)
479            || available.get(self.state) != Some(&true)
480            || available.get(self.reply) != Some(&true)
481        {
482            return Err("invalid scalar IR state or reply register".into());
483        }
484        if self.root_plan().capacity > MAX_SHADOW_ROOTS {
485            return Err("AOT function exceeds 64 simultaneously live reference roots".into());
486        }
487        Ok(())
488    }
489
490    pub fn root_plan(&self) -> RootPlan {
491        root_plan::build(self)
492    }
493}
494
495pub fn operands(operation: &Operation) -> impl Iterator<Item = Register> + '_ {
496    let (fixed, extra): (_, &[Register]) = match *operation {
497        Operation::Negate(value) | Operation::If(value) => ([Some(value), None], &[]),
498        Operation::While(value, ref exit_values) => ([Some(value), None], exit_values.as_slice()),
499        Operation::HeadInt(value)
500        | Operation::TailInts(value)
501        | Operation::IsEmptyInts(value)
502        | Operation::BytesLen(value)
503        | Operation::StringFromBytes(value)
504        | Operation::StringBytes(value)
505        | Operation::StringLen(value)
506        | Operation::IntToString(value)
507        | Operation::BoolToString(value) => ([Some(value), None], &[]),
508        Operation::StringAt(value, index) => ([Some(value), Some(index)], &[]),
509        Operation::Else(ref values)
510        | Operation::EndIf(ref values)
511        | Operation::Loop(ref values)
512        | Operation::EndLoop(ref values) => ([None, None], values.as_slice()),
513        Operation::Binary(_, left, right)
514        | Operation::Compare(_, left, right)
515        | Operation::FillBytes(left, right)
516        | Operation::ConcatStrings(left, right)
517        | Operation::EqualStrings(left, right)
518        | Operation::ByteAt(left, right)
519        | Operation::ReadI64Be(left, right)
520        | Operation::PrependInt(left, right) => ([Some(left), Some(right)], &[]),
521        Operation::ReplaceByte(ref arguments) | Operation::ReplaceI64Be(ref arguments) => {
522            ([None, None], arguments.as_slice())
523        }
524        Operation::StringSlice(ref arguments) => ([None, None], arguments.as_slice()),
525        Operation::SendSelf { ref arguments, .. } => ([None, None], arguments),
526        Operation::SendAfterSelf {
527            delay,
528            ref arguments,
529            ..
530        } => ([Some(delay), None], arguments),
531        Operation::Call { ref arguments, .. } => ([None, None], arguments),
532        Operation::FormatString { ref arguments, .. } => ([None, None], arguments),
533        Operation::RecordNew { ref arguments, .. } => ([None, None], arguments),
534        Operation::RecordField { value, .. } => ([Some(value), None], &[]),
535        Operation::Send {
536            target,
537            ref arguments,
538            ..
539        }
540        | Operation::SendActor {
541            target,
542            ref arguments,
543            ..
544        } => ([Some(target), None], arguments),
545        Operation::SendAfter {
546            target,
547            delay,
548            ref arguments,
549            ..
550        }
551        | Operation::SendAfterActor {
552            target,
553            delay,
554            ref arguments,
555            ..
556        } => ([Some(target), Some(delay)], arguments),
557        Operation::Monitor { target, .. } => ([Some(target), None], &[]),
558        Operation::Hostcall {
559            timeout,
560            ref arguments,
561        } => ([Some(timeout), None], arguments),
562        Operation::Request {
563            target,
564            timeout,
565            ref arguments,
566            ..
567        }
568        | Operation::RequestActor {
569            target,
570            timeout,
571            ref arguments,
572            ..
573        } => ([Some(target), Some(timeout)], arguments),
574        Operation::CancelRequest(value) => ([Some(value), None], &[]),
575        _ => ([None, None], &[]),
576    };
577    fixed.into_iter().flatten().chain(extra.iter().copied())
578}