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
use crate::entity::{PrimaryMap, SecondaryMap};
use crate::ir;
use crate::ir::JumpTables;
use crate::ir::{
instructions::BranchInfo, Block, DynamicStackSlot, DynamicStackSlotData, DynamicType,
ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Heap, HeapData, Inst, InstructionData,
JumpTable, JumpTableData, Opcode, SigRef, StackSlot, StackSlotData, Table, TableData, Type,
};
use crate::ir::{DataFlowGraph, Layout, Signature};
use crate::ir::{DynamicStackSlots, SourceLocs, StackSlots};
use crate::isa::CallConv;
use crate::value_label::ValueLabelsRanges;
use crate::write::write_function;
use crate::HashMap;
#[cfg(feature = "enable-serde")]
use alloc::string::String;
use core::fmt;
#[cfg(feature = "enable-serde")]
use serde::de::{Deserializer, Error};
#[cfg(feature = "enable-serde")]
use serde::ser::Serializer;
#[cfg(feature = "enable-serde")]
use serde::{Deserialize, Serialize};
use super::entities::UserExternalNameRef;
use super::extname::UserFuncName;
use super::{RelSourceLoc, SourceLoc, UserExternalName};
#[derive(Copy, Clone, Debug, PartialEq, Hash)]
pub struct VersionMarker;
#[cfg(feature = "enable-serde")]
impl Serialize for VersionMarker {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
crate::VERSION.serialize(serializer)
}
}
#[cfg(feature = "enable-serde")]
impl<'de> Deserialize<'de> for VersionMarker {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let version = String::deserialize(deserializer)?;
if version != crate::VERSION {
return Err(D::Error::custom(&format!(
"Expected a clif ir function for version {}, found one for version {}",
crate::VERSION,
version,
)));
}
Ok(VersionMarker)
}
}
#[derive(Clone)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct FunctionParameters {
base_srcloc: Option<SourceLoc>,
user_named_funcs: PrimaryMap<UserExternalNameRef, UserExternalName>,
user_ext_name_to_ref: HashMap<UserExternalName, UserExternalNameRef>,
}
impl FunctionParameters {
pub fn new() -> Self {
Self {
base_srcloc: None,
user_named_funcs: Default::default(),
user_ext_name_to_ref: Default::default(),
}
}
pub fn base_srcloc(&self) -> SourceLoc {
self.base_srcloc.unwrap_or_default()
}
pub fn ensure_base_srcloc(&mut self, srcloc: SourceLoc) -> SourceLoc {
match self.base_srcloc {
Some(val) => val,
None => {
self.base_srcloc = Some(srcloc);
srcloc
}
}
}
pub fn ensure_user_func_name(&mut self, name: UserExternalName) -> UserExternalNameRef {
if let Some(reff) = self.user_ext_name_to_ref.get(&name) {
*reff
} else {
let reff = self.user_named_funcs.push(name.clone());
self.user_ext_name_to_ref.insert(name, reff);
reff
}
}
pub fn reset_user_func_name(&mut self, index: UserExternalNameRef, name: UserExternalName) {
if let Some(prev_name) = self.user_named_funcs.get_mut(index) {
self.user_ext_name_to_ref.remove(prev_name);
*prev_name = name.clone();
self.user_ext_name_to_ref.insert(name, index);
}
}
pub fn user_named_funcs(&self) -> &PrimaryMap<UserExternalNameRef, UserExternalName> {
&self.user_named_funcs
}
fn clear(&mut self) {
self.base_srcloc = None;
self.user_named_funcs.clear();
self.user_ext_name_to_ref.clear();
}
}
#[derive(Clone, PartialEq, Hash)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct FunctionStencil {
pub version_marker: VersionMarker,
pub signature: Signature,
pub sized_stack_slots: StackSlots,
pub dynamic_stack_slots: DynamicStackSlots,
pub global_values: PrimaryMap<ir::GlobalValue, ir::GlobalValueData>,
pub heaps: PrimaryMap<ir::Heap, ir::HeapData>,
pub tables: PrimaryMap<ir::Table, ir::TableData>,
pub jump_tables: JumpTables,
pub dfg: DataFlowGraph,
pub layout: Layout,
srclocs: SourceLocs,
pub stack_limit: Option<ir::GlobalValue>,
}
impl FunctionStencil {
fn clear(&mut self) {
self.signature.clear(CallConv::Fast);
self.sized_stack_slots.clear();
self.dynamic_stack_slots.clear();
self.global_values.clear();
self.heaps.clear();
self.tables.clear();
self.jump_tables.clear();
self.dfg.clear();
self.layout.clear();
self.srclocs.clear();
self.stack_limit = None;
}
pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable {
self.jump_tables.push(data)
}
pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot {
self.sized_stack_slots.push(data)
}
pub fn create_dynamic_stack_slot(&mut self, data: DynamicStackSlotData) -> DynamicStackSlot {
self.dynamic_stack_slots.push(data)
}
pub fn import_signature(&mut self, signature: Signature) -> SigRef {
self.dfg.signatures.push(signature)
}
pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue {
self.global_values.push(data)
}
pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue {
self.dfg.dynamic_types.get(ty).unwrap().dynamic_scale
}
pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue {
let dyn_ty = self.dynamic_stack_slots.get(dss).unwrap().dyn_ty;
self.get_dyn_scale(dyn_ty)
}
pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type> {
self.dfg
.dynamic_types
.get(ty)
.unwrap_or_else(|| panic!("Undeclared dynamic vector type: {}", ty))
.concrete()
}
pub fn create_heap(&mut self, data: HeapData) -> Heap {
self.heaps.push(data)
}
pub fn create_table(&mut self, data: TableData) -> Table {
self.tables.push(data)
}
pub fn special_param(&self, purpose: ir::ArgumentPurpose) -> Option<ir::Value> {
let entry = self.layout.entry_block().expect("Function is empty");
self.signature
.special_param_index(purpose)
.map(|i| self.dfg.block_params(entry)[i])
}
pub fn collect_debug_info(&mut self) {
self.dfg.collect_debug_info();
}
pub fn change_branch_destination(&mut self, inst: Inst, new_dest: Block) {
match self.dfg[inst].branch_destination_mut() {
None => (),
Some(inst_dest) => *inst_dest = new_dest,
}
}
pub fn rewrite_branch_destination(&mut self, inst: Inst, old_dest: Block, new_dest: Block) {
match self.dfg.analyze_branch(inst) {
BranchInfo::SingleDest(dest, ..) => {
if dest == old_dest {
self.change_branch_destination(inst, new_dest);
}
}
BranchInfo::Table(table, default_dest) => {
self.jump_tables[table].iter_mut().for_each(|entry| {
if *entry == old_dest {
*entry = new_dest;
}
});
if default_dest == Some(old_dest) {
match &mut self.dfg[inst] {
InstructionData::BranchTable { destination, .. } => {
*destination = new_dest;
}
_ => panic!(
"Unexpected instruction {} having default destination",
self.dfg.display_inst(inst)
),
}
}
}
BranchInfo::NotABranch => {}
}
}
pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)> {
let dfg = &self.dfg;
let inst_iter = self.layout.block_insts(block);
let mut inst_iter = inst_iter.skip_while(|&inst| !dfg[inst].opcode().is_branch());
if let Some(_branch) = inst_iter.next() {
if let Some(next) = inst_iter.next() {
match dfg[next].opcode() {
Opcode::Jump => (),
_ => return Err((next, "post-branch instruction not jump")),
}
}
}
Ok(())
}
pub fn is_leaf(&self) -> bool {
self.dfg.signatures.is_empty()
}
pub fn transplant_inst(&mut self, dst: Inst, src: Inst) {
debug_assert_eq!(
self.dfg.inst_results(dst).len(),
self.dfg.inst_results(src).len()
);
debug_assert!(self
.dfg
.inst_results(dst)
.iter()
.zip(self.dfg.inst_results(src))
.all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b)));
self.dfg[dst] = self.dfg[src].clone();
self.layout.remove_inst(src);
}
pub fn fixed_stack_size(&self) -> u32 {
self.sized_stack_slots.values().map(|ss| ss.size).sum()
}
pub(crate) fn rel_srclocs(&self) -> &SecondaryMap<Inst, RelSourceLoc> {
&self.srclocs
}
}
#[derive(Clone)]
#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
pub struct Function {
pub name: UserFuncName,
pub stencil: FunctionStencil,
pub params: FunctionParameters,
}
impl core::ops::Deref for Function {
type Target = FunctionStencil;
fn deref(&self) -> &Self::Target {
&self.stencil
}
}
impl core::ops::DerefMut for Function {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.stencil
}
}
impl Function {
pub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self {
Self {
name,
stencil: FunctionStencil {
version_marker: VersionMarker,
signature: sig,
sized_stack_slots: StackSlots::new(),
dynamic_stack_slots: DynamicStackSlots::new(),
global_values: PrimaryMap::new(),
heaps: PrimaryMap::new(),
tables: PrimaryMap::new(),
jump_tables: PrimaryMap::new(),
dfg: DataFlowGraph::new(),
layout: Layout::new(),
srclocs: SecondaryMap::new(),
stack_limit: None,
},
params: FunctionParameters::new(),
}
}
pub fn clear(&mut self) {
self.stencil.clear();
self.params.clear();
self.name = UserFuncName::default();
}
pub fn new() -> Self {
Self::with_name_signature(Default::default(), Signature::new(CallConv::Fast))
}
pub fn display(&self) -> DisplayFunction<'_> {
DisplayFunction(self, Default::default())
}
pub fn display_with<'a>(
&'a self,
annotations: DisplayFunctionAnnotations<'a>,
) -> DisplayFunction<'a> {
DisplayFunction(self, annotations)
}
pub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc) {
let base = self.params.ensure_base_srcloc(srcloc);
self.stencil.srclocs[inst] = RelSourceLoc::from_base_offset(base, srcloc);
}
pub fn srcloc(&self, inst: Inst) -> SourceLoc {
let base = self.params.base_srcloc();
self.stencil.srclocs[inst].expand(base)
}
pub fn declare_imported_user_function(
&mut self,
name: UserExternalName,
) -> UserExternalNameRef {
self.params.ensure_user_func_name(name)
}
pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef {
self.stencil.dfg.ext_funcs.push(data)
}
}
#[derive(Default)]
pub struct DisplayFunctionAnnotations<'a> {
pub value_ranges: Option<&'a ValueLabelsRanges>,
}
pub struct DisplayFunction<'a>(&'a Function, DisplayFunctionAnnotations<'a>);
impl<'a> fmt::Display for DisplayFunction<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write_function(fmt, self.0)
}
}
impl fmt::Display for Function {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write_function(fmt, self)
}
}
impl fmt::Debug for Function {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write_function(fmt, self)
}
}