Struct cranelift_codegen::ir::function::Function
source · pub struct Function {
pub name: UserFuncName,
pub stencil: FunctionStencil,
pub params: FunctionParameters,
}
Expand description
Functions can be cloned, but it is not a very fast operation. The clone will have all the same entity numbers as the original.
Fields§
§name: UserFuncName
Name of this function.
Mostly used by .clif
files, only there for debugging / naming purposes.
stencil: FunctionStencil
All the fields required for compiling a function, independently of details irrelevant to
compilation and that are stored in the FunctionParameters
params
field instead.
params: FunctionParameters
All the parameters that can be applied onto the function stencil, that is, that don’t matter when caching compilation artifacts.
Implementations§
source§impl Function
impl Function
sourcepub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self
pub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self
Create a function with the given name and signature.
sourcepub fn display(&self) -> DisplayFunction<'_>
pub fn display(&self) -> DisplayFunction<'_>
Return an object that can display this function with correct ISA-specific annotations.
Examples found in repository?
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
pub fn optimize(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> {
log::debug!(
"Number of CLIF instructions to optimize: {}",
self.func.dfg.num_insts()
);
log::debug!(
"Number of CLIF blocks to optimize: {}",
self.func.dfg.num_blocks()
);
let opt_level = isa.flags().opt_level();
crate::trace!(
"Optimizing (opt level {:?}):\n{}",
opt_level,
self.func.display()
);
self.compute_cfg();
if !isa.flags().use_egraphs() && opt_level != OptLevel::None {
self.preopt(isa)?;
}
if isa.flags().enable_nan_canonicalization() {
self.canonicalize_nans(isa)?;
}
self.legalize(isa)?;
if !isa.flags().use_egraphs() && opt_level != OptLevel::None {
self.compute_domtree();
self.compute_loop_analysis();
self.licm(isa)?;
self.simple_gvn(isa)?;
}
self.compute_domtree();
self.eliminate_unreachable_code(isa)?;
if isa.flags().use_egraphs() || opt_level != OptLevel::None {
self.dce(isa)?;
}
self.remove_constant_phis(isa)?;
if isa.flags().use_egraphs() {
log::debug!(
"About to optimize with egraph phase:\n{}",
self.func.display()
);
self.compute_loop_analysis();
let mut eg = FuncEGraph::new(&self.func, &self.domtree, &self.loop_analysis, &self.cfg);
eg.elaborate(&mut self.func);
log::debug!("After egraph optimization:\n{}", self.func.display());
log::info!("egraph stats: {:?}", eg.stats);
} else if opt_level != OptLevel::None && isa.flags().enable_alias_analysis() {
self.replace_redundant_loads()?;
self.simple_gvn(isa)?;
}
Ok(())
}
More examples
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
pub fn simple_legalize(func: &mut ir::Function, cfg: &mut ControlFlowGraph, isa: &dyn TargetIsa) {
trace!("Pre-legalization function:\n{}", func.display());
let mut pos = FuncCursor::new(func);
let func_begin = pos.position();
pos.set_position(func_begin);
while let Some(_block) = pos.next_block() {
let mut prev_pos = pos.position();
while let Some(inst) = pos.next_inst() {
match pos.func.dfg[inst] {
// control flow
InstructionData::CondTrap {
opcode:
opcode @ (ir::Opcode::Trapnz | ir::Opcode::Trapz | ir::Opcode::ResumableTrapnz),
arg,
code,
} => {
expand_cond_trap(inst, &mut pos.func, cfg, opcode, arg, code);
}
// memory and constants
InstructionData::UnaryGlobalValue {
opcode: ir::Opcode::GlobalValue,
global_value,
} => expand_global_value(inst, &mut pos.func, isa, global_value),
InstructionData::HeapAddr {
opcode: ir::Opcode::HeapAddr,
heap,
arg,
offset,
size,
} => expand_heap_addr(inst, &mut pos.func, cfg, isa, heap, arg, offset, size),
InstructionData::HeapLoad {
opcode: ir::Opcode::HeapLoad,
heap_imm,
arg,
} => expand_heap_load(inst, &mut pos.func, cfg, isa, heap_imm, arg),
InstructionData::HeapStore {
opcode: ir::Opcode::HeapStore,
heap_imm,
args,
} => expand_heap_store(inst, &mut pos.func, cfg, isa, heap_imm, args[0], args[1]),
InstructionData::StackLoad {
opcode: ir::Opcode::StackLoad,
stack_slot,
offset,
} => {
let ty = pos.func.dfg.value_type(pos.func.dfg.first_result(inst));
let addr_ty = isa.pointer_type();
let mut pos = FuncCursor::new(pos.func).at_inst(inst);
pos.use_srcloc(inst);
let addr = pos.ins().stack_addr(addr_ty, stack_slot, offset);
// Stack slots are required to be accessible and aligned.
let mflags = MemFlags::trusted();
pos.func.dfg.replace(inst).load(ty, mflags, addr, 0);
}
InstructionData::StackStore {
opcode: ir::Opcode::StackStore,
arg,
stack_slot,
offset,
} => {
let addr_ty = isa.pointer_type();
let mut pos = FuncCursor::new(pos.func).at_inst(inst);
pos.use_srcloc(inst);
let addr = pos.ins().stack_addr(addr_ty, stack_slot, offset);
let mut mflags = MemFlags::new();
// Stack slots are required to be accessible and aligned.
mflags.set_notrap();
mflags.set_aligned();
pos.func.dfg.replace(inst).store(mflags, arg, addr, 0);
}
InstructionData::DynamicStackLoad {
opcode: ir::Opcode::DynamicStackLoad,
dynamic_stack_slot,
} => {
let ty = pos.func.dfg.value_type(pos.func.dfg.first_result(inst));
assert!(ty.is_dynamic_vector());
let addr_ty = isa.pointer_type();
let mut pos = FuncCursor::new(pos.func).at_inst(inst);
pos.use_srcloc(inst);
let addr = pos.ins().dynamic_stack_addr(addr_ty, dynamic_stack_slot);
// Stack slots are required to be accessible and aligned.
let mflags = MemFlags::trusted();
pos.func.dfg.replace(inst).load(ty, mflags, addr, 0);
}
InstructionData::DynamicStackStore {
opcode: ir::Opcode::DynamicStackStore,
arg,
dynamic_stack_slot,
} => {
pos.use_srcloc(inst);
let addr_ty = isa.pointer_type();
let vector_ty = pos.func.dfg.value_type(arg);
assert!(vector_ty.is_dynamic_vector());
let addr = pos.ins().dynamic_stack_addr(addr_ty, dynamic_stack_slot);
let mut mflags = MemFlags::new();
// Stack slots are required to be accessible and aligned.
mflags.set_notrap();
mflags.set_aligned();
pos.func.dfg.replace(inst).store(mflags, arg, addr, 0);
}
InstructionData::TableAddr {
opcode: ir::Opcode::TableAddr,
table,
arg,
offset,
} => expand_table_addr(isa, inst, &mut pos.func, table, arg, offset),
InstructionData::BinaryImm64 { opcode, arg, imm } => {
let is_signed = match opcode {
ir::Opcode::IaddImm
| ir::Opcode::IrsubImm
| ir::Opcode::ImulImm
| ir::Opcode::SdivImm
| ir::Opcode::SremImm
| ir::Opcode::IfcmpImm => true,
_ => false,
};
let imm = imm_const(&mut pos, arg, imm, is_signed);
let replace = pos.func.dfg.replace(inst);
match opcode {
// bitops
ir::Opcode::BandImm => {
replace.band(arg, imm);
}
ir::Opcode::BorImm => {
replace.bor(arg, imm);
}
ir::Opcode::BxorImm => {
replace.bxor(arg, imm);
}
// bitshifting
ir::Opcode::IshlImm => {
replace.ishl(arg, imm);
}
ir::Opcode::RotlImm => {
replace.rotl(arg, imm);
}
ir::Opcode::RotrImm => {
replace.rotr(arg, imm);
}
ir::Opcode::SshrImm => {
replace.sshr(arg, imm);
}
ir::Opcode::UshrImm => {
replace.ushr(arg, imm);
}
// math
ir::Opcode::IaddImm => {
replace.iadd(arg, imm);
}
ir::Opcode::IrsubImm => {
// note: arg order reversed
replace.isub(imm, arg);
}
ir::Opcode::ImulImm => {
replace.imul(arg, imm);
}
ir::Opcode::SdivImm => {
replace.sdiv(arg, imm);
}
ir::Opcode::SremImm => {
replace.srem(arg, imm);
}
ir::Opcode::UdivImm => {
replace.udiv(arg, imm);
}
ir::Opcode::UremImm => {
replace.urem(arg, imm);
}
// comparisons
ir::Opcode::IfcmpImm => {
replace.ifcmp(arg, imm);
}
_ => prev_pos = pos.position(),
};
}
// comparisons
InstructionData::IntCompareImm {
opcode: ir::Opcode::IcmpImm,
cond,
arg,
imm,
} => {
let imm = imm_const(&mut pos, arg, imm, true);
pos.func.dfg.replace(inst).icmp(cond, arg, imm);
}
_ => {
prev_pos = pos.position();
continue;
}
}
// Legalization implementations require fixpoint loop here.
// TODO: fix this.
pos.set_position(prev_pos);
}
}
trace!("Post-legalization function:\n{}", func.display());
}
sourcepub fn display_with<'a>(
&'a self,
annotations: DisplayFunctionAnnotations<'a>
) -> DisplayFunction<'a>
pub fn display_with<'a>(
&'a self,
annotations: DisplayFunctionAnnotations<'a>
) -> DisplayFunction<'a>
Return an object that can display this function with correct ISA-specific annotations.
sourcepub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc)
pub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc)
Sets an absolute source location for the given instruction.
If no base source location has been set yet, records it at the same time.
Examples found in repository?
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
fn insert_built_inst(self, inst: ir::Inst) -> &'c mut ir::DataFlowGraph {
// TODO: Remove this assertion once #796 is fixed.
#[cfg(debug_assertions)]
{
if let CursorPosition::At(_) = self.position() {
if let Some(curr) = self.current_inst() {
if let Some(prev) = self.layout().prev_inst(curr) {
let prev_op = self.data_flow_graph()[prev].opcode();
let inst_op = self.data_flow_graph()[inst].opcode();
let curr_op = self.data_flow_graph()[curr].opcode();
if prev_op.is_branch()
&& !prev_op.is_terminator()
&& !inst_op.is_terminator()
{
panic!(
"Inserting instruction {} after {}, and before {}",
inst_op, prev_op, curr_op
)
}
};
};
};
}
self.insert_inst(inst);
if !self.srcloc.is_default() {
self.func.set_srcloc(inst, self.srcloc);
}
&mut self.func.dfg
}
sourcepub fn srcloc(&self, inst: Inst) -> SourceLoc
pub fn srcloc(&self, inst: Inst) -> SourceLoc
Returns an absolute source location for the given instruction.
Examples found in repository?
More examples
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
fn write_instruction(
w: &mut dyn Write,
func: &Function,
aliases: &SecondaryMap<Value, Vec<Value>>,
inst: Inst,
indent: usize,
) -> fmt::Result {
// Prefix containing source location, encoding, and value locations.
let mut s = String::with_capacity(16);
// Source location goes first.
let srcloc = func.srcloc(inst);
if !srcloc.is_default() {
write!(s, "{} ", srcloc)?;
}
// Write out prefix and indent the instruction.
write!(w, "{1:0$}", indent, s)?;
// Write out the result values, if any.
let mut has_results = false;
for r in func.dfg.inst_results(inst) {
if !has_results {
has_results = true;
write!(w, "{}", r)?;
} else {
write!(w, ", {}", r)?;
}
}
if has_results {
write!(w, " = ")?;
}
// Then the opcode, possibly with a '.type' suffix.
let opcode = func.dfg[inst].opcode();
match type_suffix(func, inst) {
Some(suf) => write!(w, "{}.{}", opcode, suf)?,
None => write!(w, "{}", opcode)?,
}
write_operands(w, &func.dfg, inst)?;
writeln!(w)?;
// Value aliases come out on lines after the instruction defining the referent.
for r in func.dfg.inst_results(inst) {
write_value_aliases(w, aliases, *r, indent)?;
}
Ok(())
}
sourcepub fn declare_imported_user_function(
&mut self,
name: UserExternalName
) -> UserExternalNameRef
pub fn declare_imported_user_function(
&mut self,
name: UserExternalName
) -> UserExternalNameRef
Declare a user-defined external function import, to be referenced in ExtFuncData::User
later.
sourcepub fn import_function(&mut self, data: ExtFuncData) -> FuncRef
pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef
Declare an external function import.
Methods from Deref<Target = FunctionStencil>§
sourcepub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable
pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable
Creates a jump table in the function, to be used by br_table
instructions.
sourcepub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot
pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot
Creates a sized stack slot in the function, to be used by stack_load
, stack_store
and stack_addr
instructions.
sourcepub fn create_dynamic_stack_slot(
&mut self,
data: DynamicStackSlotData
) -> DynamicStackSlot
pub fn create_dynamic_stack_slot(
&mut self,
data: DynamicStackSlotData
) -> DynamicStackSlot
Creates a dynamic stack slot in the function, to be used by dynamic_stack_load
,
dynamic_stack_store
and dynamic_stack_addr
instructions.
sourcepub fn import_signature(&mut self, signature: Signature) -> SigRef
pub fn import_signature(&mut self, signature: Signature) -> SigRef
Adds a signature which can later be used to declare an external function import.
sourcepub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue
pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue
Declares a global value accessible to the function.
sourcepub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue
pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue
Find the global dyn_scale value associated with given DynamicType
sourcepub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue
pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue
Find the global dyn_scale for the given stack slot.
sourcepub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type>
pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type>
Get a concrete Type
from a user defined DynamicType
.
Examples found in repository?
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
pub fn new<'a>(
f: &ir::Function,
isa: &dyn TargetIsa,
isa_flags: &M::F,
sigs: &SigSet,
) -> CodegenResult<Self> {
trace!("ABI: func signature {:?}", f.signature);
let flags = isa.flags().clone();
let sig = sigs.abi_sig_for_signature(&f.signature);
let call_conv = f.signature.call_conv;
// Only these calling conventions are supported.
debug_assert!(
call_conv == isa::CallConv::SystemV
|| call_conv == isa::CallConv::Fast
|| call_conv == isa::CallConv::Cold
|| call_conv.extends_windows_fastcall()
|| call_conv == isa::CallConv::AppleAarch64
|| call_conv == isa::CallConv::WasmtimeSystemV
|| call_conv == isa::CallConv::WasmtimeAppleAarch64,
"Unsupported calling convention: {:?}",
call_conv
);
// Compute sized stackslot locations and total stackslot size.
let mut sized_stack_offset: u32 = 0;
let mut sized_stackslots = PrimaryMap::new();
for (stackslot, data) in f.sized_stack_slots.iter() {
let off = sized_stack_offset;
sized_stack_offset += data.size;
let mask = M::word_bytes() - 1;
sized_stack_offset = (sized_stack_offset + mask) & !mask;
debug_assert_eq!(stackslot.as_u32() as usize, sized_stackslots.len());
sized_stackslots.push(off);
}
// Compute dynamic stackslot locations and total stackslot size.
let mut dynamic_stackslots = PrimaryMap::new();
let mut dynamic_stack_offset: u32 = sized_stack_offset;
for (stackslot, data) in f.dynamic_stack_slots.iter() {
debug_assert_eq!(stackslot.as_u32() as usize, dynamic_stackslots.len());
let off = dynamic_stack_offset;
let ty = f
.get_concrete_dynamic_ty(data.dyn_ty)
.unwrap_or_else(|| panic!("invalid dynamic vector type: {}", data.dyn_ty));
dynamic_stack_offset += isa.dynamic_vector_bytes(ty);
let mask = M::word_bytes() - 1;
dynamic_stack_offset = (dynamic_stack_offset + mask) & !mask;
dynamic_stackslots.push(off);
}
let stackslots_size = dynamic_stack_offset;
let mut dynamic_type_sizes = HashMap::with_capacity(f.dfg.dynamic_types.len());
for (dyn_ty, _data) in f.dfg.dynamic_types.iter() {
let ty = f
.get_concrete_dynamic_ty(dyn_ty)
.unwrap_or_else(|| panic!("invalid dynamic vector type: {}", dyn_ty));
let size = isa.dynamic_vector_bytes(ty);
dynamic_type_sizes.insert(ty, size);
}
// Figure out what instructions, if any, will be needed to check the
// stack limit. This can either be specified as a special-purpose
// argument or as a global value which often calculates the stack limit
// from the arguments.
let stack_limit =
get_special_purpose_param_register(f, sigs, &sig, ir::ArgumentPurpose::StackLimit)
.map(|reg| (reg, smallvec![]))
.or_else(|| {
f.stack_limit
.map(|gv| gen_stack_limit::<M>(f, sigs, &sig, gv))
});
// Determine whether a probestack call is required for large enough
// frames (and the minimum frame size if so).
let probestack_min_frame = if flags.enable_probestack() {
assert!(
!flags.probestack_func_adjusts_sp(),
"SP-adjusting probestack not supported in new backends"
);
Some(1 << flags.probestack_size_log2())
} else {
None
};
Ok(Self {
ir_sig: ensure_struct_return_ptr_is_returned(&f.signature),
sig,
dynamic_stackslots,
dynamic_type_sizes,
sized_stackslots,
stackslots_size,
outgoing_args_size: 0,
reg_args: vec![],
clobbered: vec![],
spillslots: None,
fixed_frame_storage_size: 0,
total_frame_size: None,
ret_area_ptr: None,
arg_temp_reg: vec![],
call_conv,
flags,
isa_flags: isa_flags.clone(),
is_leaf: f.is_leaf(),
stack_limit,
probestack_min_frame,
setup_frame: true,
_mach: PhantomData,
})
}
sourcepub fn create_heap(&mut self, data: HeapData) -> Heap
pub fn create_heap(&mut self, data: HeapData) -> Heap
Declares a heap accessible to the function.
sourcepub fn create_table(&mut self, data: TableData) -> Table
pub fn create_table(&mut self, data: TableData) -> Table
Declares a table accessible to the function.
sourcepub fn special_param(&self, purpose: ArgumentPurpose) -> Option<Value>
pub fn special_param(&self, purpose: ArgumentPurpose) -> Option<Value>
Find a presumed unique special-purpose function parameter value.
Returns the value of the last purpose
parameter, or None
if no such parameter exists.
Examples found in repository?
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
fn vmctx_addr(inst: ir::Inst, func: &mut ir::Function) {
// Get the value representing the `vmctx` argument.
let vmctx = func
.special_param(ir::ArgumentPurpose::VMContext)
.expect("Missing vmctx parameter");
// Replace the `global_value` instruction's value with an alias to the vmctx arg.
let result = func.dfg.first_result(inst);
func.dfg.clear_results(inst);
func.dfg.change_to_alias(result, vmctx);
func.layout.remove_inst(inst);
}
/// Expand a `global_value` instruction for an iadd_imm global.
fn iadd_imm_addr(
inst: ir::Inst,
func: &mut ir::Function,
base: ir::GlobalValue,
offset: i64,
global_type: ir::Type,
) {
let mut pos = FuncCursor::new(func).at_inst(inst);
// Get the value for the lhs. For tidiness, expand VMContext here so that we avoid
// `vmctx_addr` which creates an otherwise unneeded value alias.
let lhs = if let ir::GlobalValueData::VMContext = pos.func.global_values[base] {
pos.func
.special_param(ir::ArgumentPurpose::VMContext)
.expect("Missing vmctx parameter")
} else {
pos.ins().global_value(global_type, base)
};
// Simply replace the `global_value` instruction with an `iadd_imm`, reusing the result value.
pos.func.dfg.replace(inst).iadd_imm(lhs, offset);
}
/// Expand a `global_value` instruction for a load global.
fn load_addr(
inst: ir::Inst,
func: &mut ir::Function,
base: ir::GlobalValue,
offset: ir::immediates::Offset32,
global_type: ir::Type,
readonly: bool,
isa: &dyn TargetIsa,
) {
// We need to load a pointer from the `base` global value, so insert a new `global_value`
// instruction. This depends on the iterative legalization loop. Note that the IR verifier
// detects any cycles in the `load` globals.
let ptr_ty = isa.pointer_type();
let mut pos = FuncCursor::new(func).at_inst(inst);
pos.use_srcloc(inst);
// Get the value for the base. For tidiness, expand VMContext here so that we avoid
// `vmctx_addr` which creates an otherwise unneeded value alias.
let base_addr = if let ir::GlobalValueData::VMContext = pos.func.global_values[base] {
pos.func
.special_param(ir::ArgumentPurpose::VMContext)
.expect("Missing vmctx parameter")
} else {
pos.ins().global_value(ptr_ty, base)
};
// Global-value loads are always notrap and aligned. They may be readonly.
let mut mflags = ir::MemFlags::trusted();
if readonly {
mflags.set_readonly();
}
// Perform the load.
pos.func
.dfg
.replace(inst)
.load(global_type, mflags, base_addr, offset);
}
More examples
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
fn gen_arg_setup(&mut self) {
if let Some(entry_bb) = self.f.layout.entry_block() {
trace!(
"gen_arg_setup: entry BB {} args are:\n{:?}",
entry_bb,
self.f.dfg.block_params(entry_bb)
);
// Make the vmctx available in debuginfo.
if let Some(vmctx_val) = self.f.special_param(ArgumentPurpose::VMContext) {
self.emit_value_label_marks_for_value(vmctx_val);
}
for (i, param) in self.f.dfg.block_params(entry_bb).iter().enumerate() {
if !self.vcode.abi().arg_is_needed_in_body(i) {
continue;
}
let regs = writable_value_regs(self.value_regs[*param]);
for insn in self
.vcode
.vcode
.abi
.gen_copy_arg_to_regs(&self.vcode.vcode.sigs, i, regs, &mut self.vregs)
.into_iter()
{
self.emit(insn);
}
if self.abi().signature().params[i].purpose == ArgumentPurpose::StructReturn {
assert!(regs.len() == 1);
let ty = self.abi().signature().params[i].value_type;
// The ABI implementation must have ensured that a StructReturn
// arg is present in the return values.
assert!(self
.abi()
.signature()
.returns
.iter()
.position(|ret| ret.purpose == ArgumentPurpose::StructReturn)
.is_some());
self.emit(I::gen_move(
Writable::from_reg(self.sret_reg.unwrap().regs()[0]),
regs.regs()[0].to_reg(),
ty,
));
}
}
if let Some(insn) = self
.vcode
.vcode
.abi
.gen_retval_area_setup(&self.vcode.vcode.sigs, &mut self.vregs)
{
self.emit(insn);
}
// The `args` instruction below must come first. Finish
// the current "IR inst" (with a default source location,
// as for other special instructions inserted during
// lowering) and continue the scan backward.
self.finish_ir_inst(Default::default());
if let Some(insn) = self.vcode.vcode.abi.take_args() {
self.emit(insn);
}
}
}
/// Generate the return instruction.
pub fn gen_return(&mut self, rets: Vec<ValueRegs<Reg>>) {
let mut out_rets = vec![];
let mut rets = rets.into_iter();
for (i, ret) in self
.abi()
.signature()
.returns
.clone()
.into_iter()
.enumerate()
{
let regs = if ret.purpose == ArgumentPurpose::StructReturn {
self.sret_reg.unwrap().clone()
} else {
rets.next().unwrap()
};
let (regs, insns) = self.vcode.abi().gen_copy_regs_to_retval(
self.vcode.sigs(),
i,
regs,
&mut self.vregs,
);
out_rets.extend(regs);
for insn in insns {
self.emit(insn);
}
}
// Hack: generate a virtual instruction that uses vmctx in
// order to keep it alive for the duration of the function,
// for the benefit of debuginfo.
if self.f.dfg.values_labels.is_some() {
if let Some(vmctx_val) = self.f.special_param(ArgumentPurpose::VMContext) {
let vmctx_reg = self.value_regs[vmctx_val].only_reg().unwrap();
self.emit(I::gen_dummy_use(vmctx_reg));
}
}
let inst = self.abi().gen_ret(out_rets);
self.emit(inst);
}
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
fn verify_global_values(&self, errors: &mut VerifierErrors) -> VerifierStepResult<()> {
let mut cycle_seen = false;
let mut seen = SparseSet::new();
'gvs: for gv in self.func.global_values.keys() {
seen.clear();
seen.insert(gv);
let mut cur = gv;
loop {
match self.func.global_values[cur] {
ir::GlobalValueData::Load { base, .. }
| ir::GlobalValueData::IAddImm { base, .. } => {
if seen.insert(base).is_some() {
if !cycle_seen {
errors.report((
gv,
format!("global value cycle: {}", DisplayList(seen.as_slice())),
));
// ensures we don't report the cycle multiple times
cycle_seen = true;
}
continue 'gvs;
}
cur = base;
}
_ => break,
}
}
match self.func.global_values[gv] {
ir::GlobalValueData::VMContext { .. } => {
if self
.func
.special_param(ir::ArgumentPurpose::VMContext)
.is_none()
{
errors.report((gv, format!("undeclared vmctx reference {}", gv)));
}
}
ir::GlobalValueData::IAddImm {
base, global_type, ..
} => {
if !global_type.is_int() {
errors.report((
gv,
format!("iadd_imm global value with non-int type {}", global_type),
));
} else if let Some(isa) = self.isa {
let base_type = self.func.global_values[base].global_type(isa);
if global_type != base_type {
errors.report((
gv,
format!(
"iadd_imm type {} differs from operand type {}",
global_type, base_type
),
));
}
}
}
ir::GlobalValueData::Load { base, .. } => {
if let Some(isa) = self.isa {
let base_type = self.func.global_values[base].global_type(isa);
let pointer_type = isa.pointer_type();
if base_type != pointer_type {
errors.report((
gv,
format!(
"base {} has type {}, which is not the pointer type {}",
base, base_type, pointer_type
),
));
}
}
}
_ => {}
}
}
// Invalid global values shouldn't stop us from verifying the rest of the function
Ok(())
}
sourcepub fn collect_debug_info(&mut self)
pub fn collect_debug_info(&mut self)
Starts collection of debug information.
sourcepub fn change_branch_destination(&mut self, inst: Inst, new_dest: Block)
pub fn change_branch_destination(&mut self, inst: Inst, new_dest: Block)
Changes the destination of a jump or branch instruction. Does nothing if called with a non-jump or non-branch instruction.
Note that this method ignores multi-destination branches like br_table
.
Examples found in repository?
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
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 => {}
}
}
sourcepub fn rewrite_branch_destination(
&mut self,
inst: Inst,
old_dest: Block,
new_dest: Block
)
pub fn rewrite_branch_destination(
&mut self,
inst: Inst,
old_dest: Block,
new_dest: Block
)
Rewrite the branch destination to new_dest
if the destination matches old_dest
.
Does nothing if called with a non-jump or non-branch instruction.
Unlike change_branch_destination, this method
rewrite the destinations of multi-destination branches like br_table
.
Examples found in repository?
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
fn create_pre_header(
header: Block,
func: &mut Function,
cfg: &mut ControlFlowGraph,
domtree: &DominatorTree,
) -> Block {
let pool = &mut ListPool::<Value>::new();
let header_args_values = func.dfg.block_params(header).to_vec();
let header_args_types: Vec<Type> = header_args_values
.into_iter()
.map(|val| func.dfg.value_type(val))
.collect();
let pre_header = func.dfg.make_block();
let mut pre_header_args_value: EntityList<Value> = EntityList::new();
for typ in header_args_types {
pre_header_args_value.push(func.dfg.append_block_param(pre_header, typ), pool);
}
for BlockPredecessor {
inst: last_inst, ..
} in cfg.pred_iter(header)
{
// We only follow normal edges (not the back edges)
if !domtree.dominates(header, last_inst, &func.layout) {
func.rewrite_branch_destination(last_inst, header, pre_header);
}
}
// Inserts the pre-header at the right place in the layout.
let mut pos = FuncCursor::new(func).at_top(header);
pos.insert_block(pre_header);
pos.next_inst();
pos.ins().jump(header, pre_header_args_value.as_slice(pool));
pre_header
}
sourcepub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)>
pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)>
Checks that the specified block can be encoded as a basic block.
On error, returns the first invalid instruction and an error message.
sourcepub fn is_leaf(&self) -> bool
pub fn is_leaf(&self) -> bool
Returns true if the function is function that doesn’t call any other functions. This is not to be confused with a “leaf function” in Windows terminology.
Examples found in repository?
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
pub fn new<'a>(
f: &ir::Function,
isa: &dyn TargetIsa,
isa_flags: &M::F,
sigs: &SigSet,
) -> CodegenResult<Self> {
trace!("ABI: func signature {:?}", f.signature);
let flags = isa.flags().clone();
let sig = sigs.abi_sig_for_signature(&f.signature);
let call_conv = f.signature.call_conv;
// Only these calling conventions are supported.
debug_assert!(
call_conv == isa::CallConv::SystemV
|| call_conv == isa::CallConv::Fast
|| call_conv == isa::CallConv::Cold
|| call_conv.extends_windows_fastcall()
|| call_conv == isa::CallConv::AppleAarch64
|| call_conv == isa::CallConv::WasmtimeSystemV
|| call_conv == isa::CallConv::WasmtimeAppleAarch64,
"Unsupported calling convention: {:?}",
call_conv
);
// Compute sized stackslot locations and total stackslot size.
let mut sized_stack_offset: u32 = 0;
let mut sized_stackslots = PrimaryMap::new();
for (stackslot, data) in f.sized_stack_slots.iter() {
let off = sized_stack_offset;
sized_stack_offset += data.size;
let mask = M::word_bytes() - 1;
sized_stack_offset = (sized_stack_offset + mask) & !mask;
debug_assert_eq!(stackslot.as_u32() as usize, sized_stackslots.len());
sized_stackslots.push(off);
}
// Compute dynamic stackslot locations and total stackslot size.
let mut dynamic_stackslots = PrimaryMap::new();
let mut dynamic_stack_offset: u32 = sized_stack_offset;
for (stackslot, data) in f.dynamic_stack_slots.iter() {
debug_assert_eq!(stackslot.as_u32() as usize, dynamic_stackslots.len());
let off = dynamic_stack_offset;
let ty = f
.get_concrete_dynamic_ty(data.dyn_ty)
.unwrap_or_else(|| panic!("invalid dynamic vector type: {}", data.dyn_ty));
dynamic_stack_offset += isa.dynamic_vector_bytes(ty);
let mask = M::word_bytes() - 1;
dynamic_stack_offset = (dynamic_stack_offset + mask) & !mask;
dynamic_stackslots.push(off);
}
let stackslots_size = dynamic_stack_offset;
let mut dynamic_type_sizes = HashMap::with_capacity(f.dfg.dynamic_types.len());
for (dyn_ty, _data) in f.dfg.dynamic_types.iter() {
let ty = f
.get_concrete_dynamic_ty(dyn_ty)
.unwrap_or_else(|| panic!("invalid dynamic vector type: {}", dyn_ty));
let size = isa.dynamic_vector_bytes(ty);
dynamic_type_sizes.insert(ty, size);
}
// Figure out what instructions, if any, will be needed to check the
// stack limit. This can either be specified as a special-purpose
// argument or as a global value which often calculates the stack limit
// from the arguments.
let stack_limit =
get_special_purpose_param_register(f, sigs, &sig, ir::ArgumentPurpose::StackLimit)
.map(|reg| (reg, smallvec![]))
.or_else(|| {
f.stack_limit
.map(|gv| gen_stack_limit::<M>(f, sigs, &sig, gv))
});
// Determine whether a probestack call is required for large enough
// frames (and the minimum frame size if so).
let probestack_min_frame = if flags.enable_probestack() {
assert!(
!flags.probestack_func_adjusts_sp(),
"SP-adjusting probestack not supported in new backends"
);
Some(1 << flags.probestack_size_log2())
} else {
None
};
Ok(Self {
ir_sig: ensure_struct_return_ptr_is_returned(&f.signature),
sig,
dynamic_stackslots,
dynamic_type_sizes,
sized_stackslots,
stackslots_size,
outgoing_args_size: 0,
reg_args: vec![],
clobbered: vec![],
spillslots: None,
fixed_frame_storage_size: 0,
total_frame_size: None,
ret_area_ptr: None,
arg_temp_reg: vec![],
call_conv,
flags,
isa_flags: isa_flags.clone(),
is_leaf: f.is_leaf(),
stack_limit,
probestack_min_frame,
setup_frame: true,
_mach: PhantomData,
})
}
sourcepub fn transplant_inst(&mut self, dst: Inst, src: Inst)
pub fn transplant_inst(&mut self, dst: Inst, src: Inst)
Replace the dst
instruction’s data with the src
instruction’s data
and then remove src
.
src
and its result values should not be used at all, as any uses would
be left dangling after calling this method.
src
and dst
must have the same number of resulting values, and
src
’s i^th value must have the same type as dst
’s i^th value.
sourcepub fn fixed_stack_size(&self) -> u32
pub fn fixed_stack_size(&self) -> u32
Size occupied by all stack slots associated with this function.
Does not include any padding necessary due to offsets