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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//! Methods of [`State`] for specializing values through comparison operations.

use super::*;

impl State {
    /// Try to restrict the input variables of `expression` on `self`
    /// so that `expression` only evaluates to values represented by the given `result`.
    ///
    /// If `expression` cannot evaluate to any value represented by `self`, return an error.
    ///
    /// This function may restrict to upper bounds of possible values
    /// if the restriction cannot be made exact,
    /// i.e. after calling this function the state may still contain values
    /// for which `expression` does not evaluate to values represented by `result`.
    pub fn specialize_by_expression_result(
        &mut self,
        expression: &Expression,
        result: Data,
    ) -> Result<(), Error> {
        if let Expression::Var(var) = expression {
            self.set_register(var, self.eval(expression).intersect(&result)?);
            Ok(())
        } else if let Expression::BinOp { op, lhs, rhs } = expression {
            self.specialize_by_binop_expression_result(op, lhs, rhs, result)
        } else {
            match expression {
                Expression::Var(_) => panic!(),
                Expression::Const(input_bitvec) => {
                    if let Ok(result_bitvec) = result.try_to_bitvec() {
                        if *input_bitvec == result_bitvec {
                            Ok(())
                        } else {
                            Err(anyhow!("Unsatisfiable state"))
                        }
                    } else {
                        Ok(())
                    }
                }
                Expression::BinOp { .. } => {
                    panic!() // Already handled above
                }
                Expression::UnOp { op, arg } => {
                    use UnOpType::*;
                    match op {
                        IntNegate | BoolNegate | Int2Comp => {
                            let intermediate_result = result.un_op(*op);
                            self.specialize_by_expression_result(arg, intermediate_result)
                        }
                        _ => Ok(()),
                    }
                }
                Expression::Cast { op, size: _, arg } => match op {
                    CastOpType::IntZExt | CastOpType::IntSExt => {
                        let intermediate_result = result.subpiece(ByteSize::new(0), arg.bytesize());
                        self.specialize_by_expression_result(arg, intermediate_result)
                    }
                    _ => Ok(()),
                },
                Expression::Unknown {
                    description: _,
                    size: _,
                } => Ok(()),
                Expression::Subpiece {
                    low_byte,
                    size,
                    arg,
                } => {
                    if *low_byte == ByteSize::new(0) {
                        if let Some(arg_value) = self.eval(expression).get_if_absolute_value() {
                            if arg_value.fits_into_size(*size) {
                                let intermediate_result =
                                    result.cast(CastOpType::IntSExt, arg.bytesize());
                                return self
                                    .specialize_by_expression_result(arg, intermediate_result);
                            }
                        }
                    }
                    Ok(())
                }
            }
        }
    }

    /// Try to restrict the input variables of the given binary operation
    /// so that it only evaluates to the given `result_bitvec`.
    fn specialize_by_binop_expression_result(
        &mut self,
        op: &BinOpType,
        lhs: &Expression,
        rhs: &Expression,
        result: Data,
    ) -> Result<(), Error> {
        match op {
            BinOpType::IntAdd => {
                let intermediate_result = result.clone() - self.eval(lhs).without_widening_hints();
                self.specialize_by_expression_result(rhs, intermediate_result)?;

                let intermediate_result = result - self.eval(rhs).without_widening_hints();
                self.specialize_by_expression_result(lhs, intermediate_result)?;

                return Ok(());
            }
            BinOpType::IntSub => {
                let intermediate_result: Data =
                    self.eval(lhs).without_widening_hints() - result.clone();
                self.specialize_by_expression_result(rhs, intermediate_result)?;

                let intermediate_result = result + self.eval(rhs).without_widening_hints();
                self.specialize_by_expression_result(lhs, intermediate_result)?;

                return Ok(());
            }
            _ => (),
        }
        if let Ok(result_bitvec) = result.try_to_bitvec() {
            match op {
                BinOpType::IntXOr | BinOpType::BoolXOr => {
                    if let Ok(bitvec) = self.eval(lhs).try_to_bitvec() {
                        self.specialize_by_expression_result(
                            rhs,
                            (result_bitvec.clone() ^ &bitvec).into(),
                        )?;
                    }
                    if let Ok(bitvec) = self.eval(rhs).try_to_bitvec() {
                        self.specialize_by_expression_result(
                            lhs,
                            (result_bitvec ^ &bitvec).into(),
                        )?;
                    }
                    Ok(())
                }
                BinOpType::IntOr | BinOpType::BoolOr => {
                    if result_bitvec.is_zero() {
                        self.specialize_by_expression_result(lhs, result_bitvec.clone().into())?;
                        self.specialize_by_expression_result(rhs, result_bitvec.into())
                    } else if self
                        .eval(lhs)
                        .try_to_bitvec()
                        .map_or(false, |bitvec| bitvec.is_zero())
                    {
                        self.specialize_by_expression_result(rhs, result_bitvec.into())
                    } else if self
                        .eval(rhs)
                        .try_to_bitvec()
                        .map_or(false, |bitvec| bitvec.is_zero())
                    {
                        self.specialize_by_expression_result(lhs, result_bitvec.into())
                    } else {
                        Ok(())
                    }
                }
                BinOpType::BoolAnd => {
                    if !result_bitvec.is_zero() {
                        self.specialize_by_expression_result(lhs, result_bitvec.clone().into())?;
                        self.specialize_by_expression_result(rhs, result_bitvec.into())
                    } else if self
                        .eval(lhs)
                        .try_to_bitvec()
                        .map_or(false, |bitvec| !bitvec.is_zero())
                    {
                        self.specialize_by_expression_result(rhs, result_bitvec.into())
                    } else if self
                        .eval(rhs)
                        .try_to_bitvec()
                        .map_or(false, |bitvec| !bitvec.is_zero())
                    {
                        self.specialize_by_expression_result(lhs, result_bitvec.into())
                    } else {
                        Ok(())
                    }
                }
                BinOpType::IntEqual | BinOpType::IntNotEqual => {
                    match (op, !result_bitvec.is_zero()) {
                        (BinOpType::IntEqual, true) | (BinOpType::IntNotEqual, false) => {
                            // lhs == rhs
                            if let Ok(bitvec) = self.eval(lhs).try_to_bitvec() {
                                self.specialize_by_expression_result(rhs, bitvec.into())?;
                            }
                            if let Ok(bitvec) = self.eval(rhs).try_to_bitvec() {
                                self.specialize_by_expression_result(lhs, bitvec.into())?;
                            }
                            // Also specialize cases of pointer comparisons
                            self.specialize_pointer_comparison(&BinOpType::IntEqual, lhs, rhs)?;
                            Ok(())
                        }
                        (BinOpType::IntEqual, false) | (BinOpType::IntNotEqual, true) => {
                            // lhs != rhs
                            if let Ok(bitvec) = self.eval(lhs).try_to_bitvec() {
                                let new_result = self
                                    .eval(rhs)
                                    .without_widening_hints()
                                    .add_not_equal_bound(&bitvec)?;
                                self.specialize_by_expression_result(rhs, new_result)?;
                            }
                            if let Ok(bitvec) = self.eval(rhs).try_to_bitvec() {
                                let new_result = self
                                    .eval(lhs)
                                    .without_widening_hints()
                                    .add_not_equal_bound(&bitvec)?;
                                self.specialize_by_expression_result(lhs, new_result)?;
                            }
                            // Also specialize cases of pointer comparisons
                            self.specialize_pointer_comparison(&BinOpType::IntNotEqual, lhs, rhs)?;
                            Ok(())
                        }
                        _ => panic!(),
                    }
                }
                BinOpType::IntSLess
                | BinOpType::IntLess
                | BinOpType::IntLessEqual
                | BinOpType::IntSLessEqual => {
                    use BinOpType::*;
                    let mut op = *op;
                    let (mut left_expr, mut right_expr) = (lhs, rhs);
                    if result_bitvec.is_zero() {
                        std::mem::swap(&mut left_expr, &mut right_expr);
                        op = match op {
                            IntSLess => IntSLessEqual,
                            IntSLessEqual => IntSLess,
                            IntLess => IntLessEqual,
                            IntLessEqual => IntLess,
                            _ => panic!(),
                        }
                    }
                    self.specialize_by_comparison_op(&op, left_expr, right_expr)
                }
                _ => {
                    let original_expression = Expression::BinOp {
                        lhs: Box::new(lhs.clone()),
                        op: *op,
                        rhs: Box::new(rhs.clone()),
                    };
                    if let Ok(interval) = self.eval(&original_expression).try_to_interval() {
                        if !interval.contains(&result_bitvec) {
                            Err(anyhow!("Unsatisfiable bound"))
                        } else {
                            Ok(())
                        }
                    } else {
                        Ok(())
                    }
                }
            }
        } else {
            Ok(())
        }
    }

    /// If both `lhs` and `rhs` evaluate to pointers and `op` is a comparison operator that evaluates to `true`,
    /// specialize the input pointers accordingly.
    ///
    /// Note that the current implementation only specializes for `==` and `!=` operators
    /// and only if the pointers point to the same unique memory object.
    fn specialize_pointer_comparison(
        &mut self,
        op: &BinOpType,
        lhs: &Expression,
        rhs: &Expression,
    ) -> Result<(), Error> {
        let (lhs_pointer, rhs_pointer) = (
            self.eval(lhs).without_widening_hints(),
            self.eval(rhs).without_widening_hints(),
        );
        match (
            lhs_pointer.get_if_unique_target(),
            rhs_pointer.get_if_unique_target(),
        ) {
            (Some((lhs_id, lhs_offset)), Some((rhs_id, rhs_offset))) if lhs_id == rhs_id => {
                if !(self.memory.is_unique_object(lhs_id)?) {
                    // Since the pointers may or may not point to different instances referenced by the same ID we cannot compare them.
                    return Ok(());
                }
                if *op == BinOpType::IntEqual {
                    let specialized_offset = lhs_offset.clone().intersect(rhs_offset)?;
                    let specialized_domain: Data =
                        Data::from_target(lhs_id.clone(), specialized_offset);
                    self.specialize_by_expression_result(lhs, specialized_domain.clone())?;
                    self.specialize_by_expression_result(rhs, specialized_domain)?;
                } else if *op == BinOpType::IntNotEqual {
                    if let Ok(rhs_offset_bitvec) = rhs_offset.try_to_bitvec() {
                        let new_lhs_offset =
                            lhs_offset.clone().add_not_equal_bound(&rhs_offset_bitvec)?;
                        self.specialize_by_expression_result(
                            lhs,
                            Data::from_target(lhs_id.clone(), new_lhs_offset),
                        )?;
                    }
                    if let Ok(lhs_offset_bitvec) = lhs_offset.try_to_bitvec() {
                        let new_rhs_offset =
                            rhs_offset.clone().add_not_equal_bound(&lhs_offset_bitvec)?;
                        self.specialize_by_expression_result(
                            rhs,
                            Data::from_target(rhs_id.clone(), new_rhs_offset),
                        )?;
                    }
                }
            }
            _ => (), // Other cases not handled, since it depends on the meaning of pointer IDs, which may change in the future.
        }
        Ok(())
    }

    /// Try to restrict the input variables of the given comparison operation
    /// (signed and unsigned versions of `<` and `<=`)
    /// so that the comparison evaluates to `true`.
    fn specialize_by_comparison_op(
        &mut self,
        op: &BinOpType,
        lhs: &Expression,
        rhs: &Expression,
    ) -> Result<(), Error> {
        use BinOpType::*;
        if let Ok(mut lhs_bound) = self.eval(lhs).try_to_bitvec() {
            match op {
                IntSLess => {
                    if lhs_bound == Bitvector::signed_max_value(lhs_bound.width()) {
                        return Err(anyhow!("Unsatisfiable bound"));
                    }
                    lhs_bound += &Bitvector::one(lhs_bound.width());
                    let new_result = self
                        .eval(rhs)
                        .without_widening_hints()
                        .add_signed_greater_equal_bound(&lhs_bound)?;
                    self.specialize_by_expression_result(rhs, new_result)?;
                }
                IntSLessEqual => {
                    let new_result = self
                        .eval(rhs)
                        .without_widening_hints()
                        .add_signed_greater_equal_bound(&lhs_bound)?;
                    self.specialize_by_expression_result(rhs, new_result)?;
                }
                IntLess => {
                    if lhs_bound == Bitvector::unsigned_max_value(lhs_bound.width()) {
                        return Err(anyhow!("Unsatisfiable bound"));
                    }
                    lhs_bound += &Bitvector::one(lhs_bound.width());
                    let new_result = self
                        .eval(rhs)
                        .without_widening_hints()
                        .add_unsigned_greater_equal_bound(&lhs_bound)?;
                    self.specialize_by_expression_result(rhs, new_result)?;
                }
                IntLessEqual => {
                    let new_result = self
                        .eval(rhs)
                        .without_widening_hints()
                        .add_unsigned_greater_equal_bound(&lhs_bound)?;
                    self.specialize_by_expression_result(rhs, new_result)?;
                }
                _ => panic!(),
            }
        }
        if let Ok(mut rhs_bound) = self.eval(rhs).try_to_bitvec() {
            match op {
                IntSLess => {
                    if rhs_bound == Bitvector::signed_min_value(rhs_bound.width()) {
                        return Err(anyhow!("Unsatisfiable bound"));
                    }
                    rhs_bound -= &Bitvector::one(rhs_bound.width());
                    let new_result = self
                        .eval(lhs)
                        .without_widening_hints()
                        .add_signed_less_equal_bound(&rhs_bound)?;
                    self.specialize_by_expression_result(lhs, new_result)?;
                }
                IntSLessEqual => {
                    let new_result = self
                        .eval(lhs)
                        .without_widening_hints()
                        .add_signed_less_equal_bound(&rhs_bound)?;
                    self.specialize_by_expression_result(lhs, new_result)?;
                }
                IntLess => {
                    if rhs_bound == Bitvector::zero(rhs_bound.width()) {
                        return Err(anyhow!("Unsatisfiable bound"));
                    }
                    rhs_bound -= &Bitvector::one(rhs_bound.width());
                    let new_result = self
                        .eval(lhs)
                        .without_widening_hints()
                        .add_unsigned_less_equal_bound(&rhs_bound)?;
                    self.specialize_by_expression_result(lhs, new_result)?;
                }
                IntLessEqual => {
                    let new_result = self
                        .eval(lhs)
                        .without_widening_hints()
                        .add_unsigned_less_equal_bound(&rhs_bound)?;
                    self.specialize_by_expression_result(lhs, new_result)?;
                }
                _ => panic!(),
            }
        }
        Ok(())
    }
}