1use crate::cursor::{Cursor as _, FuncCursor};
23use crate::ir::{self, DebugTag, ExceptionTableData, ExceptionTableItem, InstBuilder as _};
24use crate::isa::CallConv;
25use crate::result::CodegenResult;
26use crate::trace;
27use crate::traversals::Dfs;
28use alloc::borrow::Cow;
29use alloc::vec::Vec;
30use cranelift_entity::{SecondaryMap, packed_option::PackedOption};
31use smallvec::SmallVec;
32
33type SmallValueVec = SmallVec<[ir::Value; 8]>;
34type SmallBlockArgVec = SmallVec<[ir::BlockArg; 8]>;
35type SmallBlockCallVec = SmallVec<[ir::BlockCall; 8]>;
36
37pub enum InlineCommand<'a> {
39 KeepCall,
41
42 Inline {
48 callee: Cow<'a, ir::Function>,
50 visit_callee: bool,
53 },
54}
55
56pub trait Inline {
61 fn inline(
84 &mut self,
85 caller: &ir::Function,
86 call_inst: ir::Inst,
87 call_opcode: ir::Opcode,
88 callee: ir::FuncRef,
89 call_args: &[ir::Value],
90 ) -> InlineCommand<'_>;
91}
92
93impl<'a, T> Inline for &'a mut T
94where
95 T: Inline,
96{
97 fn inline(
98 &mut self,
99 caller: &ir::Function,
100 inst: ir::Inst,
101 opcode: ir::Opcode,
102 callee: ir::FuncRef,
103 args: &[ir::Value],
104 ) -> InlineCommand<'_> {
105 (*self).inline(caller, inst, opcode, callee, args)
106 }
107}
108
109pub(crate) fn do_inlining(
114 func: &mut ir::Function,
115 mut inliner: impl Inline,
116) -> CodegenResult<bool> {
117 trace!("function {} before inlining: {}", func.name, func);
118
119 let mut inlined_any = false;
120 let mut allocs = InliningAllocs::default();
121
122 let mut cursor = FuncCursor::new(func);
123 'block_loop: while let Some(block) = cursor.next_block() {
124 let mut prev_pos;
132
133 while let Some(inst) = {
134 prev_pos = cursor.position();
135 cursor.next_inst()
136 } {
137 debug_assert_eq!(Some(block), cursor.func.layout.inst_block(inst));
141
142 match cursor.func.dfg.insts[inst] {
143 ir::InstructionData::Call { func_ref, .. }
144 if cursor.func.dfg.ext_funcs[func_ref].patchable =>
145 {
146 }
150
151 ir::InstructionData::Call {
152 opcode: opcode @ ir::Opcode::Call | opcode @ ir::Opcode::ReturnCall,
153 args: _,
154 func_ref,
155 } => {
156 trace!(
157 "considering call site for inlining: {inst}: {}",
158 cursor.func.dfg.display_inst(inst),
159 );
160 let args = cursor.func.dfg.inst_args(inst);
161 match inliner.inline(&cursor.func, inst, opcode, func_ref, args) {
162 InlineCommand::KeepCall => {
163 trace!(" --> keeping call");
164 }
165 InlineCommand::Inline {
166 callee,
167 visit_callee,
168 } => {
169 if can_inline(cursor.func, &callee) {
170 let last_inlined_block = inline_one(
171 &mut allocs,
172 cursor.func,
173 func_ref,
174 block,
175 inst,
176 opcode,
177 &callee,
178 None,
179 )?;
180 inlined_any = true;
181 if visit_callee {
182 cursor.set_position(prev_pos);
183 } else {
184 cursor.goto_bottom(last_inlined_block);
188 continue 'block_loop;
189 }
190 }
191 }
192 }
193 }
194 ir::InstructionData::TryCall {
195 opcode: opcode @ ir::Opcode::TryCall,
196 args: _,
197 func_ref,
198 exception,
199 } => {
200 trace!(
201 "considering call site for inlining: {inst}: {}",
202 cursor.func.dfg.display_inst(inst),
203 );
204 let args = cursor.func.dfg.inst_args(inst);
205 match inliner.inline(&cursor.func, inst, opcode, func_ref, args) {
206 InlineCommand::KeepCall => {
207 trace!(" --> keeping call");
208 }
209 InlineCommand::Inline {
210 callee,
211 visit_callee,
212 } => {
213 if can_inline(cursor.func, &callee) {
214 let last_inlined_block = inline_one(
215 &mut allocs,
216 cursor.func,
217 func_ref,
218 block,
219 inst,
220 opcode,
221 &callee,
222 Some(exception),
223 )?;
224 inlined_any = true;
225 if visit_callee {
226 cursor.set_position(prev_pos);
227 } else {
228 cursor.goto_bottom(last_inlined_block);
232 continue 'block_loop;
233 }
234 }
235 }
236 }
237 }
238 ir::InstructionData::CallIndirect { .. }
239 | ir::InstructionData::TryCallIndirect { .. } => {
240 }
243 _ => {
244 debug_assert!(
245 !cursor.func.dfg.insts[inst].opcode().is_call(),
246 "should have matched all call instructions, but found: {inst}: {}",
247 cursor.func.dfg.display_inst(inst),
248 );
249 }
250 }
251 }
252 }
253
254 if inlined_any {
255 trace!("function {} after inlining: {}", func.name, func);
256 } else {
257 trace!("function {} did not have any callees inlined", func.name);
258 }
259
260 Ok(inlined_any)
261}
262
263fn can_inline(caller: &ir::Function, callee: &ir::Function) -> bool {
266 if caller.signature.call_conv != CallConv::Tail
270 && callee.signature.call_conv == CallConv::Tail
273 && contains_opcode(callee, ir::Opcode::InterruptPoll)
274 {
275 trace!(
276 " --> keeping call because callee uses `interrupt_poll` and caller doesn't use `tail` convention"
277 );
278 return false;
279 }
280
281 true
282}
283
284fn contains_opcode(func: &ir::Function, opcode: ir::Opcode) -> bool {
286 func.layout
287 .blocks()
288 .flat_map(|b| func.layout.block_insts(b))
289 .any(|i| func.dfg.insts[i].opcode() == opcode)
290}
291
292#[derive(Default)]
293struct InliningAllocs {
294 values: SecondaryMap<ir::Value, PackedOption<ir::Value>>,
296
297 constants: SecondaryMap<ir::Constant, PackedOption<ir::Constant>>,
302
303 user_external_name_refs:
308 SecondaryMap<ir::UserExternalNameRef, PackedOption<ir::UserExternalNameRef>>,
309
310 calls_needing_exception_table_fixup: Vec<ir::Inst>,
326}
327
328impl InliningAllocs {
329 fn reset(&mut self, callee: &ir::Function) {
330 let InliningAllocs {
331 values,
332 constants,
333 user_external_name_refs,
334 calls_needing_exception_table_fixup,
335 } = self;
336
337 values.clear();
338 values.resize(callee.dfg.len_values());
339
340 constants.clear();
341 constants.resize(callee.dfg.constants.len());
342
343 user_external_name_refs.clear();
344 user_external_name_refs.resize(callee.params.user_named_funcs().len());
345
346 calls_needing_exception_table_fixup.clear();
350 }
351
352 fn inlined_external_name(&self, name: &ir::ExternalName) -> ir::ExternalName {
356 match name {
357 ir::ExternalName::User(name_ref) => {
358 ir::ExternalName::User(self.user_external_name_refs[*name_ref].expect(
359 "should have translated all `ir::UserExternalNameRef`s before translating \
360 entities that reference them",
361 ))
362 }
363 ir::ExternalName::TestCase(_)
364 | ir::ExternalName::LibCall(_)
365 | ir::ExternalName::KnownSymbol(_) => name.clone(),
366 }
367 }
368
369 fn set_inlined_value(
370 &mut self,
371 callee: &ir::Function,
372 callee_val: ir::Value,
373 inlined_val: ir::Value,
374 ) {
375 trace!(" --> callee {callee_val:?} = inlined {inlined_val:?}");
376 debug_assert!(self.values[callee_val].is_none());
377 let resolved_callee_val = callee.dfg.resolve_aliases(callee_val);
378 debug_assert!(self.values[resolved_callee_val].is_none());
379 self.values[resolved_callee_val] = Some(inlined_val).into();
380 }
381
382 fn get_inlined_value(&self, callee: &ir::Function, callee_val: ir::Value) -> Option<ir::Value> {
383 let resolved_callee_val = callee.dfg.resolve_aliases(callee_val);
384 self.values[resolved_callee_val].expand()
385 }
386}
387
388fn inline_one(
392 allocs: &mut InliningAllocs,
393 func: &mut ir::Function,
394 callee_func_ref: ir::FuncRef,
395 call_block: ir::Block,
396 call_inst: ir::Inst,
397 call_opcode: ir::Opcode,
398 callee: &ir::Function,
399 call_exception_table: Option<ir::ExceptionTable>,
400) -> CodegenResult<ir::Block> {
401 trace!(
402 "Inlining call {call_inst:?}: {}\n\
403 with callee = {callee:?}",
404 func.dfg.display_inst(call_inst)
405 );
406
407 let expected_callee_sig = func.dfg.ext_funcs[callee_func_ref].signature;
409 let expected_callee_sig = &func.dfg.signatures[expected_callee_sig];
410 assert_eq!(expected_callee_sig, &callee.signature);
411
412 allocs.reset(callee);
413
414 let entity_map = create_entities(allocs, func, callee)?;
417
418 let return_block = split_off_return_block(func, call_inst, call_opcode, callee);
421 let call_stack_map = replace_call_with_jump(allocs, func, call_inst, callee, &entity_map);
422
423 let mut last_inlined_block = inline_block_layout(func, call_block, callee, &entity_map);
427
428 let call_debug_tags = func.debug_tags.get(call_inst).to_vec();
433 func.debug_tags.set(call_inst, []);
434
435 for callee_block in Dfs::new().pre_order_iter(callee) {
441 let inlined_block = entity_map.inlined_block(callee_block);
442 trace!(
443 "Processing instructions in callee block {callee_block:?} (inlined block {inlined_block:?}"
444 );
445
446 let mut next_callee_inst = callee.layout.first_inst(callee_block);
447 while let Some(callee_inst) = next_callee_inst {
448 trace!(
449 "Processing callee instruction {callee_inst:?}: {}",
450 callee.dfg.display_inst(callee_inst)
451 );
452
453 let mut inst_remapper = InliningInstRemapper {
456 allocs: &allocs,
457 func,
458 callee,
459 entity_map: &entity_map,
460 error: None,
461 };
462 let inlined_inst_data = callee.dfg.insts[callee_inst].map(&mut inst_remapper);
463 if let Some(err) = inst_remapper.error.take() {
464 return Err(err);
465 }
466 let inlined_inst = func.dfg.make_inst(inlined_inst_data);
467 func.layout.append_inst(inlined_inst, inlined_block);
468
469 let debug_tags = callee.debug_tags.get(callee_inst);
472 if !debug_tags.is_empty() {
479 let tags = call_debug_tags
480 .iter()
481 .cloned()
482 .chain(debug_tags.iter().map(|tag| match *tag {
483 DebugTag::User(value) => DebugTag::User(value),
484 DebugTag::StackSlot(slot) => {
485 DebugTag::StackSlot(entity_map.inlined_stack_slot(slot))
486 }
487 }))
488 .collect::<SmallVec<[_; 4]>>();
489 func.debug_tags.set(inlined_inst, tags);
490 }
491
492 let opcode = callee.dfg.insts[callee_inst].opcode();
493 if opcode.is_return() {
494 if let Some(return_block) = return_block {
499 fixup_inst_that_returns(
500 allocs,
501 func,
502 callee,
503 &entity_map,
504 call_opcode,
505 inlined_inst,
506 callee_inst,
507 return_block,
508 call_stack_map.as_ref().map(|es| &**es),
509 );
510 } else {
511 debug_assert_eq!(call_opcode, ir::Opcode::ReturnCall);
516 }
517 } else {
518 let ctrl_typevar = callee.dfg.ctrl_typevar(callee_inst);
520 func.dfg.make_inst_results(inlined_inst, ctrl_typevar);
521
522 let callee_results = callee.dfg.inst_results(callee_inst);
524 let inlined_results = func.dfg.inst_results(inlined_inst);
525 debug_assert_eq!(callee_results.len(), inlined_results.len());
526 for (callee_val, inlined_val) in callee_results.iter().zip(inlined_results) {
527 allocs.set_inlined_value(callee, *callee_val, *inlined_val);
528 }
529
530 if opcode.is_safepoint() {
531 append_stack_map_entries(
532 func,
533 callee,
534 &entity_map,
535 call_stack_map.as_deref(),
536 inlined_inst,
537 callee_inst,
538 );
539 }
540
541 if opcode.is_call() {
542 debug_assert_eq!(
555 call_opcode == ir::Opcode::TryCall,
556 call_exception_table.is_some()
557 );
558 if call_opcode == ir::Opcode::TryCall {
559 allocs
560 .calls_needing_exception_table_fixup
561 .push(inlined_inst);
562 }
563 }
564 }
565
566 trace!(
567 " --> inserted inlined instruction {inlined_inst:?}: {}",
568 func.dfg.display_inst(inlined_inst)
569 );
570
571 next_callee_inst = callee.layout.next_inst(callee_inst);
572 }
573 }
574
575 for block in entity_map.iter_inlined_blocks(func) {
582 if func.layout.is_block_inserted(block) && func.layout.first_inst(block).is_none() {
583 log::trace!("removing unreachable inlined block from layout: {block}");
584
585 if block == last_inlined_block {
589 last_inlined_block = func.layout.prev_block(last_inlined_block).expect(
590 "there will always at least be the block that contained the call we are \
591 inlining",
592 );
593 }
594
595 func.layout.remove_block(block);
596 }
597 }
598
599 debug_assert!(
610 allocs.calls_needing_exception_table_fixup.is_empty() || call_exception_table.is_some()
611 );
612 debug_assert_eq!(
613 call_opcode == ir::Opcode::TryCall,
614 call_exception_table.is_some()
615 );
616 if let Some(call_exception_table) = call_exception_table {
617 fixup_inlined_call_exception_tables(allocs, func, call_exception_table);
618 }
619
620 debug_assert!(
621 func.layout.is_block_inserted(last_inlined_block),
622 "last_inlined_block={last_inlined_block} should be inserted in the layout"
623 );
624 Ok(last_inlined_block)
625}
626
627fn append_stack_map_entries(
630 func: &mut ir::Function,
631 callee: &ir::Function,
632 entity_map: &EntityMap,
633 call_stack_map: Option<&[ir::UserStackMapEntry]>,
634 inlined_inst: ir::Inst,
635 callee_inst: ir::Inst,
636) {
637 func.dfg.append_user_stack_map_entries(
641 inlined_inst,
642 call_stack_map
643 .iter()
644 .flat_map(|entries| entries.iter().cloned()),
645 );
646
647 func.dfg.append_user_stack_map_entries(
651 inlined_inst,
652 callee
653 .dfg
654 .user_stack_map_entries(callee_inst)
655 .iter()
656 .flat_map(|entries| entries.iter())
657 .map(|entry| ir::UserStackMapEntry {
658 ty: entry.ty,
659 slot: entity_map.inlined_stack_slot(entry.slot),
660 offset: entry.offset,
661 }),
662 );
663}
664
665fn fixup_inlined_call_exception_tables(
669 allocs: &mut InliningAllocs,
670 func: &mut ir::Function,
671 call_exception_table: ir::ExceptionTable,
672) {
673 let split_block_for_new_try_call = |func: &mut ir::Function, inst: ir::Inst| -> ir::Block {
676 debug_assert!(func.dfg.insts[inst].opcode().is_call());
677 debug_assert!(!func.dfg.insts[inst].opcode().is_terminator());
678
679 let next_inst = func
681 .layout
682 .next_inst(inst)
683 .expect("inst is not a terminator, should have a successor");
684 let new_block = func.dfg.blocks.add();
685 func.layout.split_block(new_block, next_inst);
686
687 let old_results = SmallValueVec::from_iter(func.dfg.inst_results(inst).iter().copied());
692 func.dfg.detach_inst_results(inst);
693 for old_result in old_results {
694 let ty = func.dfg.value_type(old_result);
695 let new_block_param = func.dfg.append_block_param(new_block, ty);
696 func.dfg.change_to_alias(old_result, new_block_param);
697 }
698
699 new_block
700 };
701
702 let clone_exception_table_for_this_call = |func: &mut ir::Function,
705 signature: ir::SigRef,
706 new_block: ir::Block|
707 -> ir::ExceptionTable {
708 let mut exception = func.stencil.dfg.exception_tables[call_exception_table]
709 .deep_clone(&mut func.stencil.dfg.value_lists);
710
711 *exception.signature_mut() = signature;
712
713 let returns_len = func.dfg.signatures[signature].returns.len();
714 let returns_len = u32::try_from(returns_len).unwrap();
715
716 *exception.normal_return_mut() = ir::BlockCall::new(
717 new_block,
718 (0..returns_len).map(|i| ir::BlockArg::TryCallRet(i)),
719 &mut func.dfg.value_lists,
720 );
721
722 func.dfg.exception_tables.push(exception)
723 };
724
725 for inst in allocs.calls_needing_exception_table_fixup.drain(..) {
726 debug_assert!(func.dfg.insts[inst].opcode().is_call());
727 debug_assert!(!func.dfg.insts[inst].opcode().is_return());
728 match func.dfg.insts[inst] {
729 ir::InstructionData::Call {
742 opcode: ir::Opcode::Call,
743 args,
744 func_ref,
745 } => {
746 let new_block = split_block_for_new_try_call(func, inst);
747 let signature = func.dfg.ext_funcs[func_ref].signature;
748 let exception = clone_exception_table_for_this_call(func, signature, new_block);
749 func.dfg.insts[inst] = ir::InstructionData::TryCall {
750 opcode: ir::Opcode::TryCall,
751 args,
752 func_ref,
753 exception,
754 };
755 }
756
757 ir::InstructionData::CallIndirect {
770 opcode: ir::Opcode::CallIndirect,
771 args,
772 sig_ref,
773 } => {
774 let new_block = split_block_for_new_try_call(func, inst);
775 let exception = clone_exception_table_for_this_call(func, sig_ref, new_block);
776 func.dfg.insts[inst] = ir::InstructionData::TryCallIndirect {
777 opcode: ir::Opcode::TryCallIndirect,
778 args,
779 exception,
780 };
781 }
782
783 ir::InstructionData::TryCall {
786 opcode: ir::Opcode::TryCall,
787 exception,
788 ..
789 }
790 | ir::InstructionData::TryCallIndirect {
791 opcode: ir::Opcode::TryCallIndirect,
792 exception,
793 ..
794 } => {
795 let sig = func.dfg.exception_tables[exception].signature();
802 let normal_return = *func.dfg.exception_tables[exception].normal_return();
803 let exception_data = ExceptionTableData::new(
804 sig,
805 normal_return,
806 func.dfg.exception_tables[exception]
807 .items()
808 .chain(func.dfg.exception_tables[call_exception_table].items()),
809 )
810 .deep_clone(&mut func.dfg.value_lists);
811
812 func.dfg.exception_tables[exception] = exception_data;
813 }
814
815 otherwise => unreachable!("unknown non-return call instruction: {otherwise:?}"),
816 }
817 }
818}
819
820fn fixup_inst_that_returns(
825 allocs: &mut InliningAllocs,
826 func: &mut ir::Function,
827 callee: &ir::Function,
828 entity_map: &EntityMap,
829 call_opcode: ir::Opcode,
830 inlined_inst: ir::Inst,
831 callee_inst: ir::Inst,
832 return_block: ir::Block,
833 call_stack_map: Option<&[ir::UserStackMapEntry]>,
834) {
835 debug_assert!(func.dfg.insts[inlined_inst].opcode().is_return());
836 match func.dfg.insts[inlined_inst] {
837 ir::InstructionData::MultiAry {
843 opcode: ir::Opcode::Return,
844 args,
845 } => {
846 let rets = SmallBlockArgVec::from_iter(
847 args.as_slice(&func.dfg.value_lists)
848 .iter()
849 .copied()
850 .map(|v| v.into()),
851 );
852 func.replace(inlined_inst).jump(return_block, &rets);
853 }
854
855 ir::InstructionData::Call {
862 opcode: ir::Opcode::ReturnCall,
863 args,
864 func_ref,
865 } => {
866 func.dfg.insts[inlined_inst] = ir::InstructionData::Call {
867 opcode: ir::Opcode::Call,
868 args,
869 func_ref,
870 };
871 func.dfg.make_inst_results(inlined_inst, ir::types::INVALID);
872
873 append_stack_map_entries(
874 func,
875 callee,
876 &entity_map,
877 call_stack_map,
878 inlined_inst,
879 callee_inst,
880 );
881
882 let rets = SmallBlockArgVec::from_iter(
883 func.dfg
884 .inst_results(inlined_inst)
885 .iter()
886 .copied()
887 .map(|v| v.into()),
888 );
889 let mut cursor = FuncCursor::new(func);
890 cursor.goto_after_inst(inlined_inst);
891 cursor.ins().jump(return_block, &rets);
892
893 if call_opcode == ir::Opcode::TryCall {
894 allocs
895 .calls_needing_exception_table_fixup
896 .push(inlined_inst);
897 }
898 }
899
900 ir::InstructionData::CallIndirect {
907 opcode: ir::Opcode::ReturnCallIndirect,
908 args,
909 sig_ref,
910 } => {
911 func.dfg.insts[inlined_inst] = ir::InstructionData::CallIndirect {
912 opcode: ir::Opcode::CallIndirect,
913 args,
914 sig_ref,
915 };
916 func.dfg.make_inst_results(inlined_inst, ir::types::INVALID);
917
918 append_stack_map_entries(
919 func,
920 callee,
921 &entity_map,
922 call_stack_map,
923 inlined_inst,
924 callee_inst,
925 );
926
927 let rets = SmallBlockArgVec::from_iter(
928 func.dfg
929 .inst_results(inlined_inst)
930 .iter()
931 .copied()
932 .map(|v| v.into()),
933 );
934 let mut cursor = FuncCursor::new(func);
935 cursor.goto_after_inst(inlined_inst);
936 cursor.ins().jump(return_block, &rets);
937
938 if call_opcode == ir::Opcode::TryCall {
939 allocs
940 .calls_needing_exception_table_fixup
941 .push(inlined_inst);
942 }
943 }
944
945 inst_data => unreachable!(
946 "should have handled all `is_return() == true` instructions above; \
947 got {inst_data:?}"
948 ),
949 }
950}
951
952struct InliningInstRemapper<'a> {
955 allocs: &'a InliningAllocs,
956 func: &'a mut ir::Function,
957 callee: &'a ir::Function,
958 entity_map: &'a EntityMap,
959 error: Option<crate::result::CodegenError>,
960}
961
962impl<'a> ir::instructions::InstructionMapper for InliningInstRemapper<'a> {
963 fn map_value(&mut self, value: ir::Value) -> ir::Value {
964 self.allocs.get_inlined_value(self.callee, value).expect(
965 "defs come before uses; we should have already inlined all values \
966 used by an instruction",
967 )
968 }
969
970 fn map_value_list(&mut self, value_list: ir::ValueList) -> ir::ValueList {
971 let mut inlined_list = ir::ValueList::new();
972 for callee_val in value_list.as_slice(&self.callee.dfg.value_lists) {
973 let inlined_val = self.map_value(*callee_val);
974 inlined_list.push(inlined_val, &mut self.func.dfg.value_lists);
975 }
976 inlined_list
977 }
978
979 fn map_global_value(&mut self, global_value: ir::GlobalValue) -> ir::GlobalValue {
980 self.entity_map.inlined_global_value(global_value)
981 }
982
983 fn map_jump_table(&mut self, jump_table: ir::JumpTable) -> ir::JumpTable {
984 let inlined_default =
985 self.map_block_call(self.callee.dfg.jump_tables[jump_table].default_block());
986 let inlined_table = self.callee.dfg.jump_tables[jump_table]
987 .as_slice()
988 .iter()
989 .map(|callee_block_call| self.map_block_call(*callee_block_call))
990 .collect::<SmallBlockCallVec>();
991 self.func
992 .dfg
993 .jump_tables
994 .push(ir::JumpTableData::new(inlined_default, &inlined_table))
995 }
996
997 fn map_exception_table(&mut self, exception_table: ir::ExceptionTable) -> ir::ExceptionTable {
998 let exception_table = &self.callee.dfg.exception_tables[exception_table];
999 let inlined_sig_ref = self.map_sig_ref(exception_table.signature());
1000 let inlined_normal_return = self.map_block_call(*exception_table.normal_return());
1001 let inlined_table = exception_table
1002 .items()
1003 .map(|item| match item {
1004 ExceptionTableItem::Tag(tag, block_call) => {
1005 ExceptionTableItem::Tag(tag, self.map_block_call(block_call))
1006 }
1007 ExceptionTableItem::Default(block_call) => {
1008 ExceptionTableItem::Default(self.map_block_call(block_call))
1009 }
1010 ExceptionTableItem::Context(value) => {
1011 ExceptionTableItem::Context(self.map_value(value))
1012 }
1013 })
1014 .collect::<SmallVec<[_; 8]>>();
1015 self.func
1016 .dfg
1017 .exception_tables
1018 .push(ir::ExceptionTableData::new(
1019 inlined_sig_ref,
1020 inlined_normal_return,
1021 inlined_table,
1022 ))
1023 }
1024
1025 fn map_block_call(&mut self, block_call: ir::BlockCall) -> ir::BlockCall {
1026 let callee_block = block_call.block(&self.callee.dfg.value_lists);
1027 let inlined_block = self.entity_map.inlined_block(callee_block);
1028 let args = block_call
1029 .args(&self.callee.dfg.value_lists)
1030 .map(|arg| match arg {
1031 ir::BlockArg::Value(value) => self.map_value(value).into(),
1032 ir::BlockArg::TryCallRet(_) | ir::BlockArg::TryCallExn(_) => arg,
1033 })
1034 .collect::<SmallBlockArgVec>();
1035 ir::BlockCall::new(inlined_block, args, &mut self.func.dfg.value_lists)
1036 }
1037
1038 fn map_block(&mut self, block: ir::Block) -> ir::Block {
1039 self.entity_map.inlined_block(block)
1040 }
1041
1042 fn map_func_ref(&mut self, func_ref: ir::FuncRef) -> ir::FuncRef {
1043 self.entity_map.inlined_func_ref(func_ref)
1044 }
1045
1046 fn map_sig_ref(&mut self, sig_ref: ir::SigRef) -> ir::SigRef {
1047 self.entity_map.inlined_sig_ref(sig_ref)
1048 }
1049
1050 fn map_stack_slot(&mut self, stack_slot: ir::StackSlot) -> ir::StackSlot {
1051 self.entity_map.inlined_stack_slot(stack_slot)
1052 }
1053
1054 fn map_dynamic_stack_slot(
1055 &mut self,
1056 dynamic_stack_slot: ir::DynamicStackSlot,
1057 ) -> ir::DynamicStackSlot {
1058 self.entity_map
1059 .inlined_dynamic_stack_slot(dynamic_stack_slot)
1060 }
1061
1062 fn map_constant(&mut self, constant: ir::Constant) -> ir::Constant {
1063 self.allocs
1064 .constants
1065 .get(constant)
1066 .and_then(|o| o.expand())
1067 .expect("should have inlined all callee constants")
1068 }
1069
1070 fn map_immediate(&mut self, immediate: ir::Immediate) -> ir::Immediate {
1071 self.entity_map.inlined_immediate(immediate)
1072 }
1073 fn map_mem_flags(&mut self, flags: ir::MemFlags) -> ir::MemFlags {
1074 let mut flags_data = self.callee.dfg.mem_flags[flags];
1075 if let Some(callee_region) = flags_data.alias_region() {
1077 let region_data = self.callee.dfg.alias_regions[callee_region].clone();
1078 let caller_region = self.func.dfg.alias_regions.insert(region_data);
1079 flags_data.set_alias_region(Some(caller_region));
1080 }
1081 match self.func.dfg.mem_flags.insert(flags_data) {
1082 Ok(flags) => flags,
1083 Err(_) => {
1084 self.error = Some(crate::result::CodegenError::ImplLimitExceeded);
1085 self.func
1086 .dfg
1087 .mem_flags
1088 .insert(ir::MemFlagsData::trusted())
1089 .unwrap()
1090 }
1091 }
1092 }
1093}
1094
1095fn inline_block_layout(
1099 func: &mut ir::Function,
1100 call_block: ir::Block,
1101 callee: &ir::Function,
1102 entity_map: &EntityMap,
1103) -> ir::Block {
1104 debug_assert!(func.layout.is_block_inserted(call_block));
1105
1106 let mut prev_inlined_block = call_block;
1109 let mut next_callee_block = callee.layout.entry_block();
1110 while let Some(callee_block) = next_callee_block {
1111 debug_assert!(func.layout.is_block_inserted(prev_inlined_block));
1112
1113 let inlined_block = entity_map.inlined_block(callee_block);
1114 func.layout
1115 .insert_block_after(inlined_block, prev_inlined_block);
1116
1117 prev_inlined_block = inlined_block;
1118 next_callee_block = callee.layout.next_block(callee_block);
1119 }
1120
1121 debug_assert!(func.layout.is_block_inserted(prev_inlined_block));
1122 prev_inlined_block
1123}
1124
1125fn split_off_return_block(
1131 func: &mut ir::Function,
1132 call_inst: ir::Inst,
1133 opcode: ir::Opcode,
1134 callee: &ir::Function,
1135) -> Option<ir::Block> {
1136 let return_block = func.layout.next_inst(call_inst).map(|next_inst| {
1139 let return_block = func.dfg.blocks.add();
1140 func.layout.split_block(return_block, next_inst);
1141
1142 let old_results =
1145 SmallValueVec::from_iter(func.dfg.inst_results(call_inst).iter().copied());
1146 debug_assert_eq!(old_results.len(), callee.signature.returns.len());
1147 func.dfg.detach_inst_results(call_inst);
1148 for (abi, old_val) in callee.signature.returns.iter().zip(old_results) {
1149 debug_assert_eq!(abi.value_type, func.dfg.value_type(old_val));
1150 let ret_param = func.dfg.append_block_param(return_block, abi.value_type);
1151 func.dfg.change_to_alias(old_val, ret_param);
1152 }
1153
1154 return_block
1155 });
1156
1157 debug_assert_eq!(
1188 return_block.is_none(),
1189 opcode == ir::Opcode::ReturnCall || opcode == ir::Opcode::TryCall,
1190 );
1191 return_block.or_else(|| match func.dfg.insts[call_inst] {
1192 ir::InstructionData::TryCall {
1193 opcode: ir::Opcode::TryCall,
1194 args: _,
1195 func_ref: _,
1196 exception,
1197 } => {
1198 let normal_return = func.dfg.exception_tables[exception].normal_return();
1199 let normal_return_block = normal_return.block(&func.dfg.value_lists);
1200
1201 {
1203 let normal_return_args = normal_return.args(&func.dfg.value_lists);
1204 if normal_return_args.len() == callee.signature.returns.len()
1205 && normal_return_args.enumerate().all(|(i, arg)| {
1206 let i = u32::try_from(i).unwrap();
1207 arg == ir::BlockArg::TryCallRet(i)
1208 })
1209 {
1210 return Some(normal_return_block);
1211 }
1212 }
1213
1214 let return_block = func.dfg.blocks.add();
1218 func.layout.insert_block(return_block, normal_return_block);
1219
1220 let return_block_params = callee
1221 .signature
1222 .returns
1223 .iter()
1224 .map(|abi| func.dfg.append_block_param(return_block, abi.value_type))
1225 .collect::<SmallValueVec>();
1226
1227 let normal_return_args = func.dfg.exception_tables[exception]
1228 .normal_return()
1229 .args(&func.dfg.value_lists)
1230 .collect::<SmallBlockArgVec>();
1231 let jump_args = normal_return_args
1232 .into_iter()
1233 .map(|arg| match arg {
1234 ir::BlockArg::Value(value) => ir::BlockArg::Value(value),
1235 ir::BlockArg::TryCallRet(i) => {
1236 let i = usize::try_from(i).unwrap();
1237 ir::BlockArg::Value(return_block_params[i])
1238 }
1239 ir::BlockArg::TryCallExn(_) => {
1240 unreachable!("normal-return edges cannot use exceptional results")
1241 }
1242 })
1243 .collect::<SmallBlockArgVec>();
1244
1245 let mut cursor = FuncCursor::new(func);
1246 cursor.goto_first_insertion_point(return_block);
1247 cursor.ins().jump(normal_return_block, &jump_args);
1248
1249 Some(return_block)
1250 }
1251 _ => None,
1252 })
1253}
1254
1255fn replace_call_with_jump(
1263 allocs: &mut InliningAllocs,
1264 func: &mut ir::Function,
1265 call_inst: ir::Inst,
1266 callee: &ir::Function,
1267 entity_map: &EntityMap,
1268) -> Option<ir::UserStackMapEntryVec> {
1269 trace!("Replacing `call` with `jump`");
1270 trace!(
1271 " --> call instruction: {call_inst:?}: {}",
1272 func.dfg.display_inst(call_inst)
1273 );
1274
1275 let callee_entry_block = callee
1276 .layout
1277 .entry_block()
1278 .expect("callee function should have an entry block");
1279 let callee_param_values = callee.dfg.block_params(callee_entry_block);
1280 let caller_arg_values = SmallValueVec::from_iter(func.dfg.inst_args(call_inst).iter().copied());
1281 debug_assert_eq!(callee_param_values.len(), caller_arg_values.len());
1282 debug_assert_eq!(callee_param_values.len(), callee.signature.params.len());
1283 for (abi, (callee_param_value, caller_arg_value)) in callee
1284 .signature
1285 .params
1286 .iter()
1287 .zip(callee_param_values.into_iter().zip(caller_arg_values))
1288 {
1289 debug_assert_eq!(abi.value_type, callee.dfg.value_type(*callee_param_value));
1290 debug_assert_eq!(abi.value_type, func.dfg.value_type(caller_arg_value));
1291 allocs.set_inlined_value(callee, *callee_param_value, caller_arg_value);
1292 }
1293
1294 let inlined_entry_block = entity_map.inlined_block(callee_entry_block);
1301 func.replace(call_inst).jump(inlined_entry_block, &[]);
1302 trace!(
1303 " --> replaced with jump instruction: {call_inst:?}: {}",
1304 func.dfg.display_inst(call_inst)
1305 );
1306
1307 let stack_map_entries = func.dfg.take_user_stack_map_entries(call_inst);
1308 stack_map_entries
1309}
1310
1311#[derive(Default)]
1314struct EntityMap {
1315 block_offset: Option<u32>,
1328 global_value_offset: Option<u32>,
1329 sig_ref_offset: Option<u32>,
1330 func_ref_offset: Option<u32>,
1331 stack_slot_offset: Option<u32>,
1332 dynamic_type_offset: Option<u32>,
1333 dynamic_stack_slot_offset: Option<u32>,
1334 immediate_offset: Option<u32>,
1335}
1336
1337impl EntityMap {
1338 fn inlined_block(&self, callee_block: ir::Block) -> ir::Block {
1339 let offset = self
1340 .block_offset
1341 .expect("must create inlined `ir::Block`s before calling `EntityMap::inlined_block`");
1342 ir::Block::from_u32(offset + callee_block.as_u32())
1343 }
1344
1345 fn iter_inlined_blocks(&self, func: &ir::Function) -> impl Iterator<Item = ir::Block> + use<> {
1346 let start = self.block_offset.expect(
1347 "must create inlined `ir::Block`s before calling `EntityMap::iter_inlined_blocks`",
1348 );
1349
1350 let end = func.dfg.blocks.len();
1351 let end = u32::try_from(end).unwrap();
1352
1353 (start..end).map(|i| ir::Block::from_u32(i))
1354 }
1355
1356 fn inlined_global_value(&self, callee_global_value: ir::GlobalValue) -> ir::GlobalValue {
1357 let offset = self
1358 .global_value_offset
1359 .expect("must create inlined `ir::GlobalValue`s before calling `EntityMap::inlined_global_value`");
1360 ir::GlobalValue::from_u32(offset + callee_global_value.as_u32())
1361 }
1362
1363 fn inlined_sig_ref(&self, callee_sig_ref: ir::SigRef) -> ir::SigRef {
1364 let offset = self.sig_ref_offset.expect(
1365 "must create inlined `ir::SigRef`s before calling `EntityMap::inlined_sig_ref`",
1366 );
1367 ir::SigRef::from_u32(offset + callee_sig_ref.as_u32())
1368 }
1369
1370 fn inlined_func_ref(&self, callee_func_ref: ir::FuncRef) -> ir::FuncRef {
1371 let offset = self.func_ref_offset.expect(
1372 "must create inlined `ir::FuncRef`s before calling `EntityMap::inlined_func_ref`",
1373 );
1374 ir::FuncRef::from_u32(offset + callee_func_ref.as_u32())
1375 }
1376
1377 fn inlined_stack_slot(&self, callee_stack_slot: ir::StackSlot) -> ir::StackSlot {
1378 let offset = self.stack_slot_offset.expect(
1379 "must create inlined `ir::StackSlot`s before calling `EntityMap::inlined_stack_slot`",
1380 );
1381 ir::StackSlot::from_u32(offset + callee_stack_slot.as_u32())
1382 }
1383
1384 fn inlined_dynamic_type(&self, callee_dynamic_type: ir::DynamicType) -> ir::DynamicType {
1385 let offset = self.dynamic_type_offset.expect(
1386 "must create inlined `ir::DynamicType`s before calling `EntityMap::inlined_dynamic_type`",
1387 );
1388 ir::DynamicType::from_u32(offset + callee_dynamic_type.as_u32())
1389 }
1390
1391 fn inlined_dynamic_stack_slot(
1392 &self,
1393 callee_dynamic_stack_slot: ir::DynamicStackSlot,
1394 ) -> ir::DynamicStackSlot {
1395 let offset = self.dynamic_stack_slot_offset.expect(
1396 "must create inlined `ir::DynamicStackSlot`s before calling `EntityMap::inlined_dynamic_stack_slot`",
1397 );
1398 ir::DynamicStackSlot::from_u32(offset + callee_dynamic_stack_slot.as_u32())
1399 }
1400
1401 fn inlined_immediate(&self, callee_immediate: ir::Immediate) -> ir::Immediate {
1402 let offset = self.immediate_offset.expect(
1403 "must create inlined `ir::Immediate`s before calling `EntityMap::inlined_immediate`",
1404 );
1405 ir::Immediate::from_u32(offset + callee_immediate.as_u32())
1406 }
1407}
1408
1409fn create_entities(
1413 allocs: &mut InliningAllocs,
1414 func: &mut ir::Function,
1415 callee: &ir::Function,
1416) -> CodegenResult<EntityMap> {
1417 let mut entity_map = EntityMap::default();
1418
1419 entity_map.block_offset = Some(create_blocks(allocs, func, callee));
1420 create_user_external_name_refs(allocs, func, callee);
1421 entity_map.global_value_offset = Some(create_global_values(allocs, func, callee)?);
1422 entity_map.sig_ref_offset = Some(create_sig_refs(func, callee));
1423 entity_map.func_ref_offset = Some(create_func_refs(allocs, func, callee, &entity_map));
1424 entity_map.stack_slot_offset = Some(create_stack_slots(func, callee));
1425 entity_map.dynamic_type_offset = Some(create_dynamic_types(func, callee, &entity_map));
1426 entity_map.dynamic_stack_slot_offset =
1427 Some(create_dynamic_stack_slots(func, callee, &entity_map));
1428 entity_map.immediate_offset = Some(create_immediates(func, callee));
1429
1430 create_constants(allocs, func, callee);
1434
1435 Ok(entity_map)
1436}
1437
1438fn create_blocks(
1440 allocs: &mut InliningAllocs,
1441 func: &mut ir::Function,
1442 callee: &ir::Function,
1443) -> u32 {
1444 let offset = func.dfg.blocks.len();
1445 let offset = u32::try_from(offset).unwrap();
1446
1447 func.dfg.blocks.reserve(callee.dfg.blocks.len());
1448 for callee_block in callee.dfg.blocks.iter() {
1449 let caller_block = func.dfg.blocks.add();
1450 trace!("Callee {callee_block:?} = inlined {caller_block:?}");
1451
1452 if callee.layout.is_cold(callee_block) {
1453 func.layout.set_cold(caller_block);
1454 }
1455
1456 if callee.layout.entry_block() != Some(callee_block) {
1460 for callee_param in callee.dfg.blocks[callee_block].params(&callee.dfg.value_lists) {
1461 let ty = callee.dfg.value_type(*callee_param);
1462 let caller_param = func.dfg.append_block_param(caller_block, ty);
1463
1464 allocs.set_inlined_value(callee, *callee_param, caller_param);
1465 }
1466 }
1467 }
1468
1469 offset
1470}
1471
1472fn create_global_values(
1474 allocs: &InliningAllocs,
1475 func: &mut ir::Function,
1476 callee: &ir::Function,
1477) -> CodegenResult<u32> {
1478 let gv_offset = func.global_values.len();
1479 let gv_offset = u32::try_from(gv_offset).unwrap();
1480
1481 func.global_values.reserve(callee.global_values.len());
1482 for gv in callee.global_values.values() {
1483 let remapped_flags = match gv {
1486 ir::GlobalValueData::Load { flags, .. } => {
1487 let mut flags_data = callee.dfg.mem_flags[*flags];
1488 if let Some(callee_region) = flags_data.alias_region() {
1490 let region_data = callee.dfg.alias_regions[callee_region].clone();
1491 let caller_region = func.dfg.alias_regions.insert(region_data);
1492 flags_data.set_alias_region(Some(caller_region));
1493 }
1494 Some(
1495 func.dfg
1496 .mem_flags
1497 .insert(flags_data)
1498 .map_err(|_| crate::result::CodegenError::ImplLimitExceeded)?,
1499 )
1500 }
1501 _ => None,
1502 };
1503 func.global_values.push(match gv {
1504 ir::GlobalValueData::Load {
1507 base,
1508 offset,
1509 global_type,
1510 flags: _,
1511 } => ir::GlobalValueData::Load {
1512 base: ir::GlobalValue::from_u32(base.as_u32() + gv_offset),
1513 offset: *offset,
1514 global_type: *global_type,
1515 flags: remapped_flags.unwrap(),
1516 },
1517 ir::GlobalValueData::IAddImm {
1518 base,
1519 offset,
1520 global_type,
1521 } => ir::GlobalValueData::IAddImm {
1522 base: ir::GlobalValue::from_u32(base.as_u32() + gv_offset),
1523 offset: *offset,
1524 global_type: *global_type,
1525 },
1526
1527 ir::GlobalValueData::Symbol {
1530 name,
1531 offset,
1532 colocated,
1533 tls,
1534 } => ir::GlobalValueData::Symbol {
1535 name: allocs.inlined_external_name(name),
1536 offset: *offset,
1537 colocated: *colocated,
1538 tls: *tls,
1539 },
1540
1541 ir::GlobalValueData::VMContext | ir::GlobalValueData::DynScaleTargetConst { .. } => {
1544 gv.clone()
1545 }
1546 });
1547 }
1548
1549 Ok(gv_offset)
1550}
1551
1552fn create_sig_refs(func: &mut ir::Function, callee: &ir::Function) -> u32 {
1554 let offset = func.dfg.signatures.len();
1555 let offset = u32::try_from(offset).unwrap();
1556
1557 func.dfg.signatures.reserve(callee.dfg.signatures.len());
1558 for sig in callee.dfg.signatures.values() {
1559 func.dfg.signatures.push(sig.clone());
1560 }
1561
1562 offset
1563}
1564
1565fn create_user_external_name_refs(
1566 allocs: &mut InliningAllocs,
1567 func: &mut ir::Function,
1568 callee: &ir::Function,
1569) {
1570 for (callee_named_func_ref, name) in callee.params.user_named_funcs().iter() {
1571 let caller_named_func_ref = func.declare_imported_user_function(name.clone());
1572 allocs.user_external_name_refs[callee_named_func_ref] = Some(caller_named_func_ref).into();
1573 }
1574}
1575
1576fn create_func_refs(
1578 allocs: &InliningAllocs,
1579 func: &mut ir::Function,
1580 callee: &ir::Function,
1581 entity_map: &EntityMap,
1582) -> u32 {
1583 let offset = func.dfg.ext_funcs.len();
1584 let offset = u32::try_from(offset).unwrap();
1585
1586 func.dfg.ext_funcs.reserve(callee.dfg.ext_funcs.len());
1587 for ir::ExtFuncData {
1588 name,
1589 signature,
1590 colocated,
1591 patchable,
1592 } in callee.dfg.ext_funcs.values()
1593 {
1594 func.dfg.ext_funcs.push(ir::ExtFuncData {
1595 name: allocs.inlined_external_name(name),
1596 signature: entity_map.inlined_sig_ref(*signature),
1597 colocated: *colocated,
1598 patchable: *patchable,
1599 });
1600 }
1601
1602 offset
1603}
1604
1605fn create_stack_slots(func: &mut ir::Function, callee: &ir::Function) -> u32 {
1607 let offset = func.sized_stack_slots.len();
1608 let offset = u32::try_from(offset).unwrap();
1609
1610 func.sized_stack_slots
1611 .reserve(callee.sized_stack_slots.len());
1612 for slot in callee.sized_stack_slots.values() {
1613 func.sized_stack_slots.push(slot.clone());
1614 }
1615
1616 offset
1617}
1618
1619fn create_dynamic_types(
1621 func: &mut ir::Function,
1622 callee: &ir::Function,
1623 entity_map: &EntityMap,
1624) -> u32 {
1625 let offset = func.dfg.dynamic_types.len();
1626 let offset = u32::try_from(offset).unwrap();
1627
1628 func.dfg
1629 .dynamic_types
1630 .reserve(callee.dfg.dynamic_types.len());
1631 for ir::DynamicTypeData {
1632 base_vector_ty,
1633 dynamic_scale,
1634 } in callee.dfg.dynamic_types.values()
1635 {
1636 func.dfg.dynamic_types.push(ir::DynamicTypeData {
1637 base_vector_ty: *base_vector_ty,
1638 dynamic_scale: entity_map.inlined_global_value(*dynamic_scale),
1639 });
1640 }
1641
1642 offset
1643}
1644
1645fn create_dynamic_stack_slots(
1647 func: &mut ir::Function,
1648 callee: &ir::Function,
1649 entity_map: &EntityMap,
1650) -> u32 {
1651 let offset = func.dynamic_stack_slots.len();
1652 let offset = u32::try_from(offset).unwrap();
1653
1654 func.dynamic_stack_slots
1655 .reserve(callee.dynamic_stack_slots.len());
1656 for ir::DynamicStackSlotData { kind, dyn_ty } in callee.dynamic_stack_slots.values() {
1657 func.dynamic_stack_slots.push(ir::DynamicStackSlotData {
1658 kind: *kind,
1659 dyn_ty: entity_map.inlined_dynamic_type(*dyn_ty),
1660 });
1661 }
1662
1663 offset
1664}
1665
1666fn create_immediates(func: &mut ir::Function, callee: &ir::Function) -> u32 {
1668 let offset = func.dfg.immediates.len();
1669 let offset = u32::try_from(offset).unwrap();
1670
1671 func.dfg.immediates.reserve(callee.dfg.immediates.len());
1672 for imm in callee.dfg.immediates.values() {
1673 func.dfg.immediates.push(imm.clone());
1674 }
1675
1676 offset
1677}
1678
1679fn create_constants(allocs: &mut InliningAllocs, func: &mut ir::Function, callee: &ir::Function) {
1681 for (callee_constant, data) in callee.dfg.constants.iter() {
1682 let inlined_constant = func.dfg.constants.insert(data.clone());
1683 allocs.constants[*callee_constant] = Some(inlined_constant).into();
1684 }
1685}