Skip to content

Commit 2c75c5d

Browse files
committed
Update to new APIs on Cranelift side.
1 parent 64f0757 commit 2c75c5d

File tree

8 files changed

+96
-44
lines changed

8 files changed

+96
-44
lines changed

crates/cranelift/src/compiled_function.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ use cranelift_codegen::{
33
Final, MachBufferFinalized, MachBufferFrameLayout, MachSrcLoc, ValueLabelsRanges, ir,
44
isa::unwind::CfaUnwindInfo, isa::unwind::UnwindInfo,
55
};
6-
use wasmtime_environ::{FilePos, InstructionAddressMap, PrimaryMap, TrapInformation};
6+
use wasmtime_environ::{
7+
FilePos, FrameStateSlotBuilder, InstructionAddressMap, PrimaryMap, TrapInformation,
8+
};
79

810
#[derive(Debug, Clone, PartialEq, Eq, Default)]
911
/// Metadata to translate from binary offsets back to the original
@@ -61,6 +63,8 @@ pub struct CompiledFunction {
6163
/// The metadata for the compiled function, including unwind information
6264
/// the function address map.
6365
metadata: CompiledFunctionMetadata,
66+
/// Debug metadata for the top-level function's state slot.
67+
pub debug_slot_descriptor: Option<FrameStateSlotBuilder>,
6468
}
6569

6670
impl CompiledFunction {
@@ -77,6 +81,7 @@ impl CompiledFunction {
7781
name_map,
7882
alignment,
7983
metadata: Default::default(),
84+
debug_slot_descriptor: None,
8085
}
8186
}
8287

crates/cranelift/src/compiler.rs

Lines changed: 49 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ use wasmparser::{FuncValidatorAllocations, FunctionBody};
3434
use wasmtime_environ::obj::{ELF_WASMTIME_EXCEPTIONS, ELF_WASMTIME_FRAMES};
3535
use wasmtime_environ::{
3636
Abi, AddressMapSection, BuiltinFunctionIndex, CacheStore, CompileError, CompiledFunctionBody,
37-
DefinedFuncIndex, FlagValue, FrameInstPos, FrameStackShape, FrameTableBuilder, FuncKey,
38-
FunctionBodyData, FunctionLoc, HostCall, InliningCompiler, ModuleTranslation,
39-
ModuleTypesBuilder, PtrSize, StackMapSection, StaticModuleIndex, TrapEncodingBuilder,
40-
TrapSentinel, TripleExt, Tunables, VMOffsets, WasmFuncType, WasmValType,
37+
DefinedFuncIndex, FlagValue, FrameInstPos, FrameStackShape, FrameStateSlotBuilder,
38+
FrameTableBuilder, FuncKey, FunctionBodyData, FunctionLoc, HostCall, InliningCompiler,
39+
ModuleTranslation, ModuleTypesBuilder, PtrSize, StackMapSection, StaticModuleIndex,
40+
TrapEncodingBuilder, TrapSentinel, TripleExt, Tunables, VMOffsets, WasmFuncType, WasmValType,
4141
};
4242
use wasmtime_unwinder::ExceptionTableBuilder;
4343

@@ -56,6 +56,7 @@ struct CompilerContext {
5656
codegen_context: Context,
5757
incremental_cache_ctx: Option<IncrementalCacheContext>,
5858
validator_allocations: FuncValidatorAllocations,
59+
debug_slot_descriptor: Option<FrameStateSlotBuilder>,
5960
abi: Option<Abi>,
6061
}
6162

@@ -66,6 +67,7 @@ impl Default for CompilerContext {
6667
codegen_context: Context::new(),
6768
incremental_cache_ctx: None,
6869
validator_allocations: Default::default(),
70+
debug_slot_descriptor: None,
6971
abi: None,
7072
}
7173
}
@@ -329,13 +331,19 @@ impl wasmtime_environ::Compiler for Compiler {
329331
.map_err(|e| CompileError::Codegen(e.to_string()))?;
330332
}
331333

334+
let needs_gc_heap = func_env.needs_gc_heap();
335+
336+
if let Some((_, slot_builder)) = func_env.state_slot {
337+
compiler.cx.debug_slot_descriptor = Some(slot_builder);
338+
}
339+
332340
let timing = cranelift_codegen::timing::take_current();
333341
log::debug!("`{symbol}` translated to CLIF in {:?}", timing.total());
334342
log::trace!("`{symbol}` timing info\n{timing}");
335343

336344
Ok(CompiledFunctionBody {
337345
code: box_dyn_any_compiler_context(Some(compiler.cx)),
338-
needs_gc_heap: func_env.needs_gc_heap(),
346+
needs_gc_heap,
339347
})
340348
}
341349

@@ -561,12 +569,12 @@ impl wasmtime_environ::Compiler for Compiler {
561569
fn append_code(
562570
&self,
563571
obj: &mut Object<'static>,
564-
funcs: &[(String, Box<dyn Any + Send + Sync>)],
572+
funcs: &[(String, FuncKey, Box<dyn Any + Send + Sync>)],
565573
resolve_reloc: &dyn Fn(usize, FuncKey) -> usize,
566574
) -> Result<Vec<(SymbolId, FunctionLoc)>> {
567575
log::trace!(
568576
"appending functions to object file: {:#?}",
569-
funcs.iter().map(|(sym, _)| sym).collect::<Vec<_>>()
577+
funcs.iter().map(|(sym, _, _)| sym).collect::<Vec<_>>()
570578
);
571579

572580
let mut builder =
@@ -580,8 +588,24 @@ impl wasmtime_environ::Compiler for Compiler {
580588
let mut exception_tables = ExceptionTableBuilder::default();
581589
let mut frame_tables = FrameTableBuilder::default();
582590

591+
let mut frame_descriptors = HashMap::new();
592+
if self.tunables.debug_instrumentation {
593+
for (_, key, func) in funcs {
594+
debug_assert!(!func.is::<Option<CompilerContext>>());
595+
debug_assert!(func.is::<CompiledFunction>());
596+
let func = func.downcast_ref::<CompiledFunction>().unwrap();
597+
frame_descriptors.insert(
598+
*key,
599+
func.debug_slot_descriptor
600+
.as_ref()
601+
.map(|builder| builder.serialize())
602+
.unwrap_or_else(|| vec![]),
603+
);
604+
}
605+
}
606+
583607
let mut ret = Vec::with_capacity(funcs.len());
584-
for (i, (sym, func)) in funcs.iter().enumerate() {
608+
for (i, (sym, _key, func)) in funcs.iter().enumerate() {
585609
debug_assert!(!func.is::<Option<CompilerContext>>());
586610
debug_assert!(func.is::<CompiledFunction>());
587611
let func = func.downcast_ref::<CompiledFunction>().unwrap();
@@ -614,6 +638,7 @@ impl wasmtime_environ::Compiler for Compiler {
614638
range.clone(),
615639
func.buffer.debug_tags(),
616640
frame_layout,
641+
&frame_descriptors,
617642
)?;
618643
}
619644
builder.append_padding(self.linkopts.padding_between_functions);
@@ -1405,6 +1430,10 @@ impl FunctionCompiler<'_> {
14051430
}
14061431
}
14071432

1433+
if let Some(builder) = self.cx.debug_slot_descriptor.take() {
1434+
compiled_function.debug_slot_descriptor = Some(builder);
1435+
}
1436+
14081437
if body_and_tunables
14091438
.map(|(_, t)| t.generate_native_debuginfo)
14101439
.unwrap_or(false)
@@ -1477,8 +1506,9 @@ fn clif_to_env_frame_tables<'a>(
14771506
range: Range<u64>,
14781507
tag_sites: impl Iterator<Item = MachBufferDebugTagList<'a>>,
14791508
frame_layout: &MachBufferFrameLayout,
1509+
frame_descriptors: &HashMap<FuncKey, Vec<u8>>,
14801510
) -> anyhow::Result<()> {
1481-
let mut frame_descriptors = HashMap::new();
1511+
let mut frame_descriptor_indices = HashMap::new();
14821512
for tag_site in tag_sites {
14831513
// Split into frames; each has three debug tags.
14841514
let mut frames = vec![];
@@ -1492,11 +1522,18 @@ fn clif_to_env_frame_tables<'a>(
14921522
panic!("Invalid tags");
14931523
};
14941524

1495-
let frame_descriptor = *frame_descriptors.entry(slot).or_insert_with(|| {
1525+
let func_key = frame_layout.stackslots[slot]
1526+
.key
1527+
.expect("Key must be present on stackslot used as state slot")
1528+
.bits();
1529+
let func_key = FuncKey::from_raw_u64(func_key);
1530+
let frame_descriptor = *frame_descriptor_indices.entry(slot).or_insert_with(|| {
14961531
let slot_to_fp_offset =
14971532
frame_layout.frame_to_fp_offset - frame_layout.stackslots[slot].offset;
1498-
let descriptor = frame_layout.stackslots[slot].descriptor.clone();
1499-
builder.add_frame_descriptor(slot_to_fp_offset, descriptor)
1533+
let descriptor = frame_descriptors
1534+
.get(&func_key)
1535+
.expect("frame descriptor not present for FuncKey");
1536+
builder.add_frame_descriptor(slot_to_fp_offset, &descriptor)
15001537
});
15011538

15021539
frames.push((

crates/cranelift/src/func_environ.rs

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,12 +1197,14 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
11971197

11981198
// Initially zero-size and with no descriptor; we will fill in
11991199
// this info once we're done with the function body.
1200-
let slot = builder.func.create_sized_stack_slot(ir::StackSlotData::new(
1201-
ir::StackSlotKind::ExplicitSlot,
1202-
0,
1203-
0,
1204-
vec![],
1205-
));
1200+
let slot = builder
1201+
.func
1202+
.create_sized_stack_slot(ir::StackSlotData::new_with_key(
1203+
ir::StackSlotKind::ExplicitSlot,
1204+
0,
1205+
0,
1206+
ir::StackSlotKey::new(self.key.into_raw_u64()),
1207+
));
12061208

12071209
self.state_slot = Some((slot, frame_builder));
12081210
}
@@ -1287,21 +1289,8 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
12871289
}
12881290
}
12891291

1290-
fn set_debug_tags(
1291-
&self,
1292-
builder: &mut FunctionBuilder,
1293-
stack: &FuncTranslationStacks,
1294-
srcloc: ir::SourceLoc,
1295-
) {
1296-
if self.state_slot.is_some() {
1297-
let tags = self.debug_tags(stack, srcloc);
1298-
builder.set_debug_tags(tags);
1299-
}
1300-
}
1301-
13021292
fn finish_debug_metadata(&self, builder: &mut FunctionBuilder) {
13031293
if let Some((slot, b)) = &self.state_slot {
1304-
builder.func.sized_stack_slots[*slot].descriptor = b.serialize();
13051294
builder.func.sized_stack_slots[*slot].size = b.size();
13061295
}
13071296
}
@@ -1335,7 +1324,9 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
13351324
srcloc: ir::SourceLoc,
13361325
) -> WasmResult<()> {
13371326
if stack.reachable() {
1338-
self.set_debug_tags(builder, stack, srcloc);
1327+
let inst = builder.ins().sequence_point();
1328+
let tags = self.debug_tags(stack, srcloc);
1329+
builder.func.debug_tags.set(inst, tags);
13391330
}
13401331
Ok(())
13411332
}

crates/environ/src/compile/frame_table.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -231,10 +231,10 @@ impl FrameTableBuilder {
231231
pub fn add_frame_descriptor(
232232
&mut self,
233233
slot_to_fp_offset: u32,
234-
data: Vec<u8>,
234+
data: &[u8],
235235
) -> FrameTableDescriptorIndex {
236236
let start = u32::try_from(self.frame_descriptor_data.len()).unwrap();
237-
self.frame_descriptor_data.extend(data);
237+
self.frame_descriptor_data.extend(data.iter().cloned());
238238
let end = u32::try_from(self.frame_descriptor_data.len()).unwrap();
239239

240240
let index = FrameTableDescriptorIndex(

crates/environ/src/compile/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ pub trait Compiler: Send + Sync {
330330
fn append_code(
331331
&self,
332332
obj: &mut Object<'static>,
333-
funcs: &[(String, Box<dyn Any + Send + Sync>)],
333+
funcs: &[(String, FuncKey, Box<dyn Any + Send + Sync>)],
334334
resolve_reloc: &dyn Fn(usize, FuncKey) -> usize,
335335
) -> Result<Vec<(SymbolId, FunctionLoc)>>;
336336

crates/environ/src/key.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,25 @@ impl FuncKey {
392392
}
393393
}
394394

395+
/// Create a key from a raw packed `u64` representation.
396+
///
397+
/// Should only be given a value produced by `into_raw_u64()`.
398+
///
399+
/// Panics when given an invalid value.
400+
pub fn from_raw_u64(value: u64) -> Self {
401+
let hi = u32::try_from(value >> 32).unwrap();
402+
let lo = u32::try_from(value & 0xffff_ffff).unwrap();
403+
FuncKey::from_raw_parts(hi, lo)
404+
}
405+
406+
/// Produce a packed `u64` representation of this key.
407+
///
408+
/// May be used with `from_raw_64()` to reconstruct this key.
409+
pub fn into_raw_u64(&self) -> u64 {
410+
let (hi, lo) = self.into_raw_parts();
411+
(u64::from(hi) << 32) | u64::from(lo)
412+
}
413+
395414
/// Unwrap a `FuncKey::DefinedWasmFunction` or else panic.
396415
pub fn unwrap_defined_wasm_function(self) -> (StaticModuleIndex, DefinedFuncIndex) {
397416
match self {

crates/wasmtime/src/compile.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -890,7 +890,7 @@ impl UnlinkedCompileOutputs<'_> {
890890
needs_gc_heap |= output.function.needs_gc_heap;
891891

892892
let index = compiled_funcs.len();
893-
compiled_funcs.push((output.symbol, output.function.code));
893+
compiled_funcs.push((output.symbol, output.key, output.function.code));
894894

895895
if output.start_srcloc != FilePos::none() {
896896
indices
@@ -913,9 +913,9 @@ impl UnlinkedCompileOutputs<'_> {
913913
struct PreLinkOutput {
914914
/// Whether or not any of these functions require a GC heap
915915
needs_gc_heap: bool,
916-
/// The flattened list of (symbol name, compiled function) pairs, as they
917-
/// will be laid out in the object file.
918-
compiled_funcs: Vec<(String, Box<dyn Any + Send + Sync>)>,
916+
/// The flattened list of (symbol name, FuncKey, compiled
917+
/// function) pairs, as they will be laid out in the object file.
918+
compiled_funcs: Vec<(String, FuncKey, Box<dyn Any + Send + Sync>)>,
919919
/// The `FunctionIndices` mapping our function keys to indices in that flat
920920
/// list.
921921
indices: FunctionIndices,
@@ -937,7 +937,7 @@ impl FunctionIndices {
937937
self,
938938
mut obj: object::write::Object<'static>,
939939
engine: &'a Engine,
940-
compiled_funcs: Vec<(String, Box<dyn Any + Send + Sync>)>,
940+
compiled_funcs: Vec<(String, FuncKey, Box<dyn Any + Send + Sync>)>,
941941
translations: PrimaryMap<StaticModuleIndex, ModuleTranslation<'_>>,
942942
dwarf_package_bytes: Option<&[u8]>,
943943
) -> Result<(wasmtime_environ::ObjectBuilder<'a>, Artifacts)> {
@@ -966,7 +966,7 @@ impl FunctionIndices {
966966
&|module, func| {
967967
let i = self.indices[&FuncKey::DefinedWasmFunction(module, func)];
968968
let (symbol, _) = symbol_ids_and_locs[i];
969-
let (_, compiled_func) = &compiled_funcs[i];
969+
let (_, _, compiled_func) = &compiled_funcs[i];
970970
(symbol, &**compiled_func)
971971
},
972972
dwarf_package_bytes,

crates/winch/src/compiler.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ impl wasmtime_environ::Compiler for Compiler {
189189
fn append_code(
190190
&self,
191191
obj: &mut Object<'static>,
192-
funcs: &[(String, Box<dyn Any + Send + Sync>)],
192+
funcs: &[(String, FuncKey, Box<dyn Any + Send + Sync>)],
193193
resolve_reloc: &dyn Fn(usize, wasmtime_environ::FuncKey) -> usize,
194194
) -> Result<Vec<(SymbolId, FunctionLoc)>> {
195195
self.trampolines.append_code(obj, funcs, resolve_reloc)
@@ -334,7 +334,7 @@ impl wasmtime_environ::Compiler for NoInlineCompiler {
334334
fn append_code(
335335
&self,
336336
obj: &mut Object<'static>,
337-
funcs: &[(String, Box<dyn Any + Send + Sync>)],
337+
funcs: &[(String, FuncKey, Box<dyn Any + Send + Sync>)],
338338
resolve_reloc: &dyn Fn(usize, FuncKey) -> usize,
339339
) -> Result<Vec<(SymbolId, FunctionLoc)>> {
340340
self.0.append_code(obj, funcs, resolve_reloc)

0 commit comments

Comments
 (0)