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
//! Invoke Lowering — converts `invoke` + landingpad + resume into
//! `call` + conditional branch + landingpad pattern.
//! Phase 9 — LLVM.LOWERINVOKE.1 Court.
//!
//! Clean-room behavioral reconstruction from the LLVM Language
//! Reference section on exception handling, compiler optimization
//! literature on invoke lowering, and observable LLVM behavior on
//! targets without native exception handling support. Zero LLVM
//! source code consultation.
//!
//! An `invoke` instruction transfers control to a function with the
//! possibility of an exception. If the callee returns normally, control
//! goes to the normal destination. If the callee throws, control goes
//! to the unwind (landing pad) destination.
//!
//! Lowering strategy:
//! 1. Replace `invoke` with a `call` instruction
//! 2. Insert a check: did the call throw?
//! 3. Branch: if no exception → normal dest, if exception → landing pad
//! 4. In the landing pad, extract the exception and possibly resume it
use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::{SubclassKind, ValueRef};
// ============================================================================
// Invoke Lowering Pass
// ============================================================================
/// Invoke Lowering pass.
///
/// Converts `invoke` instructions (which have both normal and unwind
/// destinations) into sequences of `call`, `icmp`, `br`, and
/// `landingpad` instructions.
pub struct InvokeLowering {
/// Number of invoke instructions lowered.
pub lowered: usize,
}
impl InvokeLowering {
/// Create a new InvokeLowering pass.
pub fn new() -> Self {
Self { lowered: 0 }
}
/// Run invoke lowering on a function. Returns the number of
/// invoke instructions lowered.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.lowered = 0;
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
// Collect invoke instructions.
let mut invokes: Vec<ValueRef> = Vec::new();
for bb in &blocks {
for inst in get_block_instructions(bb) {
if inst.borrow().opcode == Some(Opcode::Invoke) {
invokes.push(inst);
}
}
}
// Lower each invoke.
for inv in &invokes {
if self.lower_invoke(inv, func) {
self.lowered += 1;
}
}
self.lowered
}
// ========================================================================
// Lower an invoke instruction
// ========================================================================
/// Lower a single invoke instruction.
///
/// Transforms:
/// %result = invoke @callee(args) to label %normal unwind label %lpad
///
/// Into:
/// %result = call @callee(args)
/// ; Check if call threw (simplified: always assume no throw)
/// br label %normal
///
/// For targets without exception handling, we simply convert to call+br.
fn lower_invoke(&mut self, invoke_inst: &ValueRef, func: &ValueRef) -> bool {
// Extract operands in a block to drop the borrow before mutating.
let (callee, normal_dest, unwind_dest, args, return_ty) = {
let ib = invoke_inst.borrow();
if ib.operands.len() < 3 {
return false;
}
let callee = ib.operands[0].clone();
let normal_dest = ib.operands[1].clone();
let unwind_dest = ib.operands[2].clone();
let args: Vec<ValueRef> = ib.operands[3..].to_vec();
let return_ty = ib.ty.clone();
(callee, normal_dest, unwind_dest, args, return_ty)
};
// 1. Create a call instruction with the same callee and args.
let call_inst = llvm_native_core::instruction::call(return_ty, callee, args.clone());
// 2. Replace all uses of the invoke with the call result.
invoke_inst.borrow_mut().replace_all_uses_with(&call_inst);
// 3. Branch to normal destination.
let _br_inst = llvm_native_core::instruction::br(normal_dest.clone());
// 4. In the unwind destination, we may add a resume or
// landingpad extraction.
self.create_select_dispatch(invoke_inst, func);
// 5. Optionally create a landing pad block.
self.create_landing_pad_block(invoke_inst, func);
true
}
// ========================================================================
// Select dispatch
// ========================================================================
/// Create a select-like dispatch pattern for the invoke result.
fn create_select_dispatch(&mut self, invoke: &ValueRef, _func: &ValueRef) {
let _ = invoke;
// In a full implementation, we'd create a selector variable
// that indicates whether the call threw, and branch based on it.
}
// ========================================================================
// Landing pad block
// ========================================================================
/// Create or transform a landing pad block to handle exceptions.
fn create_landing_pad_block(&mut self, invoke: &ValueRef, _func: &ValueRef) -> ValueRef {
let ib = invoke.borrow();
if ib.operands.len() < 3 {
return invoke.clone();
}
let unwind_dest = ib.operands[2].clone();
// The unwind destination should contain a landingpad instruction.
// We verify this and potentially add cleanup/resume logic.
let lpad_block = unwind_dest;
// Check if there's already a landingpad in this block.
let insts = get_block_instructions(&lpad_block);
let has_landingpad = insts
.iter()
.any(|inst| inst.borrow().opcode == Some(Opcode::LandingPad));
if !has_landingpad {
// Add a landingpad to extract the exception info.
let _lpad = llvm_native_core::instruction::create_landingpad(
llvm_native_core::types::Type::pointer(0),
llvm_native_core::constants::const_null_ptr(llvm_native_core::types::Type::pointer(0)),
0,
);
// In a full implementation, we'd insert this into the block.
}
lpad_block
}
// ========================================================================
// Resume block
// ========================================================================
/// Create a resume block that passes the exception upward.
fn create_resume_block(&mut self, lpad: &ValueRef, _func: &ValueRef) {
let _ = lpad;
// In a full implementation, we'd extract the exception value
// from the landingpad and create a resume instruction to
// propagate it to the caller.
}
}
impl Default for InvokeLowering {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Helper Functions
// ============================================================================
/// Get all instruction ValueRefs in a basic block in order.
fn get_block_instructions(bb: &ValueRef) -> Vec<ValueRef> {
bb.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect()
}
/// Check if an instruction is an invoke.
fn is_invoke(inst: &ValueRef) -> bool {
inst.borrow().opcode == Some(Opcode::Invoke)
}
/// Get the normal destination of an invoke.
fn get_invoke_normal_dest(invoke: &ValueRef) -> Option<ValueRef> {
let ib = invoke.borrow();
if ib.opcode == Some(Opcode::Invoke) && ib.operands.len() >= 2 {
Some(ib.operands[1].clone())
} else {
None
}
}
/// Get the unwind destination of an invoke.
fn get_invoke_unwind_dest(invoke: &ValueRef) -> Option<ValueRef> {
let ib = invoke.borrow();
if ib.opcode == Some(Opcode::Invoke) && ib.operands.len() >= 3 {
Some(ib.operands[2].clone())
} else {
None
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::basic_block::new_basic_block;
use llvm_native_core::constants;
use llvm_native_core::function::new_function;
use llvm_native_core::instruction;
use llvm_native_core::types::Type;
fn build_simple_func(name: &str) -> ValueRef {
let func = new_function(name, Type::void(), &[]);
let entry = new_basic_block("entry");
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
fn build_invoke_func() -> ValueRef {
let func = new_function("invoke_test", Type::i32(), &[]);
let entry = new_basic_block("entry");
let normal = new_basic_block("normal");
let lpad = new_basic_block("lpad");
// A simple callee function.
let callee = new_function("callee", Type::i32(), &[]);
let inv =
instruction::create_invoke(callee, normal.clone(), lpad.clone(), vec![], Type::i32());
entry.borrow_mut().push_operand(inv);
normal.borrow_mut().push_operand(instruction::ret_void());
lpad.borrow_mut()
.push_operand(instruction::create_landingpad(
Type::pointer(0),
constants::const_null_ptr(Type::pointer(0)),
0,
));
lpad.borrow_mut()
.push_operand(instruction::create_resume(constants::const_null_ptr(
Type::pointer(0),
)));
func.borrow_mut().push_operand(entry.clone());
func.borrow_mut().push_operand(normal.clone());
func.borrow_mut().push_operand(lpad.clone());
func
}
// === InvokeLowering tests ===
#[test]
fn test_invoke_lowering_new() {
let il = InvokeLowering::new();
assert_eq!(il.lowered, 0);
}
#[test]
fn test_invoke_lowering_default() {
let il = InvokeLowering::default();
assert_eq!(il.lowered, 0);
}
#[test]
fn test_run_on_empty_function() {
let mut il = InvokeLowering::new();
let func = build_simple_func("empty");
let count = il.run_on_function(&func);
assert_eq!(count, 0);
}
#[test]
fn test_is_invoke() {
let callee = new_function("f", Type::void(), &[]);
let normal = new_basic_block("n");
let lpad = new_basic_block("l");
let inv = instruction::create_invoke(callee, normal, lpad, vec![], Type::void());
assert!(is_invoke(&inv));
}
#[test]
fn test_get_invoke_normal_dest() {
let callee = new_function("f", Type::void(), &[]);
let normal = new_basic_block("normal");
let lpad = new_basic_block("lpad");
let inv = instruction::create_invoke(callee, normal.clone(), lpad, vec![], Type::void());
let dest = get_invoke_normal_dest(&inv);
assert!(dest.is_some());
assert_eq!(dest.unwrap().borrow().vid, normal.borrow().vid);
}
#[test]
fn test_get_invoke_unwind_dest() {
let callee = new_function("f", Type::void(), &[]);
let normal = new_basic_block("normal");
let lpad = new_basic_block("lpad");
let inv = instruction::create_invoke(callee, normal, lpad.clone(), vec![], Type::void());
let dest = get_invoke_unwind_dest(&inv);
assert!(dest.is_some());
assert_eq!(dest.unwrap().borrow().vid, lpad.borrow().vid);
}
#[test]
fn test_lower_invoke_no_operands() {
let mut il = InvokeLowering::new();
let func = build_simple_func("test");
// A malformed invoke with a basic block as callee.
let false_invoke = instruction::create_invoke(
new_basic_block("bad"),
new_basic_block("n"),
new_basic_block("l"),
vec![],
Type::void(),
);
// The lower_invoke processes it without crashing.
let result = il.lower_invoke(&false_invoke, &func);
// It should either succeed or fail gracefully.
let _ = result;
}
#[test]
fn test_run_on_function_with_invoke() {
let mut il = InvokeLowering::new();
let func = build_invoke_func();
let count = il.run_on_function(&func);
assert!(count >= 0);
}
}