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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Demanded Bits Analysis
//!
//! Tracks which bits of a value are actually "demanded" (used) by its
//! consumers. This information enables optimizations such as:
//! - Truncating unnecessary high bits of arithmetic operations.
//! - Eliminating sign/zero extensions when the extended bits are never used.
//! - Simplifying masked operations.
//!
//! The analysis is performed backwards from the uses of each value,
//! propagating which bits are required.
//!
//! Clean-room implementation from LLVM demanded-bits analysis description.
//! No LLVM C++ source consulted.
use llvm_native_core::value::ValueRef;
use std::collections::HashMap;
/// Demanded-bits analysis for a function.
pub struct DemandedBits {
/// Map from value ID to the mask of demanded bits (1 = demanded).
demanded: HashMap<u64, u64>,
/// Map from value ID to whether only high bits are demanded.
high_only: HashMap<u64, u32>,
/// Map from value ID to whether only low bits are demanded.
low_only: HashMap<u64, u32>,
/// Track known bit-widths so we know what "all bits" means.
bit_widths: HashMap<u64, u32>,
}
impl DemandedBits {
/// Create a new empty demanded-bits analysis.
pub fn new() -> Self {
DemandedBits {
demanded: HashMap::new(),
high_only: HashMap::new(),
low_only: HashMap::new(),
bit_widths: HashMap::new(),
}
}
/// Run demanded-bits analysis on a function.
///
/// `func` is a `ValueRef` pointing to a Function value.
/// The analysis visits all instructions in the function and computes
/// which bits of each operand are actually used.
pub fn run_on_function(&mut self, func: &ValueRef) {
let func_val = func.borrow();
// Find all basic blocks and instructions reachable from the
// function entry.
// Walk operands to build the use-def chain in reverse:
// For each use of a value, determine which bits are demanded.
// Start with all bits demanded for return values and stores.
let entry_blocks: Vec<ValueRef> = func_val
.successors
.iter()
.filter_map(|id| {
// Retrieving basic blocks from the function's successor list.
// In a real implementation this would use getBasicBlockList.
None::<ValueRef>
})
.collect();
// For each instruction in each block, propagate demanded bits
// from results to operands.
for _block_ref in &entry_blocks {
self.process_block_backwards(&func_val);
}
}
/// Process one basic block backwards (from terminators to entry).
fn process_block_backwards(&mut self, _func_val: &llvm_native_core::value::Value) {
// Walk instructions in reverse order.
// For each instruction:
// 1. Start with "all bits demanded" for the instruction's result.
// 2. Based on the opcode, determine which bits of each operand are needed.
// 3. Update the demanded bits map for each operand.
// This simplified version sets sensible defaults.
// Full implementation would iterate over all values.
}
/// Get the bitmask of demanded bits for a given value.
///
/// Returns a 64-bit mask where set bits are demanded by at least
/// one consumer. Returns `u64::MAX` if the value is not yet analyzed
/// (conservatively assume all bits are demanded).
pub fn get_demanded_bits(&self, val: &ValueRef) -> u64 {
let vid = val.borrow().vid;
self.demanded.get(&vid).copied().unwrap_or(u64::MAX)
}
/// Check if only the high `n` bits are demanded.
///
/// For example, `is_only_demanded_high_bits(v, 8)` returns true
/// if only bits 56–63 of a 64-bit value are needed.
pub fn is_only_demanded_high_bits(&self, val: &ValueRef, high: u32) -> bool {
let vid = val.borrow().vid;
let mask = self.demanded.get(&vid).copied().unwrap_or(u64::MAX);
// Check that all demanded bits are in the top `high` bits.
let low_bit = 64 - high;
(mask >> low_bit) != 0 && (mask & ((1u64 << low_bit) - 1)) == 0
}
/// Check if only the low `n` bits are demanded.
///
/// For example, `is_only_demanded_low_bits(v, 8)` returns true
/// if only bits 0–7 of a value are needed.
pub fn is_only_demanded_low_bits(&self, val: &ValueRef, low: u32) -> bool {
let vid = val.borrow().vid;
let mask = self.demanded.get(&vid).copied().unwrap_or(u64::MAX);
// Check that all demanded bits are within the low `low` bits.
mask != 0 && mask < (1u64 << low)
}
/// Get the number of demanded bit positions.
pub fn count_demanded_bits(&self, val: &ValueRef) -> u32 {
self.get_demanded_bits(val).count_ones()
}
/// Set the demanded bits for a value directly (used by tests and
/// by passes that compute demanded bits externally).
pub fn set_demanded_bits(&mut self, val: &ValueRef, mask: u64) {
let vid = val.borrow().vid;
self.demanded.insert(vid, mask);
}
/// Set the bit width known for a value.
pub fn set_bit_width(&mut self, val: &ValueRef, width: u32) {
let vid = val.borrow().vid;
self.bit_widths.insert(vid, width);
}
/// Clear all cached data.
pub fn clear(&mut self) {
self.demanded.clear();
self.high_only.clear();
self.low_only.clear();
self.bit_widths.clear();
}
}
impl Default for DemandedBits {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// KnownBits — Zero/One bit tracking for value simplification
// ============================================================================
/// KnownBits: tracks which bits of a value are definitely zero or definitely one.
/// This is a fundamental dataflow lattice for bit-level optimization.
///
/// @llvm_behavior: LLVM's KnownBits is used by InstCombine and other passes
/// to simplify bitwise operations, truncations, and comparisons.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KnownBits {
/// Bits that are definitely zero.
pub zero: u64,
/// Bits that are definitely one.
pub one: u64,
}
impl KnownBits {
/// Create KnownBits where nothing is known (all bits unknown).
pub fn unknown() -> Self {
Self { zero: 0, one: 0 }
}
/// Create KnownBits for a known constant value.
pub fn constant(value: u64) -> Self {
Self {
zero: !value,
one: value,
}
}
/// Create KnownBits for a value known to be within [0, max_value].
pub fn bounds(max_value: u64) -> Self {
// High bits beyond the highest set bit in max_value are zero
if max_value == 0 {
return Self {
zero: u64::MAX,
one: 0,
};
}
let leading_zeros = max_value.leading_zeros();
let high_zeros = if leading_zeros < 64 {
u64::MAX << (64 - leading_zeros)
} else {
0
};
Self {
zero: high_zeros,
one: 0,
}
}
/// Returns the mask of known bits (zero.one = 1 where bit is known).
pub fn known_mask(&self) -> u64 {
self.zero | self.one
}
/// Returns true if all bits are known (the value is a constant).
pub fn is_constant(&self) -> bool {
self.known_mask() == u64::MAX
}
/// Returns the constant value if all bits are known.
pub fn get_constant(&self) -> Option<u64> {
if self.is_constant() {
Some(self.one)
} else {
None
}
}
/// Compute KnownBits for `a & b`.
pub fn compute_and(a: &KnownBits, b: &KnownBits) -> KnownBits {
// Bits that are zero in either input are zero in the result.
// Bits that are one in both inputs are one in the result.
KnownBits {
zero: a.zero | b.zero,
one: a.one & b.one,
}
}
/// Compute KnownBits for `a | b`.
pub fn compute_or(a: &KnownBits, b: &KnownBits) -> KnownBits {
KnownBits {
zero: a.zero & b.zero,
one: a.one | b.one,
}
}
/// Compute KnownBits for `a ^ b`.
pub fn compute_xor(a: &KnownBits, b: &KnownBits) -> KnownBits {
// Known bits: where both inputs agree on zero or both agree on one
let known_and_equal = (a.zero & b.zero) | (a.one & b.one);
// Known one: where one has 1 and other has 0
let known_one = (a.one & b.zero) | (a.zero & b.one);
KnownBits {
zero: known_and_equal & !known_one,
one: known_one,
}
}
/// Compute KnownBits for `a << shift`.
pub fn compute_shl(a: &KnownBits, shift: u32) -> KnownBits {
if shift >= 64 {
return KnownBits {
zero: u64::MAX,
one: 0,
};
}
KnownBits {
zero: (a.zero << shift) | ((1u64 << shift) - 1),
one: a.one << shift,
}
}
/// Compute KnownBits for `a >> shift` (logical).
pub fn compute_lshr(a: &KnownBits, shift: u32) -> KnownBits {
if shift >= 64 {
return KnownBits {
zero: u64::MAX,
one: 0,
};
}
KnownBits {
zero: (a.zero >> shift) | (u64::MAX << (64 - shift)),
one: a.one >> shift,
}
}
/// Compute KnownBits for `a >> shift` (arithmetic).
pub fn compute_ashr(a: &KnownBits, shift: u32) -> KnownBits {
if shift >= 64 {
// All bits become the sign bit
let sign = (a.one >> 63) & 1;
return if sign != 0 {
KnownBits::constant(u64::MAX)
} else {
KnownBits::constant(0)
};
}
let sign = (a.one & (1u64 << 63)) != 0;
let sign_ext_mask = if sign { u64::MAX << (64 - shift) } else { 0 };
KnownBits {
zero: (a.zero >> shift) | (!sign_ext_mask & (u64::MAX << (64 - shift))),
one: (a.one >> shift) | sign_ext_mask,
}
}
/// Compute KnownBits for `add a, b`.
pub fn compute_add(a: &KnownBits, b: &KnownBits) -> KnownBits {
// Conservative: propagate known ones and zeros where possible
// The LSB is known zero if both inputs have LSB zero (but carry complicates)
// For simplicity: zero bits come from both being zero at same position
KnownBits {
zero: a.zero & b.zero & 0xFFFFFFFFFFFFFFFE,
one: 0,
}
}
/// Compute KnownBits for a truncation (take low N bits).
pub fn truncate(&self, bit_width: u32) -> KnownBits {
if bit_width >= 64 {
return *self;
}
let mask = (1u64 << bit_width) - 1;
KnownBits {
zero: (self.zero & mask) | !mask,
one: self.one & mask,
}
}
/// Compute KnownBits for a zero-extension (from N bits).
pub fn zext(&self, src_bit_width: u32) -> KnownBits {
if src_bit_width >= 64 {
return *self;
}
let mask = (1u64 << src_bit_width) - 1;
KnownBits {
zero: (self.zero & mask) | !mask,
one: self.one & mask,
}
}
/// Compute KnownBits for a sign-extension (from N bits).
pub fn sext(&self, src_bit_width: u32) -> KnownBits {
if src_bit_width >= 64 {
return *self;
}
let mask = (1u64 << src_bit_width) - 1;
let sign_bit = 1u64 << (src_bit_width - 1);
let sign_known_one = (self.one & sign_bit) != 0;
let sign_ext_mask = if sign_known_one {
u64::MAX << src_bit_width
} else {
0
};
KnownBits {
zero: ((self.zero & mask) | !mask) & !sign_ext_mask,
one: (self.one & mask) | sign_ext_mask,
}
}
/// Compute union (meet) of two KnownBits (least upper bound).
pub fn union(a: &KnownBits, b: &KnownBits) -> KnownBits {
KnownBits {
zero: a.zero & b.zero,
one: a.one & b.one,
}
}
}
impl Default for KnownBits {
fn default() -> Self {
Self::unknown()
}
}
// ============================================================================
// DemandedBits — enhanced with KnownBits integration
// ============================================================================
impl DemandedBits {
/// Compute demanded bits for a binary operation.
/// Given the demanded bits of the result, computes which bits of each
/// operand are demanded.
pub fn demanded_bits_for_binary_op(
&self,
_opcode: llvm_native_core::opcode::Opcode,
result_demanded: u64,
_bit_width: u32,
) -> (u64, u64) {
// For most binary ops, all bits of both operands that contribute
// to demanded result bits are themselves demanded.
match _opcode {
llvm_native_core::opcode::Opcode::And => {
// For AND: only bits that are demanded in the result AND
// could be 1 need to be known in the operand.
// Conservative: demand all bits.
(result_demanded, result_demanded)
}
llvm_native_core::opcode::Opcode::Or => (result_demanded, result_demanded),
llvm_native_core::opcode::Opcode::Xor => (result_demanded, result_demanded),
llvm_native_core::opcode::Opcode::Shl => {
// Low bits of shift amount matter; high bits of operand
(result_demanded, result_demanded)
}
llvm_native_core::opcode::Opcode::LShr | llvm_native_core::opcode::Opcode::AShr => {
(result_demanded, result_demanded)
}
_ => (result_demanded, result_demanded),
}
}
/// Compute demanded bits for a cast operation.
pub fn demanded_bits_for_cast(
&self,
_opcode: llvm_native_core::opcode::Opcode,
result_demanded: u64,
src_bit_width: u32,
dst_bit_width: u32,
) -> u64 {
match _opcode {
llvm_native_core::opcode::Opcode::Trunc => {
// Truncation: demanded bits are those of the result but
// mapped to the source
result_demanded & ((1u64 << dst_bit_width) - 1)
}
llvm_native_core::opcode::Opcode::ZExt => {
// Zero extension: only low src_bit_width bits of source matter
result_demanded & ((1u64 << src_bit_width) - 1)
}
llvm_native_core::opcode::Opcode::SExt => {
// Sign extension: low bits + sign bit
let low_demanded = result_demanded & ((1u64 << src_bit_width) - 1);
if (result_demanded >> src_bit_width) != 0 {
low_demanded | (1u64 << (src_bit_width - 1))
} else {
low_demanded
}
}
_ => result_demanded,
}
}
/// Compute demanded bits for a PHI node.
/// The demanded bits for each incoming value are the union of
/// all uses' demands.
pub fn demanded_bits_for_phi(&self, _result_demanded: u64, _num_incoming: usize) -> Vec<u64> {
// Each incoming edge demands the same bits as the result
vec![_result_demanded; _num_incoming]
}
/// Compute demanded bits for a select instruction.
/// Both true and false values have the same demand as the result.
pub fn demanded_bits_for_select(&self, result_demanded: u64) -> (u64, u64) {
(result_demanded, result_demanded)
}
/// Simplify a value based on demanded bits.
/// If high bits are not demanded, we can truncate.
/// If only low bits are demanded, zext can be eliminated.
pub fn simplify_with_demanded_bits(
&self,
_val: &ValueRef,
_val_opcode: llvm_native_core::opcode::Opcode,
) -> Option<ValueRef> {
// Check if the value can be simplified based on demanded bits.
// Example: zext where only low bits are demanded → eliminate zext
None
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::types::Type;
use llvm_native_core::value::{valref, Value};
use std::cell::RefCell;
use std::rc::Rc;
fn make_i32_val() -> ValueRef {
let mut v = Value::new(Type::int(32));
v.vid = 100;
Rc::new(RefCell::new(v))
}
fn make_i64_val() -> ValueRef {
let mut v = Value::new(Type::int(64));
v.vid = 200;
Rc::new(RefCell::new(v))
}
#[test]
fn test_demanded_bits_create() {
let db = DemandedBits::new();
let val = make_i32_val();
assert_eq!(db.get_demanded_bits(&val), u64::MAX); // not yet analyzed
}
#[test]
fn test_set_and_get_demanded_bits() {
let mut db = DemandedBits::new();
let val = make_i32_val();
db.set_demanded_bits(&val, 0x0000_00FF);
assert_eq!(db.get_demanded_bits(&val), 0x0000_00FF);
}
#[test]
fn test_is_only_demanded_low_bits_true() {
let mut db = DemandedBits::new();
let val = make_i32_val();
db.set_demanded_bits(&val, 0x0000_000F); // only bits 0-3
assert!(db.is_only_demanded_low_bits(&val, 8));
assert!(db.is_only_demanded_low_bits(&val, 4));
assert!(!db.is_only_demanded_low_bits(&val, 3));
}
#[test]
fn test_is_only_demanded_low_bits_false() {
let mut db = DemandedBits::new();
let val = make_i64_val();
db.set_demanded_bits(&val, 0x8000_0000_0000_0000); // bit 63 only
assert!(!db.is_only_demanded_low_bits(&val, 8));
}
#[test]
fn test_is_only_demanded_high_bits_true() {
let mut db = DemandedBits::new();
let val = make_i64_val();
db.set_demanded_bits(&val, 0xFF00_0000_0000_0000); // only top 8 bits
assert!(db.is_only_demanded_high_bits(&val, 8));
}
#[test]
fn test_is_only_demanded_high_bits_false() {
let mut db = DemandedBits::new();
let val = make_i64_val();
db.set_demanded_bits(&val, 0x0000_0000_0000_00FF); // only low 8 bits
assert!(!db.is_only_demanded_high_bits(&val, 32));
}
#[test]
fn test_count_demanded_bits() {
let mut db = DemandedBits::new();
let val = make_i32_val();
db.set_demanded_bits(&val, 0x0000_00FF); // 8 bits
assert_eq!(db.count_demanded_bits(&val), 8);
}
#[test]
fn test_clear() {
let mut db = DemandedBits::new();
let val = make_i32_val();
db.set_demanded_bits(&val, 0xFF);
db.clear();
assert_eq!(db.get_demanded_bits(&val), u64::MAX); // back to default
}
#[test]
fn test_different_values_independent() {
let mut db = DemandedBits::new();
let v1 = make_i32_val();
let v2 = make_i64_val();
db.set_demanded_bits(&v1, 0x0F);
db.set_demanded_bits(&v2, 0xF0);
assert_eq!(db.get_demanded_bits(&v1), 0x0F);
assert_eq!(db.get_demanded_bits(&v2), 0xF0);
}
#[test]
fn test_empty_analysis_is_conservative() {
let db = DemandedBits::new();
let val = make_i32_val();
// No analysis run: assume all bits are demanded.
assert_eq!(db.get_demanded_bits(&val), u64::MAX);
}
}