-------------------------------------------------------------------------------- I1 cache: 65536 B, 64 B, 4-way associative D1 cache: 32768 B, 64 B, 8-way associative LL cache: 67108864 B, 64 B, 64-way associative Command: /usr/home/liquid/.rustup/toolchains/w-profiling/bin/rustc --crate-name nalgebra --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 --cfg feature="default" --cfg feature="macros" --cfg feature="matrixmultiply" --cfg feature="nalgebra-macros" --cfg feature="std" -C metadata=b27165e65df9e056 -C extra-filename=-b27165e65df9e056 --out-dir /usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps --extern approx=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libapprox-e4d68a8dca88be37.rmeta --extern matrixmultiply=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libmatrixmultiply-534be5dd1273bbb2.rmeta --extern nalgebra_macros=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libnalgebra_macros-a9a14f9103394214.so --extern num_complex=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libnum_complex-46153a8469c9c09c.rmeta --extern num_rational=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libnum_rational-51f3c57b12cce66d.rmeta --extern num_traits=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libnum_traits-6b6763f982734bb1.rmeta --extern simba=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libsimba-bd2ae116ee8a2a46.rmeta --extern typenum=/usr/home/liquid/tmp/.tmpU78rcl/target/debug/deps/libtypenum-08afab276e94ea48.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-nalgebra-0.30.1-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 116,425,528,698 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 1,942,632,735 ( 1.67%) ./malloc/malloc.c:_int_free 1,216,390,968 ( 1.04%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 1,152,800,202 ( 0.99%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs:::match_impl 1,146,738,247 ( 0.98%) ./malloc/malloc.c:malloc 933,902,553 ( 0.80%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_super_fold_with:: 894,021,689 ( 0.77%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::anonymize_late_bound_regions:: 871,101,278 ( 0.75%) ./malloc/malloc.c:_int_malloc 858,714,392 ( 0.74%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 839,446,833 ( 0.72%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs:rustc_middle::ty::relate::super_relate_consts:: 777,574,924 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 731,850,776 ( 0.63%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::reuse_or_mk_predicate 721,484,776 ( 0.62%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck::<&rustc_middle::ty::TyS> 705,372,324 ( 0.61%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::_intern_substs 697,993,626 ( 0.60%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 682,409,780 ( 0.59%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs:rustc_middle::ty::relate::super_relate_tys:: 677,605,989 ( 0.58%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs:::fold_ty 663,492,387 ( 0.57%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck:: 652,775,202 ( 0.56%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fast_reject.rs:rustc_middle::ty::fast_reject::simplify_type 643,318,369 ( 0.55%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::reuse_or_mk_predicate 640,207,950 ( 0.55%) ./malloc/malloc.c:free 631,498,787 ( 0.54%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:::rollback_to 602,102,024 ( 0.52%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs: as rustc_middle::ty::context::InternIteratorElement>>::intern_with::>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>, ::mk_substs>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>>::{closure#0}> 596,270,160 ( 0.51%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::replace_bound_vars::::replace_bound_vars_with_placeholders::{closure#0}, ::replace_bound_vars_with_placeholders::{closure#1}, ::replace_bound_vars_with_placeholders::{closure#2}> 590,679,379 ( 0.51%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs:::candidate_from_obligation_no_cache 582,401,142 ( 0.50%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 573,203,786 ( 0.49%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::try_fold_with:: 548,230,234 ( 0.47%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/project.rs:::fold_ty 531,982,240 ( 0.46%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 521,955,444 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/instance.rs:::resolve_opt_const_arg 521,742,732 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/combine.rs:::super_combine_consts:: 519,703,791 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:rustc_middle::ty::util::fold_list:: as rustc_middle::ty::fold::TypeFoldable>::try_super_fold_with::{closure#0}> 507,871,593 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 507,376,018 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs:::relate:: 494,670,738 ( 0.42%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/erase_regions.rs:::fold_ty 486,661,220 ( 0.42%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 475,545,052 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs: as core::ops::drop::Drop>::drop 474,183,319 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/equate.rs:::tys 458,337,512 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs:::add_substs 451,274,940 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/queries.rs:::const_eval_resolve 451,035,332 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/higher_ranked/mod.rs:::replace_bound_vars_with_placeholders:: 450,673,696 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/at.rs:::match_impl 439,991,409 ( 0.38%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/unify/mod.rs:>, &mut rustc_infer::infer::undo_log::InferCtxtUndoLogs>>>::uninlined_get_root_key 432,365,157 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::try_fold_with:: 432,163,673 ( 0.37%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/unify/mod.rs:>, &mut rustc_infer::infer::undo_log::InferCtxtUndoLogs>>>::probe_value:: 430,232,376 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/project.rs:rustc_trait_selection::traits::project::normalize_with_depth_to:: 425,576,965 ( 0.37%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 423,326,425 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::try_fold_with:: 423,257,490 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_if_ok::, rustc_middle::ty::error::TypeError, ::eq::{closure#0}> 417,812,418 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 413,204,391 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs:rustc_middle::ty::relate::super_relate_consts:: 411,033,080 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/function.rs:<&mut rustc_middle::ty::relate::relate_substs::{closure#0} as core::ops::function::FnOnce<((usize, (rustc_middle::ty::subst::GenericArg, rustc_middle::ty::subst::GenericArg)),)>>::call_once 402,757,059 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 402,255,495 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::start_snapshot 400,078,417 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts/kind.rs:::try_eval 393,617,873 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs:::relate:: 390,481,426 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs: as rustc_middle::ty::context::InternIteratorElement>>::intern_with::>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>, ::mk_substs>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>>::{closure#0}> 385,621,481 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/combine.rs:::super_combine_tys:: 381,079,216 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/queries.rs:::const_eval_global_id 379,733,963 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::has_escaping_bound_vars 371,005,068 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::fold_const 363,223,428 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 361,024,118 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::visit_with:: 353,769,550 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:rustc_middle::ty::util::fold_list:: as rustc_middle::ty::fold::TypeFoldable>::try_super_fold_with::{closure#0}> 349,999,937 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 331,748,710 ( 0.28%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (core::result::Result, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 324,798,976 ( 0.28%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:::write 318,806,119 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::try_fold_with:: 314,734,113 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/at.rs:::commit_if_ok::, rustc_middle::ty::error::TypeError, ::eq::{closure#0}> 305,989,908 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::try_fold_binder:: 305,341,218 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 305,141,376 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::impls_are_allowed_to_overlap 303,931,281 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/combine.rs:::unify_const_variable 301,488,296 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:<&rustc_middle::ty::consts::Const as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 301,332,216 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/project.rs:::fold_const 300,858,028 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts/kind.rs:::fold_const 295,083,954 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/stacker-0.1.14/src/lib.rs:stacker::remaining_stack 291,261,944 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:<&rustc_middle::ty::consts::Const as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 286,070,040 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::impls_are_allowed_to_overlap 280,932,725 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 278,156,685 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 276,881,859 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 276,499,764 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::rollback_to 274,300,103 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::relate:: 274,280,548 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::fold_ty 272,153,449 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 262,165,932 ( 0.23%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)>, (core::result::Result, rustc_errors::ErrorReported>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::)>> 261,392,575 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts/kind.rs:::ne 260,058,100 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/into_iter.rs:> as core::ops::drop::Drop>::drop 258,664,920 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts.rs:rustc_middle::ty::relate::super_relate_consts:: 256,359,332 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/project.rs:::fold:: 256,121,267 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs:rustc_middle::ty::util::fold_list:: as rustc_middle::ty::fold::TypeFoldable>::try_super_fold_with::{closure#0}> 250,704,100 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::and::<(rustc_span::def_id::LocalDefId, rustc_span::def_id::DefId, &rustc_middle::ty::list::List)> 250,133,678 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 249,386,931 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 248,545,776 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:>::for_item::<::fresh_substs_for_item::{closure#0}> 246,924,325 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 245,198,582 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/zip.rs: as rustc_middle::ty::context::InternIteratorElement>>::intern_with::>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>, ::mk_substs>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>>::{closure#0}> 244,192,392 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:>::fill_item::<::fresh_substs_for_item::{closure#0}> 241,098,992 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:>>::intern_with::, ::anonymize_late_bound_regions::{closure#1}>, ::mk_bound_variable_kinds, ::anonymize_late_bound_regions::{closure#1}>>::{closure#0}> 240,651,936 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts.rs:::fold_const 239,265,051 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/unify/mod.rs:>, &mut rustc_infer::infer::undo_log::InferCtxtUndoLogs>>>::unify_var_value:: 237,837,079 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 236,378,536 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::mk_const 235,002,384 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:::match_impl 227,041,133 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/confirmation.rs:::confirm_candidate 224,967,874 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::start_snapshot 224,643,021 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fast_reject.rs:::match_impl 223,372,278 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/zip.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 220,809,287 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::resolve_opt_const_arg 220,619,608 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/erase_regions.rs:::erase_regions::)>> 220,241,516 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:>::from 220,002,914 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 217,662,765 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_from 217,541,774 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::match_impl 217,249,046 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:::try_fold_with:: 216,593,174 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::has_escaping_bound_vars 216,244,454 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck::<&rustc_middle::ty::TyS> 216,140,886 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::relate:: 213,392,553 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/snapshot_vec.rs:, &mut alloc::vec::Vec>, &mut rustc_infer::infer::undo_log::InferCtxtUndoLogs>>::update::<>, &mut rustc_infer::infer::undo_log::InferCtxtUndoLogs>>>::unify_var_value::{closure#0}> 210,594,972 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs:::for_unevaluated_const 207,950,592 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::fold_ty 207,672,973 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::probe::<(), ::assemble_candidates_from_impls::{closure#0}::{closure#0}> 205,516,540 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs:<&mut rustc_middle::ty::relate::relate_substs::{closure#0} as core::ops::function::FnOnce<((usize, (rustc_middle::ty::subst::GenericArg, rustc_middle::ty::subst::GenericArg)),)>>::call_once 205,466,980 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::relate_item_substs 204,624,980 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs:::_intern_substs 204,624,980 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::_intern_substs 203,993,976 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:<&rustc_middle::ty::TyS as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 200,560,920 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::ne 199,464,279 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::fold:: 195,114,105 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:>::reverse 193,918,023 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::reuse_or_mk_predicate 192,900,900 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs:::hash:: 189,758,290 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 189,147,898 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 188,687,751 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::match_impl 187,999,995 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/infer/unify_key.rs:::unify_values 187,532,067 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/combine.rs:::consts 184,478,584 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 184,366,512 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/stack.rs:rustc_data_structures::stack::ensure_sufficient_stack::, ::match_impl::{closure#0}> 180,995,647 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck:: 180,962,031 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::with_reveal_all_normalized 180,753,060 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::from_key_hashed_nocheck::<&rustc_middle::ty::TyS> 178,815,696 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::combine_fields 178,700,367 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/bit.rs:::hash:: 178,063,742 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::_intern_substs 177,152,052 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/erase_regions.rs:::try_fold_binder:: 174,123,928 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/project.rs:rustc_data_structures::stack::ensure_sufficient_stack::, ::match_impl::{closure#0}> 170,898,406 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_type_ir/src/lib.rs:::shift_out 169,467,673 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 167,716,477 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 165,006,059 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::reuse_or_mk_predicate 164,588,139 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:::_intern_substs 164,070,846 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::try_fold_with:: 163,583,780 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 163,549,146 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 163,192,208 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:<&rustc_middle::ty::TyS as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 161,758,658 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 161,047,320 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs:::try_fold_binder:: 160,962,455 ( 0.14%) ./malloc/malloc.c:realloc 160,465,720 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (core::result::Result, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 160,454,640 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::const_eval_global_id 159,066,038 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck::<(rustc_span::def_id::DefId, rustc_span::def_id::DefId)> 158,257,665 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::features 157,952,695 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:rustc_middle::ty::util::fold_list:: as rustc_middle::ty::fold::TypeFoldable>::try_super_fold_with::{closure#0}> 156,701,948 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::candidate_from_obligation_no_cache 156,483,163 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/confirmation.rs:::vtable_impl 156,300,789 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs:::fold:: 155,623,108 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::try_fold_with:: 154,094,438 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs:::probe::, ::evaluation_probe<::evaluate_candidate::{closure#0}>::{closure#0}> 153,646,590 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/at.rs:::to_trace 152,579,521 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/query.rs:::impls_are_allowed_to_overlap 151,955,783 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::has_escaping_bound_vars 150,861,555 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck:: 150,426,225 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/tagged_ptr/copy.rs:::const_eval_global_id 147,258,308 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::has_escaping_bound_vars 146,484,348 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_type_ir/src/lib.rs:::shift_in 144,543,659 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::from_key_hashed_nocheck::<&rustc_middle::ty::TyS> 143,930,468 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/enumerate.rs: as rustc_middle::ty::context::InternIteratorElement>>::intern_with::>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>, ::mk_substs>, core::iter::adapters::copied::Copied>>>, rustc_middle::ty::relate::relate_substs::{closure#0}>>::{closure#0}> 140,406,674 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/query.rs:::const_eval_global_id 139,283,064 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sharded.rs:::intern_ty 139,059,860 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:> as core::ops::drop::Drop>::drop 138,454,616 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::anonymize_late_bound_regions:: 138,149,874 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs:::intern_ty 134,129,070 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:stacker::remaining_stack 134,085,165 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::start_snapshot 133,553,537 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/equate.rs:::relate_item_substs 133,502,564 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::impls_are_allowed_to_overlap 133,499,352 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::impls_are_allowed_to_overlap::{closure#2} 131,674,792 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs:::eq 130,362,193 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:, (core::result::Result, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 130,025,312 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts.rs:rustc_middle::ty::relate::super_relate_consts:: 127,322,862 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::match_impl 127,183,139 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::match_impl 127,140,634 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_query_system/src/query/caches.rs:::impls_are_allowed_to_overlap 126,787,016 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts.rs:::eq 126,538,587 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 126,270,860 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs: as rustc_middle::ty::fold::TypeFoldable>::super_fold_with:: 125,500,213 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::tys 125,311,758 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs:::fold_const 124,288,890 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::for_item::<::fresh_substs_for_item::{closure#0}> 123,942,850 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 123,823,330 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::fill_item::<::fresh_substs_for_item::{closure#0}> 123,188,873 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_unconditionally::>, ::confirm_impl_candidate::{closure#0}> 121,776,465 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_predicate 120,785,128 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::impls_are_allowed_to_overlap::{closure#2} 120,655,089 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck:: 120,392,985 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 120,340,980 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs:::const_eval_global_id 120,337,968 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:)>, (core::result::Result, rustc_errors::ErrorReported>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::)>> 119,774,008 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/infer/unify_key.rs:::index 117,063,586 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs:::impl_or_trait_obligations 116,909,350 ( 0.10%) ./malloc/malloc.c:malloc_consolidate 116,865,553 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 116,529,741 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs:::assemble_candidates 116,490,646 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/control_flow.rs:, ::candidate_from_obligation_no_cache::{closure#1}>, core::option::Option>, , rustc_middle::traits::SelectionError>>::transpose>, rustc_middle::traits::SelectionError> as core::iter::traits::iterator::Iterator>::next -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/stacker-0.1.14/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . /// `stack_size` bytes. . /// . /// The closure `f` is guaranteed to run on a stack with at least `red_zone` bytes, and it will be . /// run on the current stack if there's space available. . #[inline(always)] . pub fn maybe_grow R>(red_zone: usize, stack_size: usize, callback: F) -> R { . // if we can't guess the remaining stack (unsupported on some platforms) we immediately grow . // the stack and then cache the new stack size (which we do know now because we allocated it. 54,022,390 ( 0.05%) let enough_space = match remaining_stack() { . Some(remaining) => remaining >= red_zone, . None => false, . }; 80,477,442 ( 0.07%) if enough_space { 10,255,670 ( 0.01%) callback() . } else { . grow(stack_size, callback) . } . } . . /// Always creates a new stack for the passed closure to run on. . /// The closure will still be on the same thread as the caller of `grow`. . /// This will allocate a new stack with at least `stack_size` bytes. -- line 63 ---------------------------------------- -- line 82 ---------------------------------------- . _grow(stack_size, dyn_callback); . ret.unwrap() . } . . /// Queries the amount of remaining stack as interpreted by this library. . /// . /// This function will return the amount of stack space left which will be used . /// to determine whether a stack switch should be made or not. 53,651,628 ( 0.05%) pub fn remaining_stack() -> Option { . let current_ptr = current_stack_ptr(); 53,651,628 ( 0.05%) get_stack_limit().map(|limit| current_ptr - limit) 107,303,256 ( 0.09%) } . . psm_stack_information! ( . yes { . fn current_stack_ptr() -> usize { 53,651,628 ( 0.05%) psm::stack_pointer() as usize . } . } . no { . #[inline(always)] . fn current_stack_ptr() -> usize { . unsafe { . let mut x = std::mem::MaybeUninit::::uninit(); . // Unlikely to be ever exercised. As a fallback we execute a volatile read to a -- line 106 ---------------------------------------- -- line 111 ---------------------------------------- . x.as_ptr() as usize . } . } . } . ); . . thread_local! { . static STACK_LIMIT: Cell> = Cell::new(unsafe { 1 ( 0.00%) guess_os_stack_limit() . }) . } . . #[inline(always)] . fn get_stack_limit() -> Option { . STACK_LIMIT.with(|s| s.get()) . } . -- line 127 ---------------------------------------- -- line 403 ---------------------------------------- . VirtualQuery( . psm::stack_pointer() as *const _, . mi.as_mut_ptr(), . std::mem::size_of::() as SIZE_T, . ); . Some(mi.assume_init().AllocationBase as usize + get_thread_stack_guarantee() + 0x1000) . } . } else if #[cfg(any(target_os = "linux", target_os="solaris", target_os = "netbsd"))] { 2 ( 0.00%) unsafe fn guess_os_stack_limit() -> Option { . let mut attr = std::mem::MaybeUninit::::uninit(); 4 ( 0.00%) assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); 7 ( 0.00%) assert_eq!(libc::pthread_getattr_np(libc::pthread_self(), . attr.as_mut_ptr()), 0); 1 ( 0.00%) let mut stackaddr = std::ptr::null_mut(); 4 ( 0.00%) let mut stacksize = 0; 4 ( 0.00%) assert_eq!(libc::pthread_attr_getstack( . attr.as_ptr(), &mut stackaddr, &mut stacksize . ), 0); 4 ( 0.00%) assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); 1 ( 0.00%) Some(stackaddr as usize) 3 ( 0.00%) } . } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { . unsafe fn guess_os_stack_limit() -> Option { . let mut attr = std::mem::MaybeUninit::::uninit(); . assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); . assert_eq!(libc::pthread_attr_get_np(libc::pthread_self(), attr.as_mut_ptr()), 0); . let mut stackaddr = std::ptr::null_mut(); . let mut stacksize = 0; . assert_eq!(libc::pthread_attr_getstack( -- line 431 ---------------------------------------- 38,443,657 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/into_iter.rs -------------------------------------------------------------------------------- Ir -- line 51 ---------------------------------------- . /// let vec = vec!['a', 'b', 'c']; . /// let mut into_iter = vec.into_iter(); . /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); . /// let _ = into_iter.next().unwrap(); . /// assert_eq!(into_iter.as_slice(), &['b', 'c']); . /// ``` . #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] . pub fn as_slice(&self) -> &[T] { 280,032 ( 0.00%) unsafe { slice::from_raw_parts(self.ptr, self.len()) } . } . . /// Returns the remaining items of this iterator as a mutable slice. . /// . /// # Examples . /// . /// ``` . /// let vec = vec!['a', 'b', 'c']; -- line 67 ---------------------------------------- -- line 80 ---------------------------------------- . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn allocator(&self) -> &A { . &self.alloc . } . . fn as_raw_mut_slice(&mut self) -> *mut [T] { 35,805,087 ( 0.03%) ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len()) . } . . /// Drops remaining elements and relinquishes the backing allocation. . /// . /// This is roughly equivalent to the following, but more efficient . /// . /// ``` . /// # let mut into_iter = Vec::::with_capacity(10).into_iter(); -- line 96 ---------------------------------------- -- line 99 ---------------------------------------- . /// ``` . #[cfg(not(no_global_oom_handling))] . pub(super) fn forget_allocation_drop_remaining(&mut self) { . let remaining = self.as_raw_mut_slice(); . . // overwrite the individual fields instead of creating a new . // struct and then overwriting &mut self. . // this creates less assembly 14,722 ( 0.00%) self.cap = 0; 29,444 ( 0.00%) self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) }; 19,291 ( 0.00%) self.ptr = self.buf.as_ptr(); 23,923 ( 0.00%) self.end = self.buf.as_ptr(); . . unsafe { . ptr::drop_in_place(remaining); . } . } . } . . #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] -- line 118 ---------------------------------------- -- line 128 ---------------------------------------- . unsafe impl Sync for IntoIter {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = T; . . #[inline] . fn next(&mut self) -> Option { 95,336,044 ( 0.08%) if self.ptr as *const _ == self.end { 1,351,142 ( 0.00%) None 150 ( 0.00%) } else if mem::size_of::() == 0 { . // purposefully don't use 'ptr.offset' because for . // vectors with 0-size elements this would return the . // same pointer. . self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T }; . . // Make up a value of this ZST. . Some(unsafe { mem::zeroed() }) . } else { . let old = self.ptr; 17,039,483 ( 0.01%) self.ptr = unsafe { self.ptr.offset(1) }; . 1,157,732 ( 0.00%) Some(unsafe { ptr::read(old) }) . } 94 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . let exact = if mem::size_of::() == 0 { . (self.end as usize).wrapping_sub(self.ptr as usize) . } else { . unsafe { self.end.offset_from(self.ptr) as usize } . }; 3 ( 0.00%) (exact, Some(exact)) . } . . #[inline] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . let step_size = self.len().min(n); . let to_drop = ptr::slice_from_raw_parts_mut(self.ptr as *mut T, step_size); . if mem::size_of::() == 0 { . // SAFETY: due to unchecked casts of unsigned amounts to signed offsets the wraparound -- line 169 ---------------------------------------- -- line 181 ---------------------------------------- . if step_size < n { . return Err(step_size); . } . Ok(()) . } . . #[inline] . fn count(self) -> usize { 2 ( 0.00%) self.len() . } . . #[doc(hidden)] . unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item . where . Self: TrustedRandomAccessNoCoerce, . { . // SAFETY: the caller must guarantee that `i` is in bounds of the -- line 197 ---------------------------------------- -- line 207 ---------------------------------------- . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { 1,779,970 ( 0.00%) if self.end == self.ptr { . None . } else if mem::size_of::() == 0 { . // See above for why 'ptr.offset' isn't used . self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T }; . . // Make up a value of this ZST. . Some(unsafe { mem::zeroed() }) . } else { 523,604 ( 0.00%) self.end = unsafe { self.end.offset(-1) }; . 7,154 ( 0.00%) Some(unsafe { ptr::read(self.end) }) . } . } . . #[inline] . fn advance_back_by(&mut self, n: usize) -> Result<(), usize> { . let step_size = self.len().min(n); . if mem::size_of::() == 0 { . // SAFETY: same as for advance_by() -- line 234 ---------------------------------------- -- line 295 ---------------------------------------- . #[cfg(test)] . fn clone(&self) -> Self { . crate::slice::to_vec(self.as_slice(), self.alloc.clone()).into_iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { 121,457,916 ( 0.10%) fn drop(&mut self) { . struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); . . impl Drop for DropGuard<'_, T, A> { . fn drop(&mut self) { . unsafe { . // `IntoIter::alloc` is not used anymore after this . let alloc = ptr::read(&self.0.alloc); . // RawVec handles deallocation 19,545,456 ( 0.02%) let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc); . } . } . } . . let guard = DropGuard(self); . // destroy the remaining elements . unsafe { 1,458 ( 0.00%) ptr::drop_in_place(guard.0.as_raw_mut_slice()); . } . // now `guard` will be dropped and do the rest 117,442,827 ( 0.10%) } . } . . #[unstable(issue = "none", feature = "inplace_iteration")] . #[doc(hidden)] . unsafe impl InPlaceIterable for IntoIter {} . . #[unstable(issue = "none", feature = "inplace_iteration")] . #[doc(hidden)] -- line 331 ---------------------------------------- 62,300,667 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . . impl<'a, T> $name<'a, T> { . // Helper function for creating a slice from the iterator. . #[inline(always)] . fn make_slice(&self) -> &'a [T] { . // SAFETY: the iterator was created from a slice with pointer . // `self.ptr` and length `len!(self)`. This guarantees that all . // the prerequisites for `from_raw_parts` are fulfilled. 604,283 ( 0.00%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 16,372,149 ( 0.01%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 1,671 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; . self.end . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 1,018,475 ( 0.00%) len!(self) . } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . -- line 128 ---------------------------------------- -- line 134 ---------------------------------------- . fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 6,827,357 ( 0.01%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 544,295 ( 0.00%) assume(!self.end.is_null()); . } 2,349,727,037 ( 2.02%) if is_empty!(self) { . None . } else { 5,063 ( 0.00%) Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 83,372,407 ( 0.07%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 486,228 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 58,473 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 84,316 ( 0.00%) while let Some(x) = self.next() { 121,138 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] 8 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 4,790,023 ( 0.00%) while let Some(x) = self.next() { 4,767,491 ( 0.00%) if f(x) { . return true; . } . } . false 8 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 176,322 ( 0.00%) while let Some(x) = self.next() { 594,646 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 4,720 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 18,011,178 ( 0.02%) while let Some(x) = self.next() { 10,288,040 ( 0.01%) if let Some(y) = f(x) { 585,868 ( 0.00%) return Some(y); . } . } . None 61,251 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . #[rustc_inherit_overflow_checks] . fn position

(&mut self, mut predicate: P) -> Option where . Self: Sized, . P: FnMut(Self::Item) -> bool, . { . let n = len!(self); . let mut i = 0; . while let Some(x) = self.next() { 4,962,762 ( 0.00%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 589,581 ( 0.00%) while let Some(x) = self.next_back() { 7,600,102 ( 0.01%) i -= 1; 6,216,047 ( 0.01%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 34,566,295 ( 0.03%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } . } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] -- line 348 ---------------------------------------- -- line 349 ---------------------------------------- . fn next_back(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { 68 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 100 ( 0.00%) assume(!self.end.is_null()); . } 13,461,077 ( 0.01%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 234,465,627 ( 0.20%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 3,512 ( 0.00%) fn clone(&self) -> Self { 19,548 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 3,923 ( 0.00%) table: self.table.clone(), . } 3,951 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } -- line 207 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 1,081,774 ( 0.00%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 4,891,327 ( 0.00%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 47,988,996 ( 0.04%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { . hash_builder.hash_one(val) 12 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 3,341,585 ( 0.00%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 88 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 527 ---------------------------------------- . /// map.insert("c", 3); . /// . /// for key in map.keys() { . /// println!("{}", key); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn keys(&self) -> Keys<'_, K, V> { 6 ( 0.00%) Keys { inner: self.iter() } . } . . /// An iterator visiting all values in arbitrary order. . /// The iterator element type is `&'a V`. . /// . /// # Examples . /// . /// ``` -- line 543 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 322,306 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 901,406 ( 0.00%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 2,428 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 2,090 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 945 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 3,035 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 9,051,271 ( 0.01%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 11,428,382 ( 0.01%) if self.table.is_empty() { . None . } else { 3 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 8,965,480 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 10,946,890 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,798 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 11,436 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 7,596 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 3,812 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); 28 ( 0.00%) self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. . /// . /// Returns an array of length `N` with the results of each query. For soundness, at most one . /// mutable reference will be returned to any value. `None` will be returned if any of the . /// keys are duplicates or missing. -- line 1223 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 55,487,342 ( 0.05%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 4,250 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { 294 ( 0.00%) Some(mem::replace(item, v)) . } else { 19,531,429 ( 0.02%) self.table 21,054,404 ( 0.02%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 1,803,844 ( 0.00%) None . } 50,334,006 ( 0.04%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 811,242 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 7,154,487 ( 0.01%) match self.remove_entry(k) { 424,701 ( 0.00%) Some((_, v)) => Some(v), 592,179 ( 0.00%) None => None, . } 1,593,406 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 3,253,116 ( 0.00%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 246,544,550 ( 0.21%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 540,100,718 ( 0.46%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 611,210,621 ( 0.52%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 84,917,532 ( 0.07%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 408,898,027 ( 0.35%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 2,098,294 ( 0.00%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 266,653,278 ( 0.23%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 168,062,996 ( 0.14%) self.from_hash(hash, equivalent(k)) 416,537,244 ( 0.36%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 248,272,342 ( 0.21%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 3,526,333 ( 0.00%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 18,878 ( 0.00%) fn into_iter(self) -> IntoIter { 477,181 ( 0.00%) IntoIter { 244,702 ( 0.00%) inner: self.table.into_iter(), . } 56,634 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 1,836,648 ( 0.00%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 12,545 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 5 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 22,082 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 868 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 1,736 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 8 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 657,317 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 537,132 ( 0.00%) let iter = iter.into_iter(); 240,311 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 41,255 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 2,304,987 ( 0.00%) self.insert(k, v); . }); 476,636 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 171,185,633 ( 0.15%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/enumerate.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . /// debug assertions are enabled, a panic is guaranteed. . /// . /// # Panics . /// . /// Might panic if the index of the element overflows a `usize`. . #[inline] . #[rustc_inherit_overflow_checks] . fn next(&mut self) -> Option<(usize, ::Item)> { 1,792,667 ( 0.00%) let a = self.iter.next()?; 22,245,253 ( 0.02%) let i = self.count; 100,658,365 ( 0.09%) self.count += 1; 3,427,311 ( 0.00%) Some((i, a)) . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 43,401,469 ( 0.04%) self.iter.size_hint() . } . . #[inline] . #[rustc_inherit_overflow_checks] . fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> { . let a = self.iter.nth(n)?; 15,844 ( 0.00%) let i = self.count + n; 16,775 ( 0.00%) self.count = i + 1; . Some((i, a)) . } . . #[inline] . fn count(self) -> usize { . self.iter.count() . } . -- line 70 ---------------------------------------- -- line 76 ---------------------------------------- . R: Try, . { . #[inline] . fn enumerate<'a, T, Acc, R>( . count: &'a mut usize, . mut fold: impl FnMut(Acc, (usize, T)) -> R + 'a, . ) -> impl FnMut(Acc, T) -> R + 'a { . #[rustc_inherit_overflow_checks] 20,444 ( 0.00%) move |acc, item| { 1,271,453 ( 0.00%) let acc = fold(acc, (*count, item)); 50,563,268 ( 0.04%) *count += 1; . acc . } . } . 4,434 ( 0.00%) self.iter.try_fold(init, enumerate(&mut self.count, fold)) . } . . #[inline] . fn fold(self, init: Acc, fold: Fold) -> Acc . where . Fold: FnMut(Acc, Self::Item) -> Acc, . { . #[inline] . fn enumerate( . mut count: usize, . mut fold: impl FnMut(Acc, (usize, T)) -> Acc, . ) -> impl FnMut(Acc, T) -> Acc { . #[rustc_inherit_overflow_checks] 593,694 ( 0.00%) move |acc, item| { 142 ( 0.00%) let acc = fold(acc, (count, item)); 658,705 ( 0.00%) count += 1; . acc . } . } . 2,672,593 ( 0.00%) self.iter.fold(init, enumerate(self.count, fold)) . } . . #[inline] . #[rustc_inherit_overflow_checks] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . match self.iter.advance_by(n) { . ret @ Ok(_) => { . self.count += n; -- line 120 ---------------------------------------- -- line 131 ---------------------------------------- . #[doc(hidden)] . unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> ::Item . where . Self: TrustedRandomAccessNoCoerce, . { . // SAFETY: the caller must uphold the contract for . // `Iterator::__iterator_get_unchecked`. . let value = unsafe { try_get_unchecked(&mut self.iter, idx) }; 72 ( 0.00%) (self.count + idx, value) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for Enumerate . where . I: ExactSizeIterator + DoubleEndedIterator, . { -- line 147 ---------------------------------------- -- line 172 ---------------------------------------- . { . // Can safely add and subtract the count, as `ExactSizeIterator` promises . // that the number of elements fits into a `usize`. . fn enumerate( . mut count: usize, . mut fold: impl FnMut(Acc, (usize, T)) -> R, . ) -> impl FnMut(Acc, T) -> R { . move |acc, item| { 267,852 ( 0.00%) count -= 1; . fold(acc, (count, item)) . } . } . 70,966 ( 0.00%) let count = self.count + self.iter.len(); . self.iter.try_rfold(init, enumerate(count, fold)) . } . . #[inline] . fn rfold(self, init: Acc, fold: Fold) -> Acc . where . Fold: FnMut(Acc, Self::Item) -> Acc, . { -- line 193 ---------------------------------------- 5,668,464 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/infer/unify_key.rs -------------------------------------------------------------------------------- Ir -- line 16 ---------------------------------------- . } . . #[derive(PartialEq, Copy, Clone, Debug)] . pub struct UnifiedRegion<'tcx>(pub Option>); . . #[derive(PartialEq, Copy, Clone, Debug)] . pub struct RegionVidKey<'tcx> { . pub vid: ty::RegionVid, 1,764,817 ( 0.00%) pub phantom: PhantomData>, . } . . impl<'tcx> From for RegionVidKey<'tcx> { 523,595 ( 0.00%) fn from(vid: ty::RegionVid) -> Self { . RegionVidKey { vid, phantom: PhantomData } 523,595 ( 0.00%) } . } . . impl<'tcx> UnifyKey for RegionVidKey<'tcx> { . type Value = UnifiedRegion<'tcx>; . fn index(&self) -> u32 { 1,607,600 ( 0.00%) self.vid.as_u32() 1,607,600 ( 0.00%) } . fn from_index(i: u32) -> Self { . RegionVidKey::from(ty::RegionVid::from_u32(i)) 1,240,890 ( 0.00%) } . fn tag() -> &'static str { . "RegionVidKey" . } . } . . impl<'tcx> UnifyValue for UnifiedRegion<'tcx> { . type Error = NoError; . . fn unify_values(value1: &Self, value2: &Self) -> Result { 571,695 ( 0.00%) Ok(match (value1.0, value2.0) { . // Here we can just pick one value, because the full constraints graph . // will be handled later. Ideally, we might want a `MultipleValues` . // variant or something. For now though, this is fine. . (Some(_), Some(_)) => *value1, . . (Some(_), _) => *value1, . (_, Some(_)) => *value2, . . (None, None) => *value1, . }) 381,130 ( 0.00%) } . } . . impl ToType for ty::IntVarValue { . fn to_type<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 17,793 ( 0.00%) match *self { . ty::IntType(i) => tcx.mk_mach_int(i), . ty::UintType(i) => tcx.mk_mach_uint(i), . } 17,793 ( 0.00%) } . } . . impl ToType for ty::FloatVarValue { . fn to_type<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 732 ( 0.00%) tcx.mk_mach_float(self.0) 732 ( 0.00%) } . } . . // Generic consts. . . #[derive(Copy, Clone, Debug)] . pub struct ConstVariableOrigin { . pub kind: ConstVariableOriginKind, . pub span: Span, -- line 84 ---------------------------------------- -- line 98 ---------------------------------------- . Known { value: &'tcx ty::Const<'tcx> }, . Unknown { universe: ty::UniverseIndex }, . } . . impl<'tcx> ConstVariableValue<'tcx> { . /// If this value is known, returns the const it is known to be. . /// Otherwise, `None`. . pub fn known(&self) -> Option<&'tcx ty::Const<'tcx>> { 14,118,378 ( 0.01%) match *self { . ConstVariableValue::Unknown { .. } => None, . ConstVariableValue::Known { value } => Some(value), . } 7,059,189 ( 0.01%) } . } . 81,245,589 ( 0.07%) #[derive(Copy, Clone, Debug)] . pub struct ConstVarValue<'tcx> { . pub origin: ConstVariableOrigin, . pub val: ConstVariableValue<'tcx>, . } . . impl<'tcx> UnifyKey for ty::ConstVid<'tcx> { . type Value = ConstVarValue<'tcx>; . fn index(&self) -> u32 { 59,887,004 ( 0.05%) self.index 59,887,004 ( 0.05%) } 153,315 ( 0.00%) fn from_index(i: u32) -> Self { . ty::ConstVid { index: i, phantom: PhantomData } 153,315 ( 0.00%) } . fn tag() -> &'static str { . "ConstVid" . } . } . . impl<'tcx> UnifyValue for ConstVarValue<'tcx> { . type Error = (&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>); . 19,458,360 ( 0.02%) fn unify_values(&value1: &Self, &value2: &Self) -> Result { 84,319,560 ( 0.07%) Ok(match (value1.val, value2.val) { . (ConstVariableValue::Known { .. }, ConstVariableValue::Known { .. }) => { . bug!("equating two const variables, both of which have known values") . } . . // If one side is known, prefer that one. . (ConstVariableValue::Known { .. }, ConstVariableValue::Unknown { .. }) => value1, . (ConstVariableValue::Unknown { .. }, ConstVariableValue::Known { .. }) => value2, . -- line 144 ---------------------------------------- -- line 154 ---------------------------------------- . // the one which contains the fewest names in scope. . let universe = cmp::min(universe1, universe2); . ConstVarValue { . val: ConstVariableValue::Unknown { universe }, . origin: value1.origin, . } . } . }) 19,458,360 ( 0.02%) } . } . . impl<'tcx> EqUnifyValue for &'tcx ty::Const<'tcx> {} . . pub fn replace_if_possible<'tcx, V, L>( . table: &mut UnificationTable, V, L>>, . c: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> . where . V: snapshot_vec::VecLike>>, . L: UndoLogs>>>, . { 52,671,826 ( 0.05%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = c { 45,641,239 ( 0.04%) match table.probe_value(*vid).val.known() { . Some(c) => c, . None => c, . } . } else { . c . } . } 85,483,688 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fold.rs -------------------------------------------------------------------------------- Ir -- line 46 ---------------------------------------- . /// . /// To implement this conveniently, use the derive macro located in `rustc_macros`. . pub trait TypeFoldable<'tcx>: fmt::Debug + Clone { . /// Consumers may find this more convenient to use with infallible folders than . /// [`try_super_fold_with`][`TypeFoldable::try_super_fold_with`], to which the . /// provided default definition delegates. Implementors **should not** override . /// this provided default definition, to ensure that the two methods are coherent . /// (provide a definition of `try_super_fold_with` instead). 344,835,600 ( 0.30%) fn super_fold_with>(self, folder: &mut F) -> Self { 22,982,459 ( 0.02%) self.try_super_fold_with(folder).into_ok() 367,610,273 ( 0.32%) } . /// Consumers may find this more convenient to use with infallible folders than . /// [`try_fold_with`][`TypeFoldable::try_fold_with`], to which the provided . /// default definition delegates. Implementors **should not** override this . /// provided default definition, to ensure that the two methods are coherent . /// (provide a definition of `try_fold_with` instead). 4,761,773 ( 0.00%) fn fold_with>(self, folder: &mut F) -> Self { 11,666,453 ( 0.01%) self.try_fold_with(folder).into_ok() 4,368,656 ( 0.00%) } . . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result; . 942,512,569 ( 0.81%) fn try_fold_with>(self, folder: &mut F) -> Result { 505,204,647 ( 0.43%) self.try_super_fold_with(folder) 999,619,970 ( 0.86%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow; 175,968,946 ( 0.15%) fn visit_with>(&self, visitor: &mut V) -> ControlFlow { 72,895,328 ( 0.06%) self.super_visit_with(visitor) 172,468,402 ( 0.15%) } . . /// Returns `true` if `self` has any late-bound regions that are either . /// bound by `binder` or bound by some binder outside of `binder`. . /// If `binder` is `ty::INNERMOST`, this indicates whether . /// there are any late-bound regions that appear free. . fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool { 45,920,947 ( 0.04%) self.visit_with(&mut HasEscapingVarsVisitor { outer_index: binder }).is_break() . } . . /// Returns `true` if this `self` has any regions that escape `binder` (and . /// hence are not bound by it). . fn has_vars_bound_above(&self, binder: ty::DebruijnIndex) -> bool { 564 ( 0.00%) self.has_vars_bound_at_or_above(binder.shifted_in(1)) . } . 169,409,075 ( 0.15%) fn has_escaping_bound_vars(&self) -> bool { 3,356,166 ( 0.00%) self.has_vars_bound_at_or_above(ty::INNERMOST) 169,474,490 ( 0.15%) } . 1,162,831 ( 0.00%) #[instrument(level = "trace")] . fn has_type_flags(&self, flags: TypeFlags) -> bool { 34,911,947 ( 0.03%) self.visit_with(&mut HasTypeFlagsVisitor { flags }).break_value() == Some(FoundFlags) . } . fn has_projections(&self) -> bool { 123,670 ( 0.00%) self.has_type_flags(TypeFlags::HAS_PROJECTION) . } . fn has_opaque_types(&self) -> bool { . self.has_type_flags(TypeFlags::HAS_TY_OPAQUE) . } 224,056 ( 0.00%) fn references_error(&self) -> bool { . self.has_type_flags(TypeFlags::HAS_ERROR) 224,056 ( 0.00%) } . fn has_param_types_or_consts(&self) -> bool { 47,925 ( 0.00%) self.has_type_flags(TypeFlags::HAS_TY_PARAM | TypeFlags::HAS_CT_PARAM) . } . fn has_infer_regions(&self) -> bool { . self.has_type_flags(TypeFlags::HAS_RE_INFER) . } . fn has_infer_types(&self) -> bool { . self.has_type_flags(TypeFlags::HAS_TY_INFER) . } . fn has_infer_types_or_consts(&self) -> bool { 2,754,259 ( 0.00%) self.has_type_flags(TypeFlags::HAS_TY_INFER | TypeFlags::HAS_CT_INFER) . } 920,150 ( 0.00%) fn needs_infer(&self) -> bool { 2,543,550 ( 0.00%) self.has_type_flags(TypeFlags::NEEDS_INFER) 925,804 ( 0.00%) } . fn has_placeholders(&self) -> bool { . self.has_type_flags( . TypeFlags::HAS_RE_PLACEHOLDER . | TypeFlags::HAS_TY_PLACEHOLDER . | TypeFlags::HAS_CT_PLACEHOLDER, . ) . } . fn needs_subst(&self) -> bool { 96 ( 0.00%) self.has_type_flags(TypeFlags::NEEDS_SUBST) . } . /// "Free" regions in this context means that it has any region . /// that is not (a) erased or (b) late-bound. . fn has_free_regions(&self) -> bool { . self.has_type_flags(TypeFlags::HAS_FREE_REGIONS) . } . . fn has_erased_regions(&self) -> bool { -- line 142 ---------------------------------------- -- line 146 ---------------------------------------- . /// True if there are any un-erased free regions. . fn has_erasable_regions(&self) -> bool { . self.has_type_flags(TypeFlags::HAS_FREE_REGIONS) . } . . /// Indicates whether this value references only 'global' . /// generic parameters that are the same regardless of what fn we are . /// in. This is used for caching. 855 ( 0.00%) fn is_global(&self) -> bool { 1,247,614 ( 0.00%) !self.has_type_flags(TypeFlags::HAS_FREE_LOCAL_NAMES) 1,026 ( 0.00%) } . . /// True if there are any late-bound regions 2,590 ( 0.00%) fn has_late_bound_regions(&self) -> bool { 5,709 ( 0.00%) self.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND) 3,108 ( 0.00%) } . . /// Indicates whether this value still has parameters/placeholders/inference variables . /// which could be replaced later, in a way that would change the results of `impl` . /// specialization. . fn still_further_specializable(&self) -> bool { . self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE) . } . } -- line 169 ---------------------------------------- -- line 194 ---------------------------------------- . . fn tcx<'a>(&'a self) -> TyCtxt<'tcx>; . . fn fold_binder(&mut self, t: Binder<'tcx, T>) -> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . Self: TypeFolder<'tcx, Error = !>, . { 83,896,833 ( 0.07%) t.super_fold_with(self) . } . . fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> . where . Self: TypeFolder<'tcx, Error = !>, . { 1,908,032 ( 0.00%) t.super_fold_with(self) . } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> . where . Self: TypeFolder<'tcx, Error = !>, . { . r.super_fold_with(self) . } . . fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> . where . Self: TypeFolder<'tcx, Error = !>, . { 195,289 ( 0.00%) c.super_fold_with(self) . } . . fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> . where . Self: TypeFolder<'tcx, Error = !>, . { 547,855 ( 0.00%) p.super_fold_with(self) . } . . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> . where . Self: TypeFolder<'tcx, Error = !>, . { . bug!("most type folders should not be folding MIR datastructures: {:?}", c) . } -- line 238 ---------------------------------------- -- line 247 ---------------------------------------- . /// A blanket implementation of this trait (that defers to the relevant . /// method of [`TypeFolder`]) is provided for all infallible folders in . /// order to ensure the two APIs are coherent. . pub trait FallibleTypeFolder<'tcx>: TypeFolder<'tcx> { . fn try_fold_binder(&mut self, t: Binder<'tcx, T>) -> Result, Self::Error> . where . T: TypeFoldable<'tcx>, . { 4,275,116 ( 0.00%) t.try_super_fold_with(self) . } . . fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result, Self::Error> { . t.try_super_fold_with(self) . } . . fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result, Self::Error> { . r.try_super_fold_with(self) -- line 263 ---------------------------------------- -- line 269 ---------------------------------------- . ) -> Result<&'tcx ty::Const<'tcx>, Self::Error> { . c.try_super_fold_with(self) . } . . fn try_fold_predicate( . &mut self, . p: ty::Predicate<'tcx>, . ) -> Result, Self::Error> { 949,127 ( 0.00%) p.try_super_fold_with(self) . } . . fn try_fold_mir_const( . &mut self, . c: mir::ConstantKind<'tcx>, . ) -> Result, Self::Error> { . bug!("most type folders should not be folding MIR datastructures: {:?}", c) . } -- line 285 ---------------------------------------- -- line 286 ---------------------------------------- . } . . // Blanket implementation of fallible trait for infallible folders . // delegates to infallible methods to prevent incoherence . impl<'tcx, F> FallibleTypeFolder<'tcx> for F . where . F: TypeFolder<'tcx, Error = !>, . { 106,335,116 ( 0.09%) fn try_fold_binder(&mut self, t: Binder<'tcx, T>) -> Result, Self::Error> . where . T: TypeFoldable<'tcx>, . { 127,747,060 ( 0.11%) Ok(self.fold_binder(t)) 108,980,708 ( 0.09%) } . 2,523,699 ( 0.00%) fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result, Self::Error> { 287,754,829 ( 0.25%) Ok(self.fold_ty(t)) 2,752,165 ( 0.00%) } . 153,176 ( 0.00%) fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result, Self::Error> { 19,369,093 ( 0.02%) Ok(self.fold_region(r)) 153,256 ( 0.00%) } . 917,564 ( 0.00%) fn try_fold_const( . &mut self, . c: &'tcx ty::Const<'tcx>, . ) -> Result<&'tcx ty::Const<'tcx>, Self::Error> { 25,586,247 ( 0.02%) Ok(self.fold_const(c)) 516,984 ( 0.00%) } . . fn try_fold_predicate( . &mut self, . p: ty::Predicate<'tcx>, . ) -> Result, Self::Error> { . Ok(self.fold_predicate(p)) . } . -- line 322 ---------------------------------------- -- line 330 ---------------------------------------- . . pub trait TypeVisitor<'tcx>: Sized { . type BreakTy = !; . . fn visit_binder>( . &mut self, . t: &Binder<'tcx, T>, . ) -> ControlFlow { 2,988 ( 0.00%) t.super_visit_with(self) . } . . fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { 5,040 ( 0.00%) t.super_visit_with(self) . } . . fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { . r.super_visit_with(self) . } . 592 ( 0.00%) fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow { 3 ( 0.00%) c.super_visit_with(self) 518 ( 0.00%) } . . fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow { 304 ( 0.00%) uv.super_visit_with(self) . } . . fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow { . p.super_visit_with(self) . } . } . . /////////////////////////////////////////////////////////////////////////// -- line 362 ---------------------------------------- -- line 380 ---------------------------------------- . G: FnMut(ty::Region<'tcx>) -> ty::Region<'tcx>, . H: FnMut(&'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>, . { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 55,486 ( 0.00%) let t = ty.super_fold_with(self); . (self.ty_op)(t) . } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . let r = r.super_fold_with(self); . (self.lt_op)(r) . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 6,567 ( 0.00%) let ct = ct.super_fold_with(self); . (self.ct_op)(ct) . } . } . . /////////////////////////////////////////////////////////////////////////// . // Region folder . . impl<'tcx> TyCtxt<'tcx> { -- line 406 ---------------------------------------- -- line 415 ---------------------------------------- . ) -> T . where . T: TypeFoldable<'tcx>, . { . value.fold_with(&mut RegionFolder::new(self, skipped_regions, &mut f)) . } . . /// Invoke `callback` on every region appearing free in `value`. 11,506 ( 0.00%) pub fn for_each_free_region( . self, . value: &impl TypeFoldable<'tcx>, . mut callback: impl FnMut(ty::Region<'tcx>), . ) { . self.any_free_region_meets(value, |r| { 167,780 ( 0.00%) callback(r); . false . }); 9,874 ( 0.00%) } . . /// Returns `true` if `callback` returns true for every region appearing free in `value`. . pub fn all_free_regions_meet( . self, . value: &impl TypeFoldable<'tcx>, . mut callback: impl FnMut(ty::Region<'tcx>) -> bool, . ) -> bool { 36,542 ( 0.00%) !self.any_free_region_meets(value, |r| !callback(r)) . } . . /// Returns `true` if `callback` returns true for some region appearing free in `value`. . pub fn any_free_region_meets( . self, . value: &impl TypeFoldable<'tcx>, . callback: impl FnMut(ty::Region<'tcx>) -> bool, . ) -> bool { -- line 448 ---------------------------------------- -- line 473 ---------------------------------------- . F: FnMut(ty::Region<'tcx>) -> bool, . { . type BreakTy = (); . . fn visit_binder>( . &mut self, . t: &Binder<'tcx, T>, . ) -> ControlFlow { 4,408 ( 0.00%) self.outer_index.shift_in(1); 3,984 ( 0.00%) let result = t.as_ref().skip_binder().visit_with(self); 2,988 ( 0.00%) self.outer_index.shift_out(1); . result . } . 173,245 ( 0.00%) fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { 289,631 ( 0.00%) match *r { 339 ( 0.00%) ty::ReLateBound(debruijn, _) if debruijn < self.outer_index => { . ControlFlow::CONTINUE . } . _ => { . if (self.callback)(r) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } . } . } 242,543 ( 0.00%) } . . fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow { . // We're only interested in types involving regions 235,122 ( 0.00%) if ty.flags().intersects(TypeFlags::HAS_FREE_REGIONS) { 225,960 ( 0.00%) ty.super_visit_with(self) . } else { . ControlFlow::CONTINUE . } . } . } . 526,019 ( 0.00%) value.visit_with(&mut RegionVisitor { outer_index: ty::INNERMOST, callback }).is_break() . } . } . . /// Folds over the substructure of a type, visiting its component . /// types and all regions that occur *free* within it. . /// . /// That is, `Ty` can contain function or method types that bind . /// regions at the call site (`ReLateBound`), and occurrences of -- line 520 ---------------------------------------- -- line 540 ---------------------------------------- . . impl<'a, 'tcx> RegionFolder<'a, 'tcx> { . #[inline] . pub fn new( . tcx: TyCtxt<'tcx>, . skipped_regions: &'a mut bool, . fold_region_fn: &'a mut dyn FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>, . ) -> RegionFolder<'a, 'tcx> { 3,203,637 ( 0.00%) RegionFolder { tcx, skipped_regions, current_index: ty::INNERMOST, fold_region_fn } . } . } . . impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 1,703,148 ( 0.00%) self.tcx 1,703,148 ( 0.00%) } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 18,765 ( 0.00%) self.current_index.shift_in(1); 12,948 ( 0.00%) let t = t.super_fold_with(self); 17,577 ( 0.00%) self.current_index.shift_out(1); . t . } . 9,320 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 457,856 ( 0.00%) match *r { 9,320 ( 0.00%) ty::ReLateBound(debruijn, _) if debruijn < self.current_index => { . debug!(?self.current_index, "skipped bound region"); 9,320 ( 0.00%) *self.skipped_regions = true; . r . } . _ => { . debug!(?self.current_index, "folding free region"); 1,345,608 ( 0.00%) (self.fold_region_fn)(r, self.current_index) . } . } . } . } . . /////////////////////////////////////////////////////////////////////////// . // Bound vars replacer . -- line 585 ---------------------------------------- -- line 592 ---------------------------------------- . current_index: ty::DebruijnIndex, . . fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>, . fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>, . fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a)>, . } . . impl<'a, 'tcx> BoundVarReplacer<'a, 'tcx> { 790,936 ( 0.00%) fn new( . tcx: TyCtxt<'tcx>, . fld_r: Option<&'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a)>, . fld_t: Option<&'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a)>, . fld_c: Option<&'a mut (dyn FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx> + 'a)>, . ) -> Self { 2,771,307 ( 0.00%) BoundVarReplacer { tcx, current_index: ty::INNERMOST, fld_r, fld_t, fld_c } 395,468 ( 0.00%) } . } . . impl<'a, 'tcx> TypeFolder<'tcx> for BoundVarReplacer<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 2,640,916 ( 0.00%) self.tcx 2,421,288 ( 0.00%) } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 7,211,115 ( 0.01%) self.current_index.shift_in(1); 19,927,500 ( 0.02%) let t = t.super_fold_with(self); 7,137,189 ( 0.01%) self.current_index.shift_out(1); . t . } . 19,788,995 ( 0.02%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 8,665,630 ( 0.01%) match *t.kind() { 143,274 ( 0.00%) ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => { 28,657 ( 0.00%) if let Some(fld_t) = self.fld_t.as_mut() { . let ty = fld_t(bound_ty); 28,657 ( 0.00%) return ty::fold::shift_vars(self.tcx, &ty, self.current_index.as_u32()); . } . } 8,608,316 ( 0.01%) _ if t.has_vars_bound_at_or_above(self.current_index) => { 1,372,969 ( 0.00%) return t.super_fold_with(self); . } . _ => {} . } . t 22,862,838 ( 0.02%) } . 1,806,196 ( 0.00%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 1,239,608 ( 0.00%) match *r { 1,086,192 ( 0.00%) ty::ReLateBound(debruijn, br) if debruijn == self.current_index => { 542,979 ( 0.00%) if let Some(fld_r) = self.fld_r.as_mut() { . let region = fld_r(br); 1,123,894 ( 0.00%) return if let ty::ReLateBound(debruijn1, br) = *region { . // If the callback returns a late-bound region, . // that region should always use the INNERMOST . // debruijn index. Then we adjust it to the . // correct depth. 18,968 ( 0.00%) assert_eq!(debruijn1, ty::INNERMOST); 181,198 ( 0.00%) self.tcx.mk_region(ty::ReLateBound(debruijn, br)) . } else { . region . }; . } . } . _ => {} . } . r 1,806,196 ( 0.00%) } . 20,972 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 15,504 ( 0.00%) match *ct { 3,300 ( 0.00%) ty::Const { val: ty::ConstKind::Bound(debruijn, bound_const), ty } 4,950 ( 0.00%) if debruijn == self.current_index => . { 1,650 ( 0.00%) if let Some(fld_c) = self.fld_c.as_mut() { . let ct = fld_c(bound_const, ty); 1,650 ( 0.00%) return ty::fold::shift_vars(self.tcx, &ct, self.current_index.as_u32()); . } . } 3,518 ( 0.00%) _ if ct.has_vars_bound_at_or_above(self.current_index) => { . return ct.super_fold_with(self); . } . _ => {} . } . ct 20,972 ( 0.00%) } . } . . impl<'tcx> TyCtxt<'tcx> { . /// Replaces all regions bound by the given `Binder` with the . /// results returned by the closure; the closure is expected to . /// return a free region (relative to this binder), and hence the . /// binder is removed in the return type. The closure is invoked . /// once for each unique `BoundRegionKind`; multiple references to the -- line 687 ---------------------------------------- -- line 697 ---------------------------------------- . mut fld_r: F, . ) -> (T, BTreeMap>) . where . F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>, . T: TypeFoldable<'tcx>, . { . let mut region_map = BTreeMap::new(); . let mut real_fld_r = 53,558,268 ( 0.05%) |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br)); 285,606 ( 0.00%) let value = value.skip_binder(); 52,060,134 ( 0.04%) let value = if !value.has_escaping_bound_vars() { 103,799,484 ( 0.09%) value . } else { 204,973 ( 0.00%) let mut replacer = BoundVarReplacer::new(self, Some(&mut real_fld_r), None, None); 81,554 ( 0.00%) value.fold_with(&mut replacer) . }; 187,322,983 ( 0.16%) (value, region_map) . } . . /// Replaces all escaping bound vars. The `fld_r` closure replaces escaping . /// bound regions; the `fld_t` closure replaces escaping bound types and the `fld_c` . /// closure replaces escaping bound consts. 2,606,290 ( 0.00%) pub fn replace_escaping_bound_vars( . self, . value: T, . mut fld_r: F, . mut fld_t: G, . mut fld_c: H, . ) -> T . where . F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>, . G: FnMut(ty::BoundTy) -> Ty<'tcx>, . H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>, . T: TypeFoldable<'tcx>, . { 3,736,672 ( 0.00%) if !value.has_escaping_bound_vars() { 47,723,583 ( 0.04%) value . } else { . let mut replacer = 4,457,435 ( 0.00%) BoundVarReplacer::new(self, Some(&mut fld_r), Some(&mut fld_t), Some(&mut fld_c)); 394,558 ( 0.00%) value.fold_with(&mut replacer) . } 1,800,162 ( 0.00%) } . . /// Replaces all types or regions bound by the given `Binder`. The `fld_r` . /// closure replaces bound regions while the `fld_t` closure replaces bound . /// types. 157,921,995 ( 0.14%) pub fn replace_bound_vars( . self, . value: Binder<'tcx, T>, . mut fld_r: F, . fld_t: G, . fld_c: H, . ) -> (T, BTreeMap>) . where . F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>, . G: FnMut(ty::BoundTy) -> Ty<'tcx>, . H: FnMut(ty::BoundVar, Ty<'tcx>) -> &'tcx ty::Const<'tcx>, . T: TypeFoldable<'tcx>, . { . let mut region_map = BTreeMap::new(); 1,042,613 ( 0.00%) let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br)); 155,889,738 ( 0.13%) let value = self.replace_escaping_bound_vars(value.skip_binder(), real_fld_r, fld_t, fld_c); 152,882,967 ( 0.13%) (value, region_map) 103,523,251 ( 0.09%) } . . /// Replaces any late-bound regions bound in `value` with . /// free variants attached to `all_outlive_scope`. 140,910 ( 0.00%) pub fn liberate_late_bound_regions( . self, . all_outlive_scope: DefId, . value: ty::Binder<'tcx, T>, . ) -> T . where . T: TypeFoldable<'tcx>, . { . self.replace_late_bound_regions(value, |br| { 140,530 ( 0.00%) self.mk_region(ty::ReFree(ty::FreeRegion { 21,620 ( 0.00%) scope: all_outlive_scope, . bound_region: br.kind, . })) . }) . .0 76,860 ( 0.00%) } . . pub fn shift_bound_var_indices(self, bound_vars: usize, value: T) -> T . where . T: TypeFoldable<'tcx>, . { . self.replace_escaping_bound_vars( 15,960,915 ( 0.01%) value, . |r| { . self.mk_region(ty::ReLateBound( . ty::INNERMOST, . ty::BoundRegion { . var: ty::BoundVar::from_usize(r.var.as_usize() + bound_vars), . kind: r.kind, . }, . )) -- line 795 ---------------------------------------- -- line 843 ---------------------------------------- . fn collect_late_bound_regions( . self, . value: &Binder<'tcx, T>, . just_constraint: bool, . ) -> FxHashSet . where . T: TypeFoldable<'tcx>, . { 16,632 ( 0.00%) let mut collector = LateBoundRegionsCollector::new(just_constraint); . let result = value.as_ref().skip_binder().visit_with(&mut collector); . assert!(result.is_continue()); // should never have stopped early 32,128 ( 0.00%) collector.regions . } . . /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also . /// method lookup and a few other places where precise region relationships are not required. 7 ( 0.00%) pub fn erase_late_bound_regions(self, value: Binder<'tcx, T>) -> T . where . T: TypeFoldable<'tcx>, . { 46,796 ( 0.00%) self.replace_late_bound_regions(value, |_| self.lifetimes.re_erased).0 6 ( 0.00%) } . . /// Rewrite any late-bound regions so that they are anonymous. Region numbers are . /// assigned starting at 0 and increasing monotonically in the order traversed . /// by the fold operation. . /// . /// The chief purpose of this function is to canonicalize regions so that two . /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become . /// structurally identical. For example, `for<'a, 'b> fn(&'a isize, &'b isize)` and . /// `for<'a, 'b> fn(&'b isize, &'a isize)` will become identical after anonymization. 105,914,811 ( 0.09%) pub fn anonymize_late_bound_regions(self, sig: Binder<'tcx, T>) -> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { 86,970,460 ( 0.07%) let mut counter = 0; 48,307,959 ( 0.04%) let inner = self . .replace_late_bound_regions(sig, |_| { . let br = ty::BoundRegion { 37,924 ( 0.00%) var: ty::BoundVar::from_u32(counter), . kind: ty::BrAnon(counter), . }; 151,696 ( 0.00%) let r = self.mk_region(ty::ReLateBound(ty::INNERMOST, br)); 94,810 ( 0.00%) counter += 1; . r . }) . .0; 17,394,092 ( 0.01%) let bound_vars = self.mk_bound_variable_kinds( 52,182,276 ( 0.04%) (0..counter).map(|i| ty::BoundVariableKind::Region(ty::BrAnon(i))), . ); 103,843,968 ( 0.09%) Binder::bind_with_vars(inner, bound_vars) 88,521,087 ( 0.08%) } . } . . pub struct ValidateBoundVars<'tcx> { . bound_vars: &'tcx ty::List, . binder_index: ty::DebruijnIndex, . // We may encounter the same variable at different levels of binding, so . // this can't just be `Ty` . visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>, -- line 902 ---------------------------------------- -- line 1004 ---------------------------------------- . tcx: TyCtxt<'tcx>, . current_index: ty::DebruijnIndex, . amount: u32, . } . . impl<'tcx> Shifter<'tcx> { . pub fn new(tcx: TyCtxt<'tcx>, amount: u32) -> Self { . Shifter { tcx, current_index: ty::INNERMOST, amount } 60,792 ( 0.00%) } . } . . impl<'tcx> TypeFolder<'tcx> for Shifter<'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 620 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { . self.current_index.shift_in(1); . let t = t.super_fold_with(self); . self.current_index.shift_out(1); . t . } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 388 ( 0.00%) match *r { . ty::ReLateBound(debruijn, br) => { 776 ( 0.00%) if self.amount == 0 || debruijn < self.current_index { . r . } else { 194 ( 0.00%) let debruijn = debruijn.shifted_in(self.amount); . let shifted = ty::ReLateBound(debruijn, br); 1,940 ( 0.00%) self.tcx.mk_region(shifted) . } . } . _ => r, . } . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 64,716 ( 0.00%) match *ty.kind() { . ty::Bound(debruijn, bound_ty) => { . if self.amount == 0 || debruijn < self.current_index { . ty . } else { . let debruijn = debruijn.shifted_in(self.amount); . self.tcx.mk_ty(ty::Bound(debruijn, bound_ty)) . } . } . 104,892 ( 0.00%) _ => ty.super_fold_with(self), . } . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 3,770 ( 0.00%) if let ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty } = *ct { . if self.amount == 0 || debruijn < self.current_index { . ct . } else { . let debruijn = debruijn.shifted_in(self.amount); . self.tcx.mk_const(ty::Const { val: ty::ConstKind::Bound(debruijn, bound_ct), ty }) . } . } else { 5,655 ( 0.00%) ct.super_fold_with(self) . } . } . } . . pub fn shift_region<'tcx>( . tcx: TyCtxt<'tcx>, . region: ty::Region<'tcx>, . amount: u32, . ) -> ty::Region<'tcx> { . match region { . ty::ReLateBound(debruijn, br) if amount > 0 => { 3,692 ( 0.00%) tcx.mk_region(ty::ReLateBound(debruijn.shifted_in(amount), *br)) . } . _ => region, . } . } . . pub fn shift_vars<'tcx, T>(tcx: TyCtxt<'tcx>, value: T, amount: u32) -> T . where . T: TypeFoldable<'tcx>, . { . debug!("shift_vars(value={:?}, amount={})", value, amount); . 60,836 ( 0.00%) value.fold_with(&mut Shifter::new(tcx, amount)) . } . . #[derive(Debug, PartialEq, Eq, Copy, Clone)] . struct FoundEscapingVars; . . /// An "escaping var" is a bound var whose binder is not part of `t`. A bound var can be a . /// bound region or a bound type. . /// -- line 1101 ---------------------------------------- -- line 1128 ---------------------------------------- . . impl<'tcx> TypeVisitor<'tcx> for HasEscapingVarsVisitor { . type BreakTy = FoundEscapingVars; . . fn visit_binder>( . &mut self, . t: &Binder<'tcx, T>, . ) -> ControlFlow { 191,850 ( 0.00%) self.outer_index.shift_in(1); . let result = t.super_visit_with(self); 262,277 ( 0.00%) self.outer_index.shift_out(1); . result . } . . #[inline] . fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { . // If the outer-exclusive-binder is *strictly greater* than . // `outer_index`, that means that `t` contains some content . // bound at `outer_index` or above (because -- line 1146 ---------------------------------------- -- line 1160 ---------------------------------------- . // visited. . if r.bound_at_or_above_binder(self.outer_index) { . ControlFlow::Break(FoundEscapingVars) . } else { . ControlFlow::CONTINUE . } . } . 50,570 ( 0.00%) fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> ControlFlow { . // we don't have a `visit_infer_const` callback, so we have to . // hook in here to catch this case (annoying...), but . // otherwise we do want to remember to visit the rest of the . // const, as it has types/regions embedded in a lot of other . // places. 460,683 ( 0.00%) match ct.val { 693 ( 0.00%) ty::ConstKind::Bound(debruijn, _) if debruijn >= self.outer_index => { . ControlFlow::Break(FoundEscapingVars) . } 3,420 ( 0.00%) _ => ct.super_visit_with(self), . } 50,108 ( 0.00%) } . . #[inline] . fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow { . if predicate.inner.outer_exclusive_binder > self.outer_index { . ControlFlow::Break(FoundEscapingVars) . } else { . ControlFlow::CONTINUE . } -- line 1188 ---------------------------------------- -- line 1210 ---------------------------------------- . #[instrument(level = "trace")] . fn visit_ty(&mut self, t: Ty<'_>) -> ControlFlow { . debug!( . "HasTypeFlagsVisitor: t={:?} t.flags={:?} self.flags={:?}", . t, . t.flags(), . self.flags . ); 86,168,654 ( 0.07%) if t.flags().intersects(self.flags) { . ControlFlow::Break(FoundFlags) . } else { . ControlFlow::CONTINUE . } . } . . #[inline] . #[instrument(skip(self), level = "trace")] . fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { 285,481 ( 0.00%) let flags = r.type_flags(); . trace!(r.flags=?flags); . if flags.intersects(self.flags) { . ControlFlow::Break(FoundFlags) . } else { . ControlFlow::CONTINUE . } . } . . #[inline] . #[instrument(level = "trace")] . fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow { 1,467,394 ( 0.00%) let flags = FlagComputation::for_const(c); . trace!(r.flags=?flags); 10,014 ( 0.00%) if flags.intersects(self.flags) { . ControlFlow::Break(FoundFlags) . } else { . ControlFlow::CONTINUE . } . } . . #[inline] . #[instrument(level = "trace")] . fn visit_unevaluated_const(&mut self, uv: ty::Unevaluated<'tcx>) -> ControlFlow { 371,047,116 ( 0.32%) let flags = FlagComputation::for_unevaluated_const(uv); . trace!(r.flags=?flags); . if flags.intersects(self.flags) { . ControlFlow::Break(FoundFlags) . } else { . ControlFlow::CONTINUE . } . } . -- line 1260 ---------------------------------------- -- line 1285 ---------------------------------------- . /// them constraints `'a == 'b`. But if you have `<&'a u32 as . /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those . /// types may mean that `'a` and `'b` don't appear in the results, . /// so they are not considered *constrained*. . just_constrained: bool, . } . . impl LateBoundRegionsCollector { 8,032 ( 0.00%) fn new(just_constrained: bool) -> Self { 56,224 ( 0.00%) LateBoundRegionsCollector { . current_index: ty::INNERMOST, . regions: Default::default(), . just_constrained, . } 8,032 ( 0.00%) } . } . . impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector { . fn visit_binder>( . &mut self, . t: &Binder<'tcx, T>, . ) -> ControlFlow { . self.current_index.shift_in(1); . let result = t.super_visit_with(self); . self.current_index.shift_out(1); . result . } . 34,455 ( 0.00%) fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { . // if we are only looking for "constrained" region, we have to . // ignore the inputs to a projection, as they may not appear . // in the normalized form 82,194 ( 0.00%) if self.just_constrained { 91,810 ( 0.00%) if let ty::Projection(..) | ty::Opaque(..) = t.kind() { . return ControlFlow::CONTINUE; . } . } . 117,357 ( 0.00%) t.super_visit_with(self) 23,638 ( 0.00%) } . . fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow { . // if we are only looking for "constrained" region, we have to . // ignore the inputs of an unevaluated const, as they may not appear . // in the normalized form 22,475 ( 0.00%) if self.just_constrained { 6,020 ( 0.00%) if let ty::ConstKind::Unevaluated(..) = c.val { . return ControlFlow::CONTINUE; . } . } . . c.super_visit_with(self) . } . . fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { 21,395 ( 0.00%) if let ty::ReLateBound(debruijn, br) = *r { 3,595 ( 0.00%) if debruijn == self.current_index { . self.regions.insert(br.kind); . } . } . ControlFlow::CONTINUE . } . } 61,224,255 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/higher_ranked/mod.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . // Rather than checking the subtype relationship between `a` and `b` . // as-is, we need to do some extra work here in order to make sure . // that function subtyping works correctly with respect to regions . // . // Note: this is a subtle algorithm. For a full explanation, please see . // the rustc dev guide: . // . 1,125,842 ( 0.00%) let span = self.trace.cause.span; . 7,317,973 ( 0.01%) self.infcx.commit_if_ok(|_| { . // First, we instantiate each bound region in the supertype with a . // fresh placeholder region. 5,056,757 ( 0.00%) let b_prime = self.infcx.replace_bound_vars_with_placeholders(b); . . // Next, we instantiate each bound region in the subtype . // with a fresh region variable. These region variables -- . // but no other pre-existing region variables -- can name . // the placeholders. 1,121,830 ( 0.00%) let (a_prime, _) = 2,252,182 ( 0.00%) self.infcx.replace_bound_vars_with_fresh_vars(span, HigherRankedType, a); . . debug!("a_prime={:?}", a_prime); . debug!("b_prime={:?}", b_prime); . . // Compare types now that bound regions have been replaced. 3,937,943 ( 0.00%) let result = self.sub(a_is_expected).relate(a_prime, b_prime)?; . . debug!("higher_ranked_sub: OK result={:?}", result); . . // We related `a_prime` and `b_prime`, which just had any bound vars . // replaced with placeholders or infer vars, respectively. Relating . // them should not introduce new bound vars. . Ok(ty::Binder::dummy(result)) . }) -- line 56 ---------------------------------------- -- line 63 ---------------------------------------- . /// placeholder region. This is the first step of checking subtyping . /// when higher-ranked things are involved. . /// . /// **Important:** You have to be careful to not leak these placeholders, . /// for more information about how placeholders and HRTBs work, see . /// the [rustc dev guide]. . /// . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 75,125,887 ( 0.06%) pub fn replace_bound_vars_with_placeholders(&self, binder: ty::Binder<'tcx, T>) -> T . where . T: TypeFoldable<'tcx>, . { . // Figure out what the next universe will be, but don't actually create . // it until after we've done the substitution (in particular there may . // be no bound variables). This is a performance optimization, since the . // leak check for example can be skipped if no new universes are created . // (i.e., if there are no placeholders). 53,845,166 ( 0.05%) let next_universe = self.universe().next_universe(); . . let fld_r = |br: ty::BoundRegion| { 18,148 ( 0.00%) self.tcx.mk_region(ty::RePlaceholder(ty::PlaceholderRegion { 2,792 ( 0.00%) universe: next_universe, . name: br.kind, . })) . }; . . let fld_t = |bound_ty: ty::BoundTy| { . self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType { . universe: next_universe, . name: bound_ty.var, -- line 92 ---------------------------------------- -- line 98 ---------------------------------------- . val: ty::ConstKind::Placeholder(ty::PlaceholderConst { . universe: next_universe, . name: ty::BoundConst { var: bound_var, ty }, . }), . ty, . }) . }; . 260,111,166 ( 0.22%) let (result, map) = self.tcx.replace_bound_vars(binder, fld_r, fld_t, fld_c); . . // If there were higher-ranked regions to replace, then actually create . // the next universe (this avoids needlessly creating universes). 10,886,848 ( 0.01%) if !map.is_empty() { 1,271 ( 0.00%) let n_u = self.create_next_universe(); 585 ( 0.00%) assert_eq!(n_u, next_universe); . } . . debug!( . "replace_bound_vars_with_placeholders(\ . next_universe={:?}, \ . result={:?}, \ . map={:?})", . next_universe, result, map, . ); . . result 65,436,795 ( 0.06%) } . . /// See `infer::region_constraints::RegionConstraintCollector::leak_check`. 21,245,298 ( 0.02%) pub fn leak_check( . &self, . overly_polymorphic: bool, . snapshot: &CombinedSnapshot<'_, 'tcx>, . ) -> RelateResult<'tcx, ()> { . // If the user gave `-Zno-leak-check`, or we have been . // configured to skip the leak check, then skip the leak check . // completely. The leak check is deprecated. Any legitimate . // subtyping errors that it would have caught will now be . // caught later on, during region checking. However, we . // continue to use it for a transition period. 17,704,415 ( 0.02%) if self.tcx.sess.opts.debugging_opts.no_leak_check || self.skip_leak_check.get() { 3,193,257 ( 0.00%) return Ok(()); . } . 2,085,756 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().leak_check( . self.tcx, . overly_polymorphic, . self.universe(), . snapshot, . ) 17,704,415 ( 0.02%) } . } 14,418,610 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_type_ir/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[macro_use] . extern crate rustc_macros; . . use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; . use rustc_data_structures::unify::{EqUnifyValue, UnifyKey}; . use std::fmt; . use std::mem::discriminant; . 309,014,955 ( 0.27%) bitflags! { . /// Flags that we track on types. These flags are propagated upwards . /// through the type during type construction, so that we can quickly check . /// whether the type has various kinds of types in it without recursing . /// over the type itself. . pub struct TypeFlags: u32 { . // Does this have parameters? Used to determine whether substitution is . // required. . /// Does this have `Param`? -- line 21 ---------------------------------------- -- line 163 ---------------------------------------- . /// for<'a> fn(&'a x) . /// . /// and you wanted to change it to . /// . /// for<'a> fn(for<'b> fn(&'a x)) . /// . /// you would need to shift the index for `'a` into a new binder. . #[must_use] 13,933 ( 0.00%) pub fn shifted_in(self, amount: u32) -> DebruijnIndex { 48,855,982 ( 0.04%) DebruijnIndex::from_u32(self.as_u32() + amount) 41,799 ( 0.00%) } . . /// Update this index in place by shifting it "in" through . /// `amount` number of binders. 24,414,058 ( 0.02%) pub fn shift_in(&mut self, amount: u32) { 24,414,058 ( 0.02%) *self = self.shifted_in(amount); 48,828,116 ( 0.04%) } . . /// Returns the resulting index when this value is moved out from . /// `amount` number of new binders. . #[must_use] 6,485 ( 0.00%) pub fn shifted_out(self, amount: u32) -> DebruijnIndex { 48,841,086 ( 0.04%) DebruijnIndex::from_u32(self.as_u32() - amount) 19,455 ( 0.00%) } . . /// Update in place by shifting out from `amount` binders. 24,414,058 ( 0.02%) pub fn shift_out(&mut self, amount: u32) { 48,828,116 ( 0.04%) *self = self.shifted_out(amount); 48,828,116 ( 0.04%) } . . /// Adjusts any De Bruijn indices so as to make `to_binder` the . /// innermost binder. That is, if we have something bound at `to_binder`, . /// it will now be bound at INNERMOST. This is an appropriate thing to do . /// when moving a region out from inside binders: . /// . /// ``` . /// for<'a> fn(for<'b> for<'c> fn(&'a u32), _) -- line 199 ---------------------------------------- -- line 210 ---------------------------------------- . /// If we invoke `shift_out_to_binder` and the region is in fact . /// bound by one of the binders we are shifting out of, that is an . /// error (and should fail an assertion failure). . pub fn shifted_out_to_binder(self, to_binder: DebruijnIndex) -> Self { . self.shifted_out(to_binder.as_u32() - INNERMOST.as_u32()) . } . } . 546 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 4,156 ( 0.00%) #[derive(Encodable, Decodable)] . pub enum IntTy { . Isize, . I8, . I16, . I32, . I64, . I128, . } . . impl IntTy { . pub fn name_str(&self) -> &'static str { 56 ( 0.00%) match *self { . IntTy::Isize => "isize", . IntTy::I8 => "i8", . IntTy::I16 => "i16", . IntTy::I32 => "i32", . IntTy::I64 => "i64", . IntTy::I128 => "i128", . } 8 ( 0.00%) } . . pub fn bit_width(&self) -> Option { . Some(match *self { . IntTy::Isize => return None, . IntTy::I8 => 8, . IntTy::I16 => 16, . IntTy::I32 => 32, . IntTy::I64 => 64, . IntTy::I128 => 128, . }) . } . 534 ( 0.00%) pub fn normalize(&self, target_width: u32) -> Self { 1,602 ( 0.00%) match self { 1,058 ( 0.00%) IntTy::Isize => match target_width { . 16 => IntTy::I16, . 32 => IntTy::I32, . 64 => IntTy::I64, . _ => unreachable!(), . }, . _ => *self, . } 1,068 ( 0.00%) } . } . 570 ( 0.00%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)] 9,574 ( 0.00%) #[derive(Encodable, Decodable)] . pub enum UintTy { . Usize, . U8, . U16, . U32, . U64, . U128, . } . . impl UintTy { . pub fn name_str(&self) -> &'static str { 343 ( 0.00%) match *self { . UintTy::Usize => "usize", . UintTy::U8 => "u8", . UintTy::U16 => "u16", . UintTy::U32 => "u32", . UintTy::U64 => "u64", . UintTy::U128 => "u128", . } 49 ( 0.00%) } . . pub fn bit_width(&self) -> Option { 3,648 ( 0.00%) Some(match *self { . UintTy::Usize => return None, . UintTy::U8 => 8, . UintTy::U16 => 16, . UintTy::U32 => 32, . UintTy::U64 => 64, . UintTy::U128 => 128, . }) 608 ( 0.00%) } . 4,925 ( 0.00%) pub fn normalize(&self, target_width: u32) -> Self { 14,775 ( 0.00%) match self { 9,642 ( 0.00%) UintTy::Usize => match target_width { . 16 => UintTy::U16, . 32 => UintTy::U32, . 64 => UintTy::U64, . _ => unreachable!(), . }, . _ => *self, . } 9,850 ( 0.00%) } . } . 161 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 2,228 ( 0.00%) #[derive(Encodable, Decodable)] . pub enum FloatTy { . F32, . F64, . } . . impl FloatTy { . pub fn name_str(self) -> &'static str { . match self { -- line 321 ---------------------------------------- -- line 327 ---------------------------------------- . pub fn bit_width(self) -> u64 { . match self { . FloatTy::F32 => 32, . FloatTy::F64 => 64, . } . } . } . 2 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq)] . pub enum IntVarValue { . IntType(IntTy), . UintType(UintTy), . } . 768 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq)] . pub struct FloatVarValue(pub FloatTy); . . rustc_index::newtype_index! { . /// A **ty**pe **v**ariable **ID**. . pub struct TyVid { . DEBUG_FORMAT = "_#{}t" . } . } . . /// An **int**egral (`u32`, `i32`, `usize`, etc.) type **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub struct IntVid { 53,320 ( 0.00%) pub index: u32, . } . . /// An **float**ing-point (`f32` or `f64`) type **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub struct FloatVid { 4,973 ( 0.00%) pub index: u32, . } . . /// A placeholder for a type that hasn't been inferred yet. . /// . /// E.g., if we have an empty array (`[]`), then we create a fresh . /// type variable for the element type since we won't know until it's . /// used what the element type is supposed to be. 16,405,970 ( 0.01%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum InferTy { . /// A type variable. . TyVar(TyVid), . /// An integral type variable (`{integer}`). . /// . /// These are created when the compiler sees an integer literal like . /// `1` that could be several different types (`u8`, `i32`, `u32`, etc.). . /// We don't know until it's used what type it's supposed to be, so -- line 376 ---------------------------------------- -- line 396 ---------------------------------------- . FreshFloatTy(u32), . } . . /// Raw `TyVid` are used as the unification key for `sub_relations`; . /// they carry no values. . impl UnifyKey for TyVid { . type Value = (); . fn index(&self) -> u32 { 867,915 ( 0.00%) self.as_u32() 867,915 ( 0.00%) } . fn from_index(i: u32) -> TyVid { . TyVid::from_u32(i) 1,856,806 ( 0.00%) } . fn tag() -> &'static str { . "TyVid" . } . } . . impl EqUnifyValue for IntVarValue {} . . impl UnifyKey for IntVid { . type Value = Option; . #[inline] // make this function eligible for inlining - it is quite hot. . fn index(&self) -> u32 { . self.index . } 52,282 ( 0.00%) fn from_index(i: u32) -> IntVid { . IntVid { index: i } 52,282 ( 0.00%) } . fn tag() -> &'static str { . "IntVid" . } . } . . impl EqUnifyValue for FloatVarValue {} . . impl UnifyKey for FloatVid { . type Value = Option; . fn index(&self) -> u32 { 9,980 ( 0.00%) self.index 9,980 ( 0.00%) } . fn from_index(i: u32) -> FloatVid { . FloatVid { index: i } . } . fn tag() -> &'static str { . "FloatVid" . } . } . 506,944 ( 0.00%) #[derive(Copy, Clone, PartialEq, Decodable, Encodable, Hash)] . pub enum Variance { . Covariant, // T <: T iff A <: B -- e.g., function return type . Invariant, // T <: T iff B == A -- e.g., type of mutable cell . Contravariant, // T <: T iff B <: A -- e.g., function param type . Bivariant, // T <: T -- e.g., unused type parameter . } . . impl Variance { -- line 453 ---------------------------------------- -- line 482 ---------------------------------------- . /// `Contravariant.xform(Covariant)` or `Contravariant`. The same . /// is true for its `i32` argument. In the `*mut T` case, the . /// variance of `Vec` is `Contravariant.xform(Invariant)`, . /// and hence the outermost type is `Invariant` with respect to . /// `Vec` (and its `i32` argument). . /// . /// Source: Figure 1 of "Taming the Wildcards: . /// Combining Definition- and Use-Site Variance" published in PLDI'11. 838,169 ( 0.00%) pub fn xform(self, v: Variance) -> Variance { 5,106,833 ( 0.00%) match (self, v) { . // Figure 1, column 1. . (Variance::Covariant, Variance::Covariant) => Variance::Covariant, . (Variance::Covariant, Variance::Contravariant) => Variance::Contravariant, . (Variance::Covariant, Variance::Invariant) => Variance::Invariant, . (Variance::Covariant, Variance::Bivariant) => Variance::Bivariant, . . // Figure 1, column 2. . (Variance::Contravariant, Variance::Covariant) => Variance::Contravariant, -- line 499 ---------------------------------------- -- line 502 ---------------------------------------- . (Variance::Contravariant, Variance::Bivariant) => Variance::Bivariant, . . // Figure 1, column 3. . (Variance::Invariant, _) => Variance::Invariant, . . // Figure 1, column 4. . (Variance::Bivariant, _) => Variance::Bivariant, . } 838,169 ( 0.00%) } . } . . impl HashStable for DebruijnIndex { . fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . self.as_u32().hash_stable(ctx, hasher); . } . } . -- line 518 ---------------------------------------- 55,774,515 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs -------------------------------------------------------------------------------- Ir -- line 165 ---------------------------------------- . #[rustc_insignificant_dtor] . pub struct BTreeMap { . root: Option>, . length: usize, . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap { 169,377,221 ( 0.15%) fn drop(&mut self) { . drop(unsafe { ptr::read(self) }.into_iter()) 169,517,537 ( 0.15%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for BTreeMap { . fn clone(&self) -> BTreeMap { 105 ( 0.00%) fn clone_subtree<'a, K: Clone, V: Clone>( . node: NodeRef, K, V, marker::LeafOrInternal>, . ) -> BTreeMap . where . K: 'a, . V: 'a, . { 12 ( 0.00%) match node.force() { . Leaf(leaf) => { 29 ( 0.00%) let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 }; . . { . let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped . let mut out_node = match root.borrow_mut().force() { . Leaf(leaf) => leaf, . Internal(_) => unreachable!(), . }; . . let mut in_edge = leaf.first_edge(); . while let Ok(kv) = in_edge.right_kv() { . let (k, v) = kv.into_kv(); . in_edge = kv.right_edge(); . 37 ( 0.00%) out_node.push(k.clone(), v.clone()); 98 ( 0.00%) out_tree.length += 1; . } . } . 44 ( 0.00%) out_tree . } . Internal(internal) => { . let mut out_tree = clone_subtree(internal.first_edge().descend()); . . { . let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root); . let mut out_node = out_root.push_internal_level(); . let mut in_edge = internal.first_edge(); -- line 217 ---------------------------------------- -- line 235 ---------------------------------------- . out_node.push(k, v, subroot.unwrap_or_else(Root::new)); . out_tree.length += 1 + sublength; . } . } . . out_tree . } . } 96 ( 0.00%) } . 13 ( 0.00%) if self.is_empty() { . BTreeMap::new() . } else { 35 ( 0.00%) clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty . } . } . } . . impl super::Recover for BTreeMap . where . K: Borrow + Ord, . Q: Ord, -- line 256 ---------------------------------------- -- line 515 ---------------------------------------- . /// . /// // entries can now be inserted into the empty map . /// map.insert(1, "a"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . #[must_use] . pub const fn new() -> BTreeMap { 76,632,562 ( 0.07%) BTreeMap { root: None, length: 0 } . } . . /// Clears the map, removing all elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 531 ---------------------------------------- -- line 560 ---------------------------------------- . /// assert_eq!(map.get(&2), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, key: &Q) -> Option<&V> . where . K: Borrow + Ord, . Q: Ord, . { 1,950 ( 0.00%) let root_node = self.root.as_ref()?.reborrow(); 2,193 ( 0.00%) match root_node.search_tree(key) { 1,526 ( 0.00%) Found(handle) => Some(handle.into_kv().1), . GoDown(_) => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but the ordering . /// on the borrowed form *must* match the ordering on the key type. -- line 578 ---------------------------------------- -- line 848 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,602 ( 0.00%) pub fn insert(&mut self, key: K, value: V) -> Option . where . K: Ord, . { . match self.entry(key) { . Occupied(mut entry) => Some(entry.insert(value)), . Vacant(entry) => { 1,614 ( 0.00%) entry.insert(value); 3 ( 0.00%) None . } . } 1,072 ( 0.00%) } . . /// Tries to insert a key-value pair into the map, and returns . /// a mutable reference to the value in the entry. . /// . /// If the map already had this key present, nothing is updated, and . /// an error containing the occupied entry and the value is returned. . /// . /// # Examples -- line 875 ---------------------------------------- -- line 914 ---------------------------------------- . /// use std::collections::BTreeMap; . /// . /// let mut map = BTreeMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 2,899,304 ( 0.00%) pub fn remove(&mut self, key: &Q) -> Option . where . K: Borrow + Ord, . Q: Ord, . { 1,812,065 ( 0.00%) self.remove_entry(key).map(|(_, v)| v) 3,261,717 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the key . /// was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but the ordering . /// on the borrowed form *must* match the ordering on the key type. . /// . /// # Examples -- line 936 ---------------------------------------- -- line 947 ---------------------------------------- . /// ``` . #[stable(feature = "btreemap_remove_entry", since = "1.45.0")] . pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> . where . K: Borrow + Ord, . Q: Ord, . { . let (map, dormant_map) = DormantMutRef::new(self); 362,413 ( 0.00%) let root_node = map.root.as_mut()?.borrow_mut(); 1,812,065 ( 0.00%) match root_node.search_tree(key) { . Found(handle) => { 724,826 ( 0.00%) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) 362,413 ( 0.00%) } . GoDown(_) => None, . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. . /// The elements are visited in ascending key order. -- line 967 ---------------------------------------- -- line 1135 ---------------------------------------- . /// // count the number of occurrences of letters in the vec . /// for x in ["a", "b", "a", "c", "a", "b"] { . /// *count.entry(x).or_insert(0) += 1; . /// } . /// . /// assert_eq!(count["a"], 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 80 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V> . where . K: Ord, . { . // FIXME(@porglezomp) Avoid allocating if we don't insert . let (map, dormant_map) = DormantMutRef::new(self); . let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); 1,395,874 ( 0.00%) match root_node.search_tree(&key) { 14,136 ( 0.00%) Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), . GoDown(handle) => { 364,715 ( 0.00%) Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }) . } . } 72 ( 0.00%) } . . /// Splits the collection into two at the given key. Returns everything after the given key, . /// including the key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1164 ---------------------------------------- -- line 1307 ---------------------------------------- . } . . /// Makes a `BTreeMap` from a sorted iterator. . pub(crate) fn bulk_build_from_sorted_iter(iter: I) -> Self . where . K: Ord, . I: IntoIterator, . { 16 ( 0.00%) let mut root = Root::new(); 8 ( 0.00%) let mut length = 0; 40 ( 0.00%) root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length); 16 ( 0.00%) BTreeMap { root: Some(root), length } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> IntoIterator for &'a BTreeMap { . type Item = (&'a K, &'a V); . type IntoIter = Iter<'a, K, V>; . -- line 1326 ---------------------------------------- -- line 1328 ---------------------------------------- . self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . 19 ( 0.00%) fn next(&mut self) -> Option<(&'a K, &'a V)> { 1,489,256 ( 0.00%) if self.length == 0 { . None . } else { 518,652 ( 0.00%) self.length -= 1; . Some(unsafe { self.range.next_unchecked() }) . } 33 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . (self.length, Some(self.length)) . } . . fn last(mut self) -> Option<(&'a K, &'a V)> { . self.next_back() . } -- line 1351 ---------------------------------------- -- line 1460 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for BTreeMap { . type Item = (K, V); . type IntoIter = IntoIter; . . fn into_iter(self) -> IntoIter { . let mut me = ManuallyDrop::new(self); 59,066,192 ( 0.05%) if let Some(root) = me.root.take() { . let full_range = root.into_dying().full_range(); . 48 ( 0.00%) IntoIter { range: full_range, length: me.length } . } else { 34,918,368 ( 0.03%) IntoIter { range: LazyLeafRange::none(), length: 0 } . } . } . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . impl Drop for IntoIter { 91,038 ( 0.00%) fn drop(&mut self) { . struct DropGuard<'a, K, V>(&'a mut IntoIter); . . impl<'a, K, V> Drop for DropGuard<'a, K, V> { . fn drop(&mut self) { . // Continue the same loop we perform below. This only runs when unwinding, so we . // don't have to care about panics this time (they'll abort). . while let Some(kv) = self.0.dying_next() { . // SAFETY: we consume the dying handle immediately. . unsafe { kv.drop_key_val() }; . } . } . } . 4,865,781 ( 0.00%) while let Some(kv) = self.dying_next() { . let guard = DropGuard(self); . // SAFETY: we don't touch the tree before consuming the dying handle. 74,066 ( 0.00%) unsafe { kv.drop_key_val() }; . mem::forget(guard); . } 91,038 ( 0.00%) } . } . . impl IntoIter { . /// Core of a `next` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. 10,027,641 ( 0.01%) fn dying_next( . &mut self, . ) -> Option, marker::KV>> { 60,945,452 ( 0.05%) if self.length == 0 { . self.range.deallocating_end(); 2,712,238 ( 0.00%) None . } else { 352,630 ( 0.00%) self.length -= 1; 320,031 ( 0.00%) Some(unsafe { self.range.deallocating_next_unchecked() }) . } 10,027,637 ( 0.01%) } . . /// Core of a `next_back` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. . fn dying_next_back( . &mut self, . ) -> Option, marker::KV>> { . if self.length == 0 { . self.range.deallocating_end(); -- line 1524 ---------------------------------------- -- line 1529 ---------------------------------------- . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = (K, V); . 21,252 ( 0.00%) fn next(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next().map(unsafe { |kv| kv.into_key_val() }) 24,288 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { 2,902 ( 0.00%) (self.length, Some(self.length)) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . fn next_back(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next_back().map(unsafe { |kv| kv.into_key_val() }) -- line 1551 ---------------------------------------- -- line 1562 ---------------------------------------- . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for IntoIter {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . fn next(&mut self) -> Option<&'a K> { 10 ( 0.00%) self.inner.next().map(|(k, _)| k) . } . . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . . fn last(mut self) -> Option<&'a K> { . self.next_back() -- line 1578 ---------------------------------------- -- line 2089 ---------------------------------------- . /// println!("{}: {}", key, value); . /// } . /// . /// let (first_key, first_value) = map.iter().next().unwrap(); . /// assert_eq!((*first_key, *first_value), (1, "a")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn iter(&self) -> Iter<'_, K, V> { 2,160,812 ( 0.00%) if let Some(root) = &self.root { . let full_range = root.reborrow().full_range(); . 31 ( 0.00%) Iter { range: full_range, length: self.length } . } else { 6 ( 0.00%) Iter { range: LazyLeafRange::none(), length: 0 } . } . } . . /// Gets a mutable iterator over the entries of the map, sorted by key. . /// . /// # Examples . /// . /// Basic usage: -- line 2110 ---------------------------------------- -- line 2149 ---------------------------------------- . /// a.insert(2, "b"); . /// a.insert(1, "a"); . /// . /// let keys: Vec<_> = a.keys().cloned().collect(); . /// assert_eq!(keys, [1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn keys(&self) -> Keys<'_, K, V> { 23,397 ( 0.00%) Keys { inner: self.iter() } . } . . /// Gets an iterator over the values of the map, in order by key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2165 ---------------------------------------- -- line 2217 ---------------------------------------- . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn len(&self) -> usize { 11 ( 0.00%) self.length . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2233 ---------------------------------------- -- line 2238 ---------------------------------------- . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn is_empty(&self) -> bool { 10,896,063 ( 0.01%) self.len() == 0 . } . . /// If the root node is the empty (non-allocated) root node, allocate our . /// own node. Is an associated function to avoid borrowing the entire BTreeMap. . fn ensure_is_owned(root: &mut Option>) -> &mut Root { . root.get_or_insert_with(Root::new) . } . } -- line 2254 ---------------------------------------- 1,559,993 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs -------------------------------------------------------------------------------- Ir -- line 417 ---------------------------------------- . /// # #![allow(unused_mut)] . /// let mut vec: Vec = Vec::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub const fn new() -> Self { 151,200,794 ( 0.13%) Vec { buf: RawVec::NEW, len: 0 } 2,959 ( 0.00%) } . . /// Constructs a new, empty `Vec` with the specified capacity. . /// . /// The vector will be able to hold exactly `capacity` elements without . /// reallocating. If `capacity` is 0, the vector will not allocate. . /// . /// It is important to note that although the returned vector has the . /// *capacity* specified, the vector will have a zero *length*. For an -- line 434 ---------------------------------------- -- line 601 ---------------------------------------- . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 26,461,427 ( 0.02%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } . } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: -- line 617 ---------------------------------------- -- line 677 ---------------------------------------- . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 1,283,054 ( 0.00%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } . } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. -- line 693 ---------------------------------------- -- line 778 ---------------------------------------- . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn capacity(&self) -> usize { 5,145,059 ( 0.00%) self.buf.capacity() . } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 794 ---------------------------------------- -- line 801 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 15,126,850 ( 0.01%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 188,182 ( 0.00%) self.buf.reserve_exact(self.len, additional); . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `try_reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 845 ---------------------------------------- -- line 930 ---------------------------------------- . /// assert!(vec.capacity() >= 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn shrink_to_fit(&mut self) { . // The capacity is never less than the length, and there's nothing to do when . // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` . // by only calling it with a greater capacity. 348,350 ( 0.00%) if self.capacity() > self.len { 270,868 ( 0.00%) self.buf.shrink_to_fit(self.len); . } . } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// -- line 947 ---------------------------------------- -- line 990 ---------------------------------------- . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { . self.shrink_to_fit(); 94,437 ( 0.00%) let me = ManuallyDrop::new(self); . let buf = ptr::read(&me.buf); . let len = me.len(); . buf.into_box(len).assume_init() . } . } . . /// Shortens the vector, keeping the first `len` elements and dropping . /// the rest. -- line 1006 ---------------------------------------- -- line 1040 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.truncate(0); . /// assert_eq!(vec, []); . /// ``` . /// . /// [`clear`]: Vec::clear . /// [`drain`]: Vec::drain . #[stable(feature = "rust1", since = "1.0.0")] 2,887,424 ( 0.00%) pub fn truncate(&mut self, len: usize) { . // This is safe because: . // . // * the slice passed to `drop_in_place` is valid; the `len > self.len` . // case avoids creating an invalid slice, and . // * the `len` of the vector is shrunk before calling `drop_in_place`, . // such that no value will be dropped twice in case `drop_in_place` . // were to panic once (if it panics twice, the program aborts). . unsafe { . // Note: It's intentional that this is `>` and not `>=`. . // Changing it to `>=` has negative performance . // implications in some cases. See #78884 for more. 2,686,786 ( 0.00%) if len > self.len { . return; . } . let remaining_len = self.len - len; . let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 3,706,152 ( 0.00%) self.len = len; 85,253 ( 0.00%) ptr::drop_in_place(s); . } 3,464,900 ( 0.00%) } . . /// Extracts a slice containing the entire vector. . /// . /// Equivalent to `&s[..]`. . /// . /// # Examples . /// . /// ``` -- line 1076 ---------------------------------------- -- line 1126 ---------------------------------------- . /// ``` . /// . /// [`as_mut_ptr`]: Vec::as_mut_ptr . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_ptr(&self) -> *const T { . // We shadow the slice method of the same name to avoid going through . // `deref`, which creates an intermediate reference. 117,489,086 ( 0.10%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns an unsafe mutable pointer to the vector's buffer. . /// -- line 1142 ---------------------------------------- -- line 1162 ---------------------------------------- . /// } . /// assert_eq!(&*x, &[0, 1, 2, 3]); . /// ``` . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_mut_ptr(&mut self) -> *mut T { . // We shadow the slice method of the same name to avoid going through . // `deref_mut`, which creates an intermediate reference. 75,577,342 ( 0.06%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] -- line 1178 ---------------------------------------- -- line 1259 ---------------------------------------- . /// . /// Normally, here, one would use [`clear`] instead to correctly drop . /// the contents and thus not leak memory. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub unsafe fn set_len(&mut self, new_len: usize) { . debug_assert!(new_len <= self.capacity()); . 18,365,980 ( 0.02%) self.len = new_len; 1,009,088 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1305 ---------------------------------------- . assert_failed(index, len); . } . unsafe { . // We replace self[index] with the last element. Note that if the . // bounds check above succeeds there must be a last element (which . // can be self[index] itself). . let value = ptr::read(self.as_ptr().add(index)); . let base_ptr = self.as_mut_ptr(); 7,733 ( 0.00%) ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); . self.set_len(len - 1); . value . } . } . . /// Inserts an element at position `index` within the vector, shifting all . /// elements after it to the right. . /// -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 146,055 ( 0.00%) pub fn insert(&mut self, index: usize, element: T) { . #[cold] . #[inline(never)] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("insertion index (is {}) should be <= len (is {})", index, len); . } . 21,446 ( 0.00%) let len = self.len(); 46,218 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 56,120 ( 0.00%) if len == self.buf.capacity() { . self.reserve(1); . } . . unsafe { . // infallible . // The spot to put the new value . { . let p = self.as_mut_ptr().add(index); . // Shift everything over to make space. (Duplicating the . // `index`th element into two consecutive places.) 82,437 ( 0.00%) ptr::copy(p, p.offset(1), len - index); . // Write it in, overwriting the first copy of the `index`th . // element. . ptr::write(p, element); . } 56,120 ( 0.00%) self.set_len(len + 1); . } 125,190 ( 0.00%) } . . /// Removes and returns the element at position `index` within the vector, . /// shifting all elements after it to the left. . /// . /// Note: Because this shifts over the remaining elements, it has a . /// worst-case performance of *O*(*n*). If you don't need the order of elements . /// to be preserved, use [`swap_remove`] instead. If you'd like to remove . /// elements from the beginning of the `Vec`, consider using -- line 1376 ---------------------------------------- -- line 1395 ---------------------------------------- . pub fn remove(&mut self, index: usize) -> T { . #[cold] . #[inline(never)] . #[track_caller] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("removal index (is {}) should be < len (is {})", index, len); . } . 1,553 ( 0.00%) let len = self.len(); 5,693 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. . let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 8,304 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 3,391 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 2,127 ( 0.00%) self.set_len(len - 1); . ret . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the -- line 1428 ---------------------------------------- -- line 1442 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3, 4, 5]; . /// let keep = [false, true, true, false, true]; . /// let mut iter = keep.iter(); . /// vec.retain(|_| *iter.next().unwrap()); . /// assert_eq!(vec, [2, 3, 5]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 5,269,188 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 207,456 ( 0.00%) self.retain_mut(|elem| f(elem)); 5,122,112 ( 0.00%) } . . /// Retains only the elements specified by the predicate, passing a mutable reference to it. . /// . /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1463 ---------------------------------------- -- line 1474 ---------------------------------------- . /// }); . /// assert_eq!(vec, [2, 3, 4]); . /// ``` . #[unstable(feature = "vec_retain_mut", issue = "90829")] . pub fn retain_mut(&mut self, mut f: F) . where . F: FnMut(&mut T) -> bool, . { 648,855 ( 0.00%) let original_len = self.len(); . // Avoid double drop if the drop guard is not executed, . // since we may make some holes during the process. . unsafe { self.set_len(0) }; . . // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] . // |<- processed len ->| ^- next to check . // |<- deleted cnt ->| . // |<- original_len ->| -- line 1490 ---------------------------------------- -- line 1499 ---------------------------------------- . v: &'a mut Vec, . processed_len: usize, . deleted_cnt: usize, . original_len: usize, . } . . impl Drop for BackshiftOnDrop<'_, T, A> { . fn drop(&mut self) { 589,306 ( 0.00%) if self.deleted_cnt > 0 { . // SAFETY: Trailing unchecked items must be valid since we never touch them. . unsafe { . ptr::copy( . self.v.as_ptr().add(self.processed_len), 491,188 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 8,318,281 ( 0.01%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 2,966,160 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 419,554 ( 0.00%) g.processed_len += 1; 241,282 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 3,356 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 342,636 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 305,006 ( 0.00%) g.processed_len += 1; . } . } . . // Stage 1: Nothing was deleted. . process_loop::(original_len, &mut f, &mut g); . . // Stage 2: Some elements were deleted. . process_loop::(original_len, &mut f, &mut g); -- line 1565 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 36,547 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 24,500 ( 0.00%) let len = self.len(); 71,634 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 198,586 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 34,522 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 104,902 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 41,768 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1717 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2]; . /// vec.push(3); . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 12,935 ( 0.00%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 103,553,337 ( 0.09%) if self.len == self.buf.capacity() { 7,068,390 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 3,233,225 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 145,057,460 ( 0.12%) self.len += 1; . } 10,348 ( 0.00%) } . . /// Removes the last element from a vector and returns it, or [`None`] if it . /// is empty. . /// . /// If you'd like to pop the first element, consider using . /// [`VecDeque::pop_front`] instead. . /// . /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front -- line 1744 ---------------------------------------- -- line 1748 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3]; . /// assert_eq!(vec.pop(), Some(3)); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop(&mut self) -> Option { 28,570,447 ( 0.02%) if self.len == 0 { 382 ( 0.00%) None . } else { . unsafe { 40,193,345 ( 0.03%) self.len -= 1; 2,901,524 ( 0.00%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 17,486 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 14,988 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] . unsafe fn append_elements(&mut self, other: *const [T]) { . let count = unsafe { (*other).len() }; . self.reserve(count); 343,834 ( 0.00%) let len = self.len(); 8 ( 0.00%) unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 34,638,629 ( 0.03%) self.len += count; . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is -- line 1807 ---------------------------------------- -- line 1834 ---------------------------------------- . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 292,116 ( 0.00%) let len = self.len(); . let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked . self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 5,767 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 144,733 ( 0.00%) Drain { . tail_start: end, 3,868 ( 0.00%) tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Clears the vector, removing all values. . /// -- line 1861 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 5,141,176 ( 0.00%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` -- line 1885 ---------------------------------------- -- line 1900 ---------------------------------------- . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 5,864,005 ( 0.01%) self.len() == 0 . } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// -- line 1916 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 22,240 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 16,718 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 398,353 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 53,935 ( 0.00%) let len = self.len(); 107,870 ( 0.00%) if new_len > len { 395,408 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 344,418 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 6 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 477 ( 0.00%) self.buf.capacity() - self.len, . ) . } . } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data -- line 2087 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 481,550 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 48,155 ( 0.00%) let len = self.len(); . 144,465 ( 0.00%) if new_len > len { 92,487 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 61,907 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 25,837 ( 0.00%) self.0.clone() . } . fn last(self) -> T { . self.0 . } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { -- line 2287 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 3,898,102 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 92,974 ( 0.00%) let mut ptr = self.as_mut_ptr().add(self.len()); . // Use SetLenOnDrop to work around bug where compiler . // might not realize the store through `ptr` through self.set_len() . // don't alias. . let mut local_len = SetLenOnDrop::new(&mut self.len); . . // Write all elements except the last one . for _ in 1..n { . ptr::write(ptr, value.next()); . ptr = ptr.offset(1); . // Increment the length in every step in case next() panics . local_len.increment_len(1); . } . 3,929,860 ( 0.00%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 3,097,261 ( 0.00%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 5,222 ( 0.00%) self.dedup_by(|a, b| a == b) . } . } . . //////////////////////////////////////////////////////////////////////////////// . // Internal methods and functions . //////////////////////////////////////////////////////////////////////////////// . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 759,369 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 4,553,052 ( 0.00%) ::from_elem(elem, n, Global) 920,704 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2424 ---------------------------------------- . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . . fn deref(&self) -> &[T] { 145,060,660 ( 0.12%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 937 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 42,338,567 ( 0.04%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } . } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . -- line 2447 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 6,206,069 ( 0.01%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 8,174,312 ( 0.01%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2518 ---------------------------------------- . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] . fn index(&self, index: I) -> &Self::Output { 2,103,933 ( 0.00%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] . fn index_mut(&mut self, index: I) -> &mut Self::Output { 11,196 ( 0.00%) IndexMut::index_mut(&mut **self, index) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 30,205,684 ( 0.03%) >::from_iter(iter.into_iter()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . -- line 2555 ---------------------------------------- -- line 2564 ---------------------------------------- . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { . unsafe { 31,886,814 ( 0.03%) let mut me = ManuallyDrop::new(self); . let alloc = ptr::read(me.allocator()); . let begin = me.as_mut_ptr(); . let end = if mem::size_of::() == 0 { . arith_offset(begin as *const i8, me.len() as isize) as *const T . } else { . begin.add(me.len()) as *const T . }; . let cap = me.buf.capacity(); 61,496,272 ( 0.05%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2591 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . . fn into_iter(self) -> slice::Iter<'a, T> { 873 ( 0.00%) self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . . fn into_iter(self) -> slice::IterMut<'a, T> { 1,316 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 294,408 ( 0.00%) fn extend>(&mut self, iter: I) { 24,184,048 ( 0.02%) >::spec_extend(self, iter.into_iter()) 294,408 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 35,145,307 ( 0.03%) while let Some(element) = iterator.next() { 638,950 ( 0.00%) let len = self.len(); 20,965,827 ( 0.02%) if len == self.capacity() { 30,411 ( 0.00%) let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 23,367,260 ( 0.02%) self.set_len(len + 1); . } . } 82,893 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 21,912 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 88,671 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 552,640 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// . /// [`copy_from_slice`]: slice::copy_from_slice . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "extend_ref", since = "1.2.0")] . impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec { 376 ( 0.00%) fn extend>(&mut self, iter: I) { . self.spec_extend(iter.into_iter()) 282 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, &item: &'a T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2783 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 65,988,560 ( 0.06%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 16,030,913 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 78,934,330 ( 0.07%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 30,324,898 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/stack.rs -------------------------------------------------------------------------------- Ir -- line 7 ---------------------------------------- . // on. This flag has performance relevant characteristics. Don't set it too high. . const STACK_PER_RECURSION: usize = 1 * 1024 * 1024; // 1MB . . /// Grows the stack on demand to prevent stack overflow. Call this in strategic locations . /// to "break up" recursive calls. E.g. almost any call to `visit_expr` or equivalent can benefit . /// from this. . /// . /// Should not be sprinkled around carelessly, as it causes a little bit of overhead. 92,250,134 ( 0.08%) pub fn ensure_sufficient_stack(f: impl FnOnce() -> R) -> R { 66,913,457 ( 0.06%) stacker::maybe_grow(RED_ZONE, STACK_PER_RECURSION, f) 102,519,625 ( 0.09%) } 246,255 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/structural_impls.rs -------------------------------------------------------------------------------- Ir -- line 685 ---------------------------------------- . } . } . . impl<'tcx, T: TypeFoldable<'tcx>, U: TypeFoldable<'tcx>> TypeFoldable<'tcx> for (T, U) { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result<(T, U), F::Error> { 76,388 ( 0.00%) Ok((self.0.try_fold_with(folder)?, self.1.try_fold_with(folder)?)) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 182 ( 0.00%) self.0.visit_with(visitor)?; 286 ( 0.00%) self.1.visit_with(visitor) . } . } . . impl<'tcx, A: TypeFoldable<'tcx>, B: TypeFoldable<'tcx>, C: TypeFoldable<'tcx>> TypeFoldable<'tcx> . for (A, B, C) . { . fn try_super_fold_with>( . self, -- line 706 ---------------------------------------- -- line 826 ---------------------------------------- . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . self.try_map_id(|value| value.try_fold_with(folder)) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 40,864 ( 0.00%) (**self).visit_with(visitor) . } . } . . impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Vec { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 721,265 ( 0.00%) self.try_map_id(|t| t.try_fold_with(folder)) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 45,312 ( 0.00%) self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for Box<[T]> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { -- line 855 ---------------------------------------- -- line 857 ---------------------------------------- . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . impl<'tcx, T: TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder<'tcx, T> { 1,715,270 ( 0.00%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 500,937,704 ( 0.43%) self.try_map_bound(|ty| ty.try_fold_with(folder)) 2,142,967 ( 0.00%) } . . fn try_fold_with>(self, folder: &mut F) -> Result { 181,045,898 ( 0.16%) folder.try_fold_binder(self) . } . 8,964 ( 0.00%) fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 50,005 ( 0.00%) self.as_ref().skip_binder().visit_with(visitor) 7,968 ( 0.00%) } . . fn visit_with>(&self, visitor: &mut V) -> ControlFlow { . visitor.visit_binder(self) . } . } . . impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List>> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 23,828 ( 0.00%) ty::util::fold_list(self, folder, |tcx, v| tcx.intern_poly_existential_predicates(v)) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . self.iter().try_for_each(|p| p.visit_with(visitor)) . } . } . . impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 760,103 ( 0.00%) ty::util::fold_list(self, folder, |tcx, v| tcx.intern_type_list(v)) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List { -- line 911 ---------------------------------------- -- line 949 ---------------------------------------- . } . }, . }) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . use crate::ty::InstanceDef::*; . self.substs.visit_with(visitor)?; 100,284,455 ( 0.09%) match self.def { . Item(def) => def.visit_with(visitor), . VtableShim(did) | ReifyShim(did) | Intrinsic(did) | Virtual(did, _) => { . did.visit_with(visitor) . } . FnPtrShim(did, ty) | CloneShim(did, ty) => { . did.visit_with(visitor)?; . ty.visit_with(visitor) . } 6 ( 0.00%) DropGlue(did, ty) => { . did.visit_with(visitor)?; . ty.visit_with(visitor) . } . ClosureOnceShim { call_once, track_caller: _ } => call_once.visit_with(visitor), . } . } . } . -- line 974 ---------------------------------------- -- line 976 ---------------------------------------- . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . Ok(Self { instance: self.instance.try_fold_with(folder)?, promoted: self.promoted }) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 50,142,084 ( 0.04%) self.instance.visit_with(visitor) . } . } . . impl<'tcx> TypeFoldable<'tcx> for Ty<'tcx> { 1,330,034 ( 0.00%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 91,057,372 ( 0.08%) let kind = match *self.kind() { 70,086 ( 0.00%) ty::RawPtr(tm) => ty::RawPtr(tm.try_fold_with(folder)?), 567,307 ( 0.00%) ty::Array(typ, sz) => ty::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?), 143,282 ( 0.00%) ty::Slice(typ) => ty::Slice(typ.try_fold_with(folder)?), 81,262,276 ( 0.07%) ty::Adt(tid, substs) => ty::Adt(tid, substs.try_fold_with(folder)?), 18,730 ( 0.00%) ty::Dynamic(trait_ty, region) => { 36,962 ( 0.00%) ty::Dynamic(trait_ty.try_fold_with(folder)?, region.try_fold_with(folder)?) . } 631,310 ( 0.00%) ty::Tuple(ts) => ty::Tuple(ts.try_fold_with(folder)?), 666,838 ( 0.00%) ty::FnDef(def_id, substs) => ty::FnDef(def_id, substs.try_fold_with(folder)?), 186,132 ( 0.00%) ty::FnPtr(f) => ty::FnPtr(f.try_fold_with(folder)?), 3,828,021 ( 0.00%) ty::Ref(r, ty, mutbl) => { 6,300,605 ( 0.01%) ty::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl) . } . ty::Generator(did, substs, movability) => { . ty::Generator(did, substs.try_fold_with(folder)?, movability) . } . ty::GeneratorWitness(types) => ty::GeneratorWitness(types.try_fold_with(folder)?), 92,726 ( 0.00%) ty::Closure(did, substs) => ty::Closure(did, substs.try_fold_with(folder)?), 4,623,620 ( 0.00%) ty::Projection(data) => ty::Projection(data.try_fold_with(folder)?), . ty::Opaque(did, substs) => ty::Opaque(did, substs.try_fold_with(folder)?), . . ty::Bool . | ty::Char . | ty::Str . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) -- line 1020 ---------------------------------------- -- line 1022 ---------------------------------------- . | ty::Infer(_) . | ty::Param(..) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Never . | ty::Foreign(..) => return Ok(self), . }; . 60,654,752 ( 0.05%) Ok(if *self.kind() == kind { self } else { folder.tcx().mk_ty(kind) }) 1,875,522 ( 0.00%) } . . fn try_fold_with>(self, folder: &mut F) -> Result { 6,147,142 ( 0.01%) folder.try_fold_ty(self) . } . 11,233,962 ( 0.01%) fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 10,911,899 ( 0.01%) match self.kind() { . ty::RawPtr(ref tm) => tm.visit_with(visitor), 9,745 ( 0.00%) ty::Array(typ, sz) => { 23,364 ( 0.00%) typ.visit_with(visitor)?; 87,705 ( 0.00%) sz.visit_with(visitor) . } . ty::Slice(typ) => typ.visit_with(visitor), . ty::Adt(_, substs) => substs.visit_with(visitor), 498 ( 0.00%) ty::Dynamic(ref trait_ty, ref reg) => { . trait_ty.visit_with(visitor)?; 4,980 ( 0.00%) reg.visit_with(visitor) . } . ty::Tuple(ts) => ts.visit_with(visitor), . ty::FnDef(_, substs) => substs.visit_with(visitor), . ty::FnPtr(ref f) => f.visit_with(visitor), . ty::Ref(r, ty, _) => { 129,928 ( 0.00%) r.visit_with(visitor)?; . ty.visit_with(visitor) . } . ty::Generator(_did, ref substs, _) => substs.visit_with(visitor), . ty::GeneratorWitness(ref types) => types.visit_with(visitor), . ty::Closure(_did, ref substs) => substs.visit_with(visitor), 1,940 ( 0.00%) ty::Projection(ref data) => data.visit_with(visitor), . ty::Opaque(_, ref substs) => substs.visit_with(visitor), . . ty::Bool . | ty::Char . | ty::Str . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) -- line 1068 ---------------------------------------- -- line 1069 ---------------------------------------- . | ty::Error(_) . | ty::Infer(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Param(..) . | ty::Never . | ty::Foreign(..) => ControlFlow::CONTINUE, . } 10,598,205 ( 0.01%) } . . fn visit_with>(&self, visitor: &mut V) -> ControlFlow { 70,038,118 ( 0.06%) visitor.visit_ty(self) . } . } . . impl<'tcx> TypeFoldable<'tcx> for ty::Region<'tcx> { . fn try_super_fold_with>( . self, . _folder: &mut F, . ) -> Result { . Ok(self) . } . . fn try_fold_with>(self, folder: &mut F) -> Result { 296,972 ( 0.00%) folder.try_fold_region(self) . } . . fn super_visit_with>(&self, _visitor: &mut V) -> ControlFlow { . ControlFlow::CONTINUE . } . 498 ( 0.00%) fn visit_with>(&self, visitor: &mut V) -> ControlFlow { 367,217 ( 0.00%) visitor.visit_region(*self) 1,494 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for ty::Predicate<'tcx> { 2,560,626 ( 0.00%) fn try_fold_with>(self, folder: &mut F) -> Result { . folder.try_fold_predicate(self) 2,133,855 ( 0.00%) } . . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 170,832,166 ( 0.15%) let new = self.inner.kind.try_fold_with(folder)?; 622,479,276 ( 0.53%) Ok(folder.tcx().reuse_or_mk_predicate(self, new)) 1,280,313 ( 0.00%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . self.inner.kind.visit_with(visitor) . } . . fn visit_with>(&self, visitor: &mut V) -> ControlFlow { 3,907,195 ( 0.00%) visitor.visit_predicate(*self) . } . . fn has_vars_bound_at_or_above(&self, binder: ty::DebruijnIndex) -> bool { 1,099,028 ( 0.00%) self.inner.outer_exclusive_binder > binder 1,099,028 ( 0.00%) } . . fn has_type_flags(&self, flags: ty::TypeFlags) -> bool { 3,717,940 ( 0.00%) self.inner.flags.intersects(flags) 3,717,940 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 2,799,438 ( 0.00%) ty::util::fold_list(self, folder, |tcx, v| tcx.intern_predicates(v)) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 10,544 ( 0.00%) self.iter().try_for_each(|p| p.visit_with(visitor)) . } . } . . impl<'tcx, T: TypeFoldable<'tcx>, I: Idx> TypeFoldable<'tcx> for IndexVec { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { -- line 1152 ---------------------------------------- -- line 1154 ---------------------------------------- . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::Const<'tcx> { 41,094 ( 0.00%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 10,753,704 ( 0.01%) let ty = self.ty.try_fold_with(folder)?; 179,323,251 ( 0.15%) let val = self.val.try_fold_with(folder)?; 53,147,655 ( 0.05%) if ty != self.ty || val != self.val { 68,686 ( 0.00%) Ok(folder.tcx().mk_const(ty::Const { ty, val })) . } else { . Ok(self) . } 49,470 ( 0.00%) } . 85,302 ( 0.00%) fn try_fold_with>(self, folder: &mut F) -> Result { 394,733 ( 0.00%) folder.try_fold_const(self) 85,302 ( 0.00%) } . 7,988 ( 0.00%) fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 170,807 ( 0.00%) self.ty.visit_with(visitor)?; . self.val.visit_with(visitor) 10,268 ( 0.00%) } . 64,366 ( 0.00%) fn visit_with>(&self, visitor: &mut V) -> ControlFlow { 96,417 ( 0.00%) visitor.visit_const(self) 74,848 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for ty::ConstKind<'tcx> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { 24,974,150 ( 0.02%) Ok(match self { . ty::ConstKind::Infer(ic) => ty::ConstKind::Infer(ic.try_fold_with(folder)?), 1,232 ( 0.00%) ty::ConstKind::Param(p) => ty::ConstKind::Param(p.try_fold_with(folder)?), 10,034,181 ( 0.01%) ty::ConstKind::Unevaluated(uv) => ty::ConstKind::Unevaluated(uv.try_fold_with(folder)?), . ty::ConstKind::Value(_) . | ty::ConstKind::Bound(..) . | ty::ConstKind::Placeholder(..) 971,158 ( 0.00%) | ty::ConstKind::Error(_) => self, . }) . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 351,429 ( 0.00%) match *self { . ty::ConstKind::Infer(ic) => ic.visit_with(visitor), . ty::ConstKind::Param(p) => p.visit_with(visitor), . ty::ConstKind::Unevaluated(uv) => uv.visit_with(visitor), . ty::ConstKind::Value(_) . | ty::ConstKind::Bound(..) . | ty::ConstKind::Placeholder(_) . | ty::ConstKind::Error(_) => ControlFlow::CONTINUE, . } -- line 1214 ---------------------------------------- -- line 1230 ---------------------------------------- . . impl<'tcx> TypeFoldable<'tcx> for ty::Unevaluated<'tcx> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . Ok(ty::Unevaluated { . def: self.def, 23,891 ( 0.00%) substs: self.substs.try_fold_with(folder)?, . promoted: self.promoted, . }) . } . . fn visit_with>(&self, visitor: &mut V) -> ControlFlow { 4,472 ( 0.00%) visitor.visit_unevaluated_const(*self) . } . 912 ( 0.00%) fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 2,853 ( 0.00%) self.substs.visit_with(visitor) 1,064 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for ty::Unevaluated<'tcx, ()> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . Ok(ty::Unevaluated { -- line 1257 ---------------------------------------- 61,929,959 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . pub struct BitMask(pub BitMaskWord); . . #[allow(clippy::use_self)] . impl BitMask { . /// Returns a new `BitMask` with all bits inverted. . #[inline] . #[must_use] . pub fn invert(self) -> Self { 1,260,057 ( 0.00%) BitMask(self.0 ^ BITMASK_MASK) . } . . /// Flip the bit in the mask for the entry at the given index. . /// . /// Returns the bit's previous state. . #[inline] . #[allow(clippy::cast_ptr_alignment)] . #[cfg(feature = "raw")] -- line 33 ---------------------------------------- -- line 38 ---------------------------------------- . // The bit was set if the bit is now 0. . self.0 & mask == 0 . } . . /// Returns a new `BitMask` with the lowest bit removed. . #[inline] . #[must_use] . pub fn remove_lowest_bit(self) -> Self { 1,131,168 ( 0.00%) BitMask(self.0 & (self.0 - 1)) . } . /// Returns whether the `BitMask` has at least one set bit. . #[inline] . pub fn any_bit_set(self) -> bool { 18,314,472 ( 0.02%) self.0 != 0 . } . . /// Returns the first set bit in the `BitMask`, if there is one. . #[inline] . pub fn lowest_set_bit(self) -> Option { 1,029,198,860 ( 0.88%) if self.0 == 0 { . None . } else { . Some(unsafe { self.lowest_set_bit_nonzero() }) . } . } . . /// Returns the first set bit in the `BitMask`, if there is one. The . /// bitmask must not be empty. . #[inline] . #[cfg(feature = "nightly")] . pub unsafe fn lowest_set_bit_nonzero(self) -> usize { 379,523 ( 0.00%) intrinsics::cttz_nonzero(self.0) as usize / BITMASK_STRIDE . } . #[inline] . #[cfg(not(feature = "nightly"))] . pub unsafe fn lowest_set_bit_nonzero(self) -> usize { . self.trailing_zeros() . } . . /// Returns the number of trailing zeroes in the `BitMask`. -- line 77 ---------------------------------------- -- line 110 ---------------------------------------- . /// bits. . pub struct BitMaskIter(BitMask); . . impl Iterator for BitMaskIter { . type Item = usize; . . #[inline] . fn next(&mut self) -> Option { 348,094,513 ( 0.30%) let bit = self.0.lowest_set_bit()?; . self.0 = self.0.remove_lowest_bit(); . Some(bit) . } . } 4,855,990 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/fast_reject.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . pub type SimplifiedType = SimplifiedTypeGen; . . /// See `simplify_type` . /// . /// Note that we keep this type generic over the type of identifier it uses . /// because we sometimes need to use SimplifiedTypeGen values as stable sorting . /// keys (in which case we use a DefPathHash as id-type) but in the general case . /// the non-stable but fast to construct DefId-version is the better choice. 56,497,346 ( 0.05%) #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)] . pub enum SimplifiedTypeGen . where . D: Copy + Debug + Eq, . { . BoolSimplifiedType, . CharSimplifiedType, . IntSimplifiedType(ty::IntTy), . UintSimplifiedType(ty::UintTy), -- line 28 ---------------------------------------- -- line 78 ---------------------------------------- . /// . /// ¹ meaning that if two outermost layers are different, then the whole types are also different. . /// ² FIXME(@lcnr): this seems like it can actually end up being unsound with the way it's used during . /// candidate selection. We do not consider non blanket impls for `<_ as Trait>::Assoc` even . /// though `_` can be inferred to a concrete type later at which point a concrete impl . /// could actually apply. After experimenting for about an hour I wasn't able to cause any issues . /// this way so I am not going to change this until we actually find an issue as I am really . /// interesting in getting an actual test for this. 91,534,328 ( 0.08%) pub fn simplify_type( . tcx: TyCtxt<'_>, . ty: Ty<'_>, . can_simplify_params: SimplifyParams, . strip_references: StripReferences, . ) -> Option { 137,301,492 ( 0.12%) match *ty.kind() { . ty::Bool => Some(BoolSimplifiedType), . ty::Char => Some(CharSimplifiedType), 102,532 ( 0.00%) ty::Int(int_type) => Some(IntSimplifiedType(int_type)), 219,728 ( 0.00%) ty::Uint(uint_type) => Some(UintSimplifiedType(uint_type)), 47,268 ( 0.00%) ty::Float(float_type) => Some(FloatSimplifiedType(float_type)), 207,916,220 ( 0.18%) ty::Adt(def, _) => Some(AdtSimplifiedType(def.did)), . ty::Str => Some(StrSimplifiedType), . ty::Array(..) => Some(ArraySimplifiedType), . ty::Slice(..) => Some(SliceSimplifiedType), 25,176 ( 0.00%) ty::RawPtr(ptr) => Some(PtrSimplifiedType(ptr.mutbl)), 24 ( 0.00%) ty::Dynamic(ref trait_info, ..) => match trait_info.principal_def_id() { 30 ( 0.00%) Some(principal_def_id) if !tcx.trait_is_auto(principal_def_id) => { 54 ( 0.00%) Some(TraitSimplifiedType(principal_def_id)) . } . _ => Some(MarkerTraitObjectSimplifiedType), . }, 4,828,808 ( 0.00%) ty::Ref(_, ty, mutbl) => { 2,414,404 ( 0.00%) if strip_references == StripReferences::Yes { . // For diagnostics, when recommending similar impls we want to . // recommend impls even when there is a reference mismatch, . // so we treat &T and T equivalently in that case. . simplify_type(tcx, ty, can_simplify_params, strip_references) . } else { . Some(RefSimplifiedType(mutbl)) . } . } 7,049 ( 0.00%) ty::FnDef(def_id, _) | ty::Closure(def_id, _) => Some(ClosureSimplifiedType(def_id)), . ty::Generator(def_id, _, _) => Some(GeneratorSimplifiedType(def_id)), . ty::GeneratorWitness(ref tys) => { . Some(GeneratorWitnessSimplifiedType(tys.skip_binder().len())) . } . ty::Never => Some(NeverSimplifiedType), 497,496 ( 0.00%) ty::Tuple(ref tys) => Some(TupleSimplifiedType(tys.len())), 13,224 ( 0.00%) ty::FnPtr(ref f) => Some(FunctionSimplifiedType(f.skip_binder().inputs().len())), . ty::Projection(_) | ty::Param(_) => { 1,551,681 ( 0.00%) if can_simplify_params == SimplifyParams::Yes { . // In normalized types, projections don't unify with . // anything. when lazy normalization happens, this . // will change. It would still be nice to have a way . // to deal with known-not-to-unify-with-anything . // projections (e.g., the likes of <__S as Encoder>::Error). . Some(ParameterSimplifiedType) . } else { . None . } . } . ty::Opaque(def_id, _) => Some(OpaqueSimplifiedType(def_id)), . ty::Foreign(def_id) => Some(ForeignSimplifiedType(def_id)), . ty::Placeholder(..) | ty::Bound(..) | ty::Infer(_) | ty::Error(_) => None, . } 205,952,238 ( 0.18%) } . . impl SimplifiedTypeGen { . pub fn def(self) -> Option { . match self { . AdtSimplifiedType(d) . | ForeignSimplifiedType(d) . | TraitSimplifiedType(d) . | ClosureSimplifiedType(d) -- line 151 ---------------------------------------- 174,827,389 ( 0.15%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs -------------------------------------------------------------------------------- Ir -- line 208 ---------------------------------------- . /// There is no built-in impl. There may be some other . /// candidate (a where-clause or user-defined impl). . None, . /// It is unknown whether there is an impl. . Ambiguous, . } . . impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { 1,579,812 ( 0.00%) pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> { 19,576,818 ( 0.02%) SelectionContext { . infcx, 3,183,731 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode: TraitQueryMode::Standard, . } 1,316,510 ( 0.00%) } . 4,770 ( 0.00%) pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> { 841,248 ( 0.00%) SelectionContext { . infcx, 104,361 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: true, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode: TraitQueryMode::Standard, . } 3,975 ( 0.00%) } . . pub fn with_negative( . infcx: &'cx InferCtxt<'cx, 'tcx>, . allow_negative_impls: bool, . ) -> SelectionContext<'cx, 'tcx> { . debug!(?allow_negative_impls, "with_negative"); . SelectionContext { . infcx, -- line 244 ---------------------------------------- -- line 245 ---------------------------------------- . freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls, . query_mode: TraitQueryMode::Standard, . } . } . 309,296 ( 0.00%) pub fn with_query_mode( . infcx: &'cx InferCtxt<'cx, 'tcx>, . query_mode: TraitQueryMode, . ) -> SelectionContext<'cx, 'tcx> { . debug!(?query_mode, "with_query_mode"); 618,592 ( 0.00%) SelectionContext { . infcx, 38,662 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode, . } 231,972 ( 0.00%) } . . /// Enables tracking of intercrate ambiguity causes. These are . /// used in coherence to give improved diagnostics. We don't do . /// this until we detect a coherence error because it can lead to . /// false overflow results (#47139) and because it costs . /// computation time. . pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) { . assert!(self.intercrate); -- line 274 ---------------------------------------- -- line 281 ---------------------------------------- . /// was enabled and disables tracking at the same time. If . /// tracking is not enabled, just returns an empty vector. . pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec { . assert!(self.intercrate); . self.intercrate_ambiguity_causes.take().unwrap_or_default() . } . . pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> { 42,510,170 ( 0.04%) self.infcx 219,817 ( 0.00%) } . . pub fn tcx(&self) -> TyCtxt<'tcx> { 182,189,395 ( 0.16%) self.infcx.tcx . } . . pub fn is_intercrate(&self) -> bool { 3,560,774 ( 0.00%) self.intercrate . } . . /////////////////////////////////////////////////////////////////////////// . // Selection . // . // The selection phase tries to identify *how* an obligation will . // be resolved. For example, it will identify which impl or . // parameter bound is to be used. The process can be inconclusive -- line 305 ---------------------------------------- -- line 309 ---------------------------------------- . // 1. If no applicable impl or parameter bound can be found. . // 2. If the output type parameters in the obligation do not match . // those specified by the impl/bound. For example, if the obligation . // is `Vec: Iterable`, but the impl specifies . // `impl Iterable for Vec`, than an error would result. . . /// Attempts to satisfy the obligation. If successful, this will affect the surrounding . /// type environment by performing unification. 4,197,235 ( 0.00%) #[instrument(level = "debug", skip(self))] 5,396,445 ( 0.00%) pub fn select( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, Selection<'tcx>> { 4,331,333 ( 0.00%) let candidate = match self.select_from_obligation(obligation) { . Err(SelectionError::Overflow) => { . // In standard mode, overflow must have been caught and reported . // earlier. . assert!(self.query_mode == TraitQueryMode::Canonical); . return Err(SelectionError::Overflow); . } . Err(SelectionError::Ambiguous(_)) => { . return Ok(None); . } . Err(e) => { 459,662 ( 0.00%) return Err(e); . } . Ok(None) => { 271,710 ( 0.00%) return Ok(None); . } 2,651,916 ( 0.00%) Ok(Some(candidate)) => candidate, . }; . 4,423,636 ( 0.00%) match self.confirm_candidate(obligation, candidate) { . Err(SelectionError::Overflow) => { . assert!(self.query_mode == TraitQueryMode::Canonical); . Err(SelectionError::Overflow) . } 24,544 ( 0.00%) Err(e) => Err(e), . Ok(candidate) => { . debug!(?candidate, "confirmed"); 5,281,176 ( 0.00%) Ok(Some(candidate)) . } . } . } . 5,996,050 ( 0.01%) crate fn select_from_obligation( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . debug_assert!(!obligation.predicate.has_escaping_bound_vars()); . . let pec = &ProvisionalEvaluationCache::default(); . let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation); . 1,199,210 ( 0.00%) self.candidate_from_obligation(&stack) 5,396,445 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // EVALUATION . // . // Tests whether an obligation can be selected or whether an impl . // can be applied to particular types. It skips the "confirmation" . // step and hence completely ignores output type parameters. . // -- line 372 ---------------------------------------- -- line 374 ---------------------------------------- . // we can be sure it does not. . . /// Evaluates whether the obligation `obligation` can be satisfied (by any means). . pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool { . debug!(?obligation, "predicate_may_hold_fatal"); . . // This fatal query is a stopgap that should only be used in standard mode, . // where we do not expect overflow to be propagated. 1,091 ( 0.00%) assert!(self.query_mode == TraitQueryMode::Standard); . 5,455 ( 0.00%) self.evaluate_root_obligation(obligation) . .expect("Overflow should be caught earlier in standard query mode") . .may_apply() . } . . /// Evaluates whether the obligation `obligation` can be satisfied . /// and returns an `EvaluationResult`. This is meant for the . /// *initial* call. 77,324 ( 0.00%) pub fn evaluate_root_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . ) -> Result { . self.evaluation_probe(|this| { 119,259 ( 0.00%) this.evaluate_predicate_recursively( . TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), . obligation.clone(), . ) . }) 77,324 ( 0.00%) } . . fn evaluation_probe( . &mut self, . op: impl FnOnce(&mut Self) -> Result, . ) -> Result { 31,504,413 ( 0.03%) self.infcx.probe(|snapshot| -> Result { 79,506 ( 0.00%) let result = op(self)?; . 24,786,181 ( 0.02%) match self.infcx.leak_check(true, snapshot) { . Ok(()) => {} . Err(_) => return Ok(EvaluatedToErr), . } . 17,704,415 ( 0.02%) match self.infcx.region_constraints_added_in_snapshot(snapshot) { . None => Ok(result), . Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)), . } . }) . } . . /// Evaluates the predicates in `predicates` recursively. Note that . /// this applies projections in the predicates, and therefore . /// is run within an inference probe. 66,542,200 ( 0.06%) #[instrument(skip(self, stack), level = "debug")] . fn evaluate_predicates_recursively<'o, I>( . &mut self, . stack: TraitObligationStackList<'o, 'tcx>, . predicates: I, . ) -> Result . where . I: IntoIterator> + std::fmt::Debug, . { . let mut result = EvaluatedToOk; 14,651,991 ( 0.01%) for obligation in predicates { 467,184 ( 0.00%) let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?; 233,592 ( 0.00%) if let EvaluatedToErr = eval { . // fast-path - EvaluatedToErr is the top of the lattice, . // so we don't need to look on the other predicates. . return Ok(EvaluatedToErr); . } else { . result = cmp::max(result, eval); . } . } . Ok(result) . } . 1,565,490 ( 0.00%) #[instrument( . level = "debug", . skip(self, previous_stack), . fields(previous_stack = ?previous_stack.head()) 1,408,941 ( 0.00%) )] . fn evaluate_predicate_recursively<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . obligation: PredicateObligation<'tcx>, . ) -> Result { . // `previous_stack` stores a `TraitObligation`, while `obligation` is . // a `PredicateObligation`. These are distinct types, so we can't . // use any `Option` combinator method that would force them to be . // the same. 313,098 ( 0.00%) match previous_stack.head() { 233,178 ( 0.00%) Some(h) => self.check_recursion_limit(&obligation, h.obligation)?, 39,960 ( 0.00%) None => self.check_recursion_limit(&obligation, &obligation)?, . } . 939,294 ( 0.00%) let result = ensure_sufficient_stack(|| { 156,549 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 1,565,490 ( 0.00%) match bound_predicate.skip_binder() { . ty::PredicateKind::Trait(t) => { . let t = bound_predicate.rebind(t); . debug_assert!(!t.has_escaping_bound_vars()); . let obligation = obligation.with(t); 2,147,235 ( 0.00%) self.evaluate_trait_predicate_recursively(previous_stack, obligation) . } . . ty::PredicateKind::Subtype(p) => { . let p = bound_predicate.rebind(p); . // Does this code ever run? 3,465 ( 0.00%) match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) { 4 ( 0.00%) Some(Ok(InferOk { mut obligations, .. })) => { . self.add_depth(obligations.iter_mut(), obligation.recursion_depth); . self.evaluate_predicates_recursively( . previous_stack, . obligations.into_iter(), . ) . } . Some(Err(_)) => Ok(EvaluatedToErr), . None => Ok(EvaluatedToAmbig), -- line 490 ---------------------------------------- -- line 522 ---------------------------------------- . None => Ok(EvaluatedToAmbig), . }, . . ty::PredicateKind::TypeOutlives(pred) => { . // A global type with no late-bound regions can only . // contain the "'static" lifetime (any other lifetime . // would either be late-bound or local), so it is guaranteed . // to outlive any other lifetime 8,081 ( 0.00%) if pred.0.is_global() && !pred.0.has_late_bound_regions() { . Ok(EvaluatedToOk) . } else { . Ok(EvaluatedToOkModuloRegions) . } . } . . ty::PredicateKind::RegionOutlives(..) => { . // We do not consider region relationships when evaluating trait matches. -- line 538 ---------------------------------------- -- line 545 ---------------------------------------- . } else { . Ok(EvaluatedToErr) . } . } . . ty::PredicateKind::Projection(data) => { . let data = bound_predicate.rebind(data); . let project_obligation = obligation.with(data); 48,642 ( 0.00%) match project::poly_project_and_unify_type(self, &project_obligation) { 9,500 ( 0.00%) Ok(Ok(Some(mut subobligations))) => { . 'compute_res: { . // If we've previously marked this projection as 'complete', thne . // use the final cached result (either `EvaluatedToOk` or . // `EvaluatedToOkModuloRegions`), and skip re-evaluating the . // sub-obligations. 7,600 ( 0.00%) if let Some(key) = 17,100 ( 0.00%) ProjectionCacheKey::from_poly_projection_predicate(self, data) . { 15,192 ( 0.00%) if let Some(cached_res) = self . .infcx . .inner . .borrow_mut() . .projection_cache() . .is_complete(key) . { . break 'compute_res Ok(cached_res); . } . } . 3,756 ( 0.00%) self.add_depth( . subobligations.iter_mut(), 3,756 ( 0.00%) obligation.recursion_depth, . ); 3,756 ( 0.00%) let res = self.evaluate_predicates_recursively( 5,634 ( 0.00%) previous_stack, 9,390 ( 0.00%) subobligations, . ); 7,512 ( 0.00%) if let Ok(res) = res { 3,756 ( 0.00%) if res == EvaluatedToOk || res == EvaluatedToOkModuloRegions { 6,796 ( 0.00%) if let Some(key) = 1,699 ( 0.00%) ProjectionCacheKey::from_poly_projection_predicate( 11,893 ( 0.00%) self, data, . ) . { . // If the result is something that we can cache, then mark this . // entry as 'complete'. This will allow us to skip evaluating the . // suboligations at all the next time we evaluate the projection . // predicate. 11,886 ( 0.00%) self.infcx . .inner . .borrow_mut() . .projection_cache() . .complete(key, res); . } . } . } . res -- line 601 ---------------------------------------- -- line 603 ---------------------------------------- . } . Ok(Ok(None)) => Ok(EvaluatedToAmbig), . Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur), . Err(_) => Ok(EvaluatedToErr), . } . } . . ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { 25 ( 0.00%) match self.infcx.closure_kind(closure_substs) { . Some(closure_kind) => { 15 ( 0.00%) if closure_kind.extends(kind) { . Ok(EvaluatedToOk) . } else { . Ok(EvaluatedToErr) . } . } . None => Ok(EvaluatedToAmbig), . } . } -- line 621 ---------------------------------------- -- line 693 ---------------------------------------- . } . } . } . } . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for chalk") . } . } 156,549 ( 0.00%) }); . . debug!("finished: {:?} from {:?}", result, obligation); . . result . } . 3,006,129 ( 0.00%) #[instrument(skip(self, previous_stack), level = "debug")] . fn evaluate_trait_predicate_recursively<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . mut obligation: TraitObligation<'tcx>, . ) -> Result { 286,298 ( 0.00%) if !self.intercrate . && obligation.is_global() . && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst()) . { . // If a param env has no global bounds, global obligations do not . // depend on its particular value in order to work, so we can clear . // out the param env and get better caching. . debug!("in global"); 12,358 ( 0.00%) obligation.param_env = obligation.param_env.without_caller_bounds(); . } . . let stack = self.push_stack(previous_stack, &obligation); . let mut fresh_trait_pred = stack.fresh_trait_pred; 286,298 ( 0.00%) let mut param_env = obligation.param_env; . . fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| { 143,149 ( 0.00%) pred.remap_constness(self.tcx(), &mut param_env); 1,717,788 ( 0.00%) pred . }); . . debug!(?fresh_trait_pred); . 138,940 ( 0.00%) if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) { . debug!(?result, "CACHE HIT"); . return Ok(result); . } . . if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) { . debug!(?result, "PROVISIONAL CACHE HIT"); . stack.update_reached_depth(result.reached_depth); . return Ok(result.result); -- line 744 ---------------------------------------- -- line 748 ---------------------------------------- . // stack. If so, we don't want to insert the result into the . // main cache (it is cycle dependent) nor the provisional . // cache (which is meant for things that have completed but . // for a "backedge" -- this result *is* the backedge). . if let Some(cycle_result) = self.check_evaluation_cycle(&stack) { . return Ok(cycle_result); . } . 628,236 ( 0.00%) let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack)); 69,804 ( 0.00%) let result = result?; . 349,020 ( 0.00%) if !result.must_apply_modulo_regions() { . stack.cache().on_failure(stack.dfn); . } . 69,804 ( 0.00%) let reached_depth = stack.reached_depth.get(); 139,608 ( 0.00%) if reached_depth >= stack.depth { . debug!(?result, "CACHE MISS"); 1,326,276 ( 0.00%) self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result); . . stack.cache().on_completion( 139,608 ( 0.00%) stack.dfn, . |fresh_trait_pred, provisional_result, provisional_dep_node| { . // Create a new `DepNode` that has dependencies on: . // * The `DepNode` for the original evaluation that resulted in a provisional cache . // entry being crated . // * The `DepNode` for the *current* evaluation, which resulted in us completing . // provisional caches entries and inserting them into the evaluation cache . // . // This ensures that when a query reads this entry from the evaluation cache, -- line 777 ---------------------------------------- -- line 835 ---------------------------------------- . /// `self.freshener`, we can be sure that (a) this will not . /// affect the inferencer state and (b) that if we see two . /// fresh regions with the same index, they refer to the same . /// unbound type variable. . fn check_evaluation_cycle( . &mut self, . stack: &TraitObligationStack<'_, 'tcx>, . ) -> Option { 1,060 ( 0.00%) if let Some(cycle_depth) = stack . .iter() . .skip(1) // Skip top-most frame. . .find(|prev| { 85,526 ( 0.00%) stack.obligation.param_env == prev.obligation.param_env . && stack.fresh_trait_pred == prev.fresh_trait_pred . }) . .map(|stack| stack.depth) . { . debug!("evaluate_stack --> recursive at depth {}", cycle_depth); . . // If we have a stack like `A B C D E A`, where the top of . // the stack is the final `A`, then this will iterate over . // `A, E, D, C, B` -- i.e., all the participants apart . // from the cycle head. We mark them as participating in a . // cycle. This suppresses caching for those nodes. See . // `in_cycle` field for more details. 1,060 ( 0.00%) stack.update_reached_depth(cycle_depth); . . // Subtle: when checking for a coinductive cycle, we do . // not compare using the "freshened trait refs" (which . // have erased regions) but rather the fully explicit . // trait refs. This is important because it's only a cycle . // if the regions match exactly. 587 ( 0.00%) let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth); 530 ( 0.00%) let tcx = self.tcx(); 3,710 ( 0.00%) let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx)); 5,830 ( 0.00%) if self.coinductive_match(cycle) { . debug!("evaluate_stack --> recursive, coinductive"); . Some(EvaluatedToOk) . } else { . debug!("evaluate_stack --> recursive, inductive"); . Some(EvaluatedToRecur) . } . } else { . None . } . } . 628,236 ( 0.00%) fn evaluate_stack<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . ) -> Result { . // In intercrate mode, whenever any of the generics are unbound, . // there can always be an impl. Even if there are no impls in . // this crate, perhaps the type would be unified with . // something from another crate that does provide an impl. . // -- line 890 ---------------------------------------- -- line 903 ---------------------------------------- . // imagine, this is just where we started. To avoid that, we . // check for unbound variables and return an ambiguous (hence possible) . // match if we've seen this trait before. . // . // This suffices to allow chains like `FnMut` implemented in . // terms of `Fn` etc, but we could probably make this more . // precise still. . let unbound_input_types = 69,804 ( 0.00%) stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh()); . 209,412 ( 0.00%) if stack.obligation.polarity() != ty::ImplPolarity::Negative { . // This check was an imperfect workaround for a bug in the old . // intercrate mode; it should be removed when that goes away. 349,020 ( 0.00%) if unbound_input_types && self.intercrate { . debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",); . // Heuristics: show the diagnostics when there are no candidates in crate. 1,125 ( 0.00%) if self.intercrate_ambiguity_causes.is_some() { . debug!("evaluate_stack: intercrate_ambiguity_causes is some"); . if let Ok(candidate_set) = self.assemble_candidates(stack) { . if !candidate_set.ambiguous && candidate_set.vec.is_empty() { . let trait_ref = stack.obligation.predicate.skip_binder().trait_ref; . let self_ty = trait_ref.self_ty(); . let cause = with_no_trimmed_paths(|| { . IntercrateAmbiguityCause::DownstreamCrate { . trait_desc: trait_ref.print_only_trait_path().to_string(), -- line 927 ---------------------------------------- -- line 937 ---------------------------------------- . self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause); . } . } . } . return Ok(EvaluatedToAmbig); . } . } . 137,358 ( 0.00%) if unbound_input_types . && stack.iter().skip(1).any(|prev| { 29,754 ( 0.00%) stack.obligation.param_env == prev.obligation.param_env . && self.match_fresh_trait_refs( 39,672 ( 0.00%) stack.fresh_trait_pred, 39,672 ( 0.00%) prev.fresh_trait_pred, . prev.obligation.param_env, . ) . }) . { . debug!("evaluate_stack --> unbound argument, recursive --> giving up",); . return Ok(EvaluatedToUnknown); . } . 644,400 ( 0.00%) match self.candidate_from_obligation(stack) { 294,882 ( 0.00%) Ok(Some(c)) => self.evaluate_candidate(stack, &c), . Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig), . Ok(None) => Ok(EvaluatedToAmbig), . Err(Overflow) => Err(OverflowError::Canonical), . Err(ErrorReporting) => Err(OverflowError::ErrorReporting), . Err(..) => Ok(EvaluatedToErr), . } 698,040 ( 0.00%) } . . /// For defaulted traits, we use a co-inductive strategy to solve, so . /// that recursion is ok. This routine returns `true` if the top of the . /// stack (`cycle[0]`): . /// . /// - is a defaulted trait, . /// - it also appears in the backtrace at some position `X`, . /// - all the predicates at positions `X..` between `X` and the top are -- line 975 ---------------------------------------- -- line 977 ---------------------------------------- . pub fn coinductive_match(&mut self, mut cycle: I) -> bool . where . I: Iterator>, . { . cycle.all(|predicate| self.coinductive_predicate(predicate)) . } . . fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool { 1,312 ( 0.00%) let result = match predicate.kind().skip_binder() { 5,904 ( 0.00%) ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()), . _ => false, . }; . debug!(?predicate, ?result, "coinductive_predicate"); . result . } . . /// Further evaluates `candidate` to decide whether all type parameters match and whether nested . /// obligations are met. Returns whether `candidate` remains viable after this further -- line 994 ---------------------------------------- -- line 998 ---------------------------------------- . skip(self, stack), . fields(depth = stack.obligation.recursion_depth) . )] . fn evaluate_candidate<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . candidate: &SelectionCandidate<'tcx>, . ) -> Result { 6,555,640 ( 0.01%) let mut result = self.evaluation_probe(|this| { . let candidate = (*candidate).clone(); 52,482,018 ( 0.05%) match this.confirm_candidate(stack.obligation, candidate) { . Ok(selection) => { . debug!(?selection); 13,111,280 ( 0.01%) this.evaluate_predicates_recursively( . stack.list(), 42,611,660 ( 0.04%) selection.nested_obligations().into_iter(), . ) . } . Err(..) => Ok(EvaluatedToErr), . } . })?; . . // If we erased any lifetimes, then we want to use . // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk` -- line 1021 ---------------------------------------- -- line 1037 ---------------------------------------- . &self, . param_env: ty::ParamEnv<'tcx>, . trait_pred: ty::PolyTraitPredicate<'tcx>, . ) -> Option { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 286,298 ( 0.00%) if self.intercrate { . return None; . } . . let tcx = self.tcx(); . if self.can_use_global_caches(param_env) { 930,818 ( 0.00%) if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) { . return Some(res); . } . } 277,880 ( 0.00%) self.infcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) . } . 837,648 ( 0.00%) fn insert_evaluation_cache( . &mut self, . param_env: ty::ParamEnv<'tcx>, . trait_pred: ty::PolyTraitPredicate<'tcx>, . dep_node: DepNodeIndex, . result: EvaluationResult, . ) { . // Avoid caching results that depend on more than just the trait-ref . // - the stack can create recursion. 279,216 ( 0.00%) if result.is_stack_dependent() { . return; . } . . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 139,608 ( 0.00%) if self.intercrate { . return; . } . . if self.can_use_global_caches(param_env) { . if !trait_pred.needs_infer() { . debug!(?trait_pred, ?result, "insert_evaluation_cache global"); . // This may overwrite the cache with the same value . // FIXME: Due to #50507 this overwrites the different values . // This should be changed to use HashMapExt::insert_same . // when that is fixed 60,782 ( 0.00%) self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result); . return; . } . } . . debug!(?trait_pred, ?result, "insert_evaluation_cache"); 28,036 ( 0.00%) self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result); 558,432 ( 0.00%) } . . /// For various reasons, it's possible for a subobligation . /// to have a *lower* recursion_depth than the obligation used to create it. . /// Projection sub-obligations may be returned from the projection cache, . /// which results in obligations with an 'old' `recursion_depth`. . /// Additionally, methods like `InferCtxt.subtype_predicate` produce . /// subobligations without taking in a 'parent' depth, causing the . /// generated subobligations to have a `recursion_depth` of `0`. . /// . /// To ensure that obligation_depth never decreases, we force all subobligations . /// to have at least the depth of the original obligation. 1,878 ( 0.00%) fn add_depth>>( . &self, . it: I, . min_depth: usize, . ) { 4,388 ( 0.00%) it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1); 3,756 ( 0.00%) } . . fn check_recursion_depth>( . &self, . depth: usize, . error_obligation: &Obligation<'tcx, T>, . ) -> Result<(), OverflowError> { 3,299,332 ( 0.00%) if !self.infcx.tcx.recursion_limit().value_within_limit(depth) { . match self.query_mode { . TraitQueryMode::Standard => { . if self.infcx.is_tainted_by_errors() { . return Err(OverflowError::ErrorReporting); . } . self.infcx.report_overflow_error(error_obligation, true); . } . TraitQueryMode::Canonical => { -- line 1126 ---------------------------------------- -- line 1143 ---------------------------------------- . ) -> Result<(), OverflowError> { . self.check_recursion_depth(obligation.recursion_depth, error_obligation) . } . . fn in_task(&mut self, op: OP) -> (R, DepNodeIndex) . where . OP: FnOnce(&mut Self) -> R, . { 2,968,095 ( 0.00%) let (result, dep_node) = 1,928,322 ( 0.00%) self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self)); . self.tcx().dep_graph.read_index(dep_node); 2,739,780 ( 0.00%) (result, dep_node) . } . . /// filter_impls filters constant trait obligations and candidates that have a positive impl . /// for a negative goal and a negative impl for a positive goal . #[instrument(level = "debug", skip(self))] . fn filter_impls( . &mut self, . candidates: Vec>, . obligation: &TraitObligation<'tcx>, . ) -> Vec> { . let tcx = self.tcx(); . let mut result = Vec::with_capacity(candidates.len()); . 37,791,840 ( 0.03%) for candidate in candidates { . // Respect const trait obligations 10,065,600 ( 0.01%) if obligation.is_const() { 573 ( 0.00%) match candidate { . // const impl . ImplCandidate(def_id) . if tcx.impl_constness(def_id) == hir::Constness::Const => {} . // const param . ParamCandidate(trait_pred) . if trait_pred.skip_binder().constness . == ty::BoundConstness::ConstIfConst => {} . // auto trait impl -- line 1179 ---------------------------------------- -- line 1186 ---------------------------------------- . ConstDropCandidate(_) => {} . _ => { . // reject all other types of candidates . continue; . } . } . } . 6,710,018 ( 0.01%) if let ImplCandidate(def_id) = candidate { 6,565,418 ( 0.01%) if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id) 3,282,688 ( 0.00%) || obligation.polarity() == tcx.impl_polarity(def_id) . || self.allow_negative_impls . { . result.push(candidate); . } . } else { . result.push(candidate); . } . } . 707,712 ( 0.00%) result . } . . /// filter_reservation_impls filter reservation impl for any goal as ambiguous 2,295,884 ( 0.00%) #[instrument(level = "debug", skip(self))] . fn filter_reservation_impls( . &mut self, . candidate: SelectionCandidate<'tcx>, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . let tcx = self.tcx(); . // Treat reservation impls as ambiguity. 400,206 ( 0.00%) if let ImplCandidate(def_id) = candidate { 130,102 ( 0.00%) if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) { . if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes { . let attrs = tcx.get_attrs(def_id); . let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl); . let value = attr.and_then(|a| a.value_str()); . if let Some(value) = value { . debug!( . "filter_reservation_impls: \ . reservation impl ambiguity on {:?}", -- line 1227 ---------------------------------------- -- line 1232 ---------------------------------------- . message: value.to_string(), . }, . ); . } . } . return Ok(None); . } . } 810,312 ( 0.00%) Ok(Some(candidate)) . } . . fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option { . debug!("is_knowable(intercrate={:?})", self.intercrate); . 995,352 ( 0.00%) if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative { . return None; . } . . let obligation = &stack.obligation; 310,407 ( 0.00%) let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate); . . // Okay to skip binder because of the nature of the . // trait-ref-is-knowable check, which does not care about . // bound regions. . let trait_ref = predicate.skip_binder().trait_ref; . 310,407 ( 0.00%) coherence::trait_ref_is_knowable(self.tcx(), trait_ref) . } . . /// Returns `true` if the global caches can be used. . fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool { . // If there are any inference variables in the `ParamEnv`, then we . // always use a cache local to this particular scope. Otherwise, we . // switch to a global cache. . if param_env.needs_infer() { -- line 1266 ---------------------------------------- -- line 1286 ---------------------------------------- . &mut self, . mut param_env: ty::ParamEnv<'tcx>, . cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, . ) -> Option>> { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 1,336,568 ( 0.00%) if self.intercrate { 103,469 ( 0.00%) return None; . } . let tcx = self.tcx(); . let mut pred = cache_fresh_trait_pred.skip_binder(); 1,129,630 ( 0.00%) pred.remap_constness(tcx, &mut param_env); . 564,815 ( 0.00%) if self.can_use_global_caches(param_env) { 5,504,410 ( 0.00%) if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) { 5,706,428 ( 0.00%) return Some(res); . } . } 1,370,075 ( 0.00%) self.infcx.selection_cache.get(¶m_env.and(pred), tcx) . } . . /// Determines whether can we safely cache the result . /// of selecting an obligation. This is almost always `true`, . /// except when dealing with certain `ParamCandidate`s. . /// . /// Ordinarily, a `ParamCandidate` will contain no inference variables, . /// since it was usually produced directly from a `DefId`. However, -- line 1314 ---------------------------------------- -- line 1325 ---------------------------------------- . fn can_cache_candidate( . &self, . result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>, . ) -> bool { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 456,630 ( 0.00%) if self.intercrate { . return false; . } 374,538 ( 0.00%) match result { . Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(), . _ => true, . } . } . . fn insert_candidate_cache( . &mut self, . mut param_env: ty::ParamEnv<'tcx>, . cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, . dep_node: DepNodeIndex, . candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>, . ) { . let tcx = self.tcx(); . let mut pred = cache_fresh_trait_pred.skip_binder(); . 456,630 ( 0.00%) pred.remap_constness(tcx, &mut param_env); . . if !self.can_cache_candidate(&candidate) { . debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable"); . return; . } . 124,782 ( 0.00%) if self.can_use_global_caches(param_env) { 250,818 ( 0.00%) if let Err(Overflow) = candidate { . // Don't cache overflow globally; we only produce this in certain modes. . } else if !pred.needs_infer() { 445,940 ( 0.00%) if !candidate.needs_infer() { . debug!(?pred, ?candidate, "insert_candidate_cache global"); . // This may overwrite the cache with the same value. 3,010,095 ( 0.00%) tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate); . return; . } . } . } . . debug!(?pred, ?candidate, "insert_candidate_cache local"); 305,831 ( 0.00%) self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate); . } . . /// Matches a predicate against the bounds of its self type. . /// . /// Given an obligation like `::Bar: Baz` where the self type is . /// a projection, look at the bounds of `T::Bar`, see if we can find a . /// `Baz` bound. We return indexes into the list returned by . /// `tcx.item_bounds` for any applicable bounds. 73,971 ( 0.00%) fn match_projection_obligation_against_definition_bounds( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> smallvec::SmallVec<[usize; 2]> { 106,847 ( 0.00%) let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate); . let placeholder_trait_predicate = 139,723 ( 0.00%) self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate); . debug!( . ?placeholder_trait_predicate, . "match_projection_obligation_against_definition_bounds" . ); . 8,219 ( 0.00%) let tcx = self.infcx.tcx; 49,314 ( 0.00%) let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() { 24,657 ( 0.00%) ty::Projection(ref data) => (data.item_def_id, data.substs), . ty::Opaque(def_id, substs) => (def_id, substs), . _ => { . span_bug!( . obligation.cause.span, . "match_projection_obligation_against_definition_bounds() called \ . but self-ty is not a projection: {:?}", . placeholder_trait_predicate.trait_ref.self_ty() . ); -- line 1404 ---------------------------------------- -- line 1411 ---------------------------------------- . // unnecessary ambiguity. . let mut distinct_normalized_bounds = FxHashSet::default(); . . let matching_bounds = bounds . .iter() . .enumerate() . .filter_map(|(idx, bound)| { . let bound_predicate = bound.kind(); 303,456 ( 0.00%) if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() { . let bound = bound_predicate.rebind(pred.trait_ref); 1,353,090 ( 0.00%) if self.infcx.probe(|_| { 541,188 ( 0.00%) match self.match_normalize_trait_ref( . obligation, 360,824 ( 0.00%) bound, 360,824 ( 0.00%) placeholder_trait_predicate.trait_ref, . ) { . Ok(None) => true, . Ok(Some(normalized_trait)) . if distinct_normalized_bounds.insert(normalized_trait) => . { . true . } . _ => false, -- line 1433 ---------------------------------------- -- line 1437 ---------------------------------------- . } . } . None . }) . .collect(); . . debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds"); . matching_bounds 73,971 ( 0.00%) } . . /// Equates the trait in `obligation` with trait bound. If the two traits . /// can be equated and the normalized trait bound doesn't contain inference . /// variables or placeholders, the normalized bound is returned. 1,172,678 ( 0.00%) fn match_normalize_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . trait_bound: ty::PolyTraitRef<'tcx>, . placeholder_trait_ref: ty::TraitRef<'tcx>, . ) -> Result>, ()> { . debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars()); 282,286 ( 0.00%) if placeholder_trait_ref.def_id != trait_bound.def_id() { . // Avoid unnecessary normalization 168,746 ( 0.00%) return Err(()); . } . 69,996 ( 0.00%) let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 5,833 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 17,499 ( 0.00%) obligation.recursion_depth + 1, 23,332 ( 0.00%) trait_bound, . ) . }); 17,499 ( 0.00%) self.infcx 11,666 ( 0.00%) .at(&obligation.cause, obligation.param_env) . .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound) . .map(|InferOk { obligations: _, value: () }| { . // This method is called within a probe, so we can't have . // inference variables and placeholders escape. . if !trait_bound.needs_infer() && !trait_bound.has_placeholders() { 29,045 ( 0.00%) Some(trait_bound) . } else { . None . } . }) . .map_err(|_| ()) 811,854 ( 0.00%) } . . fn evaluate_where_clause<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . where_clause_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result { . self.evaluation_probe(|this| { 2,456,410 ( 0.00%) match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) { 379,288 ( 0.00%) Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations), . Err(()) => Ok(EvaluatedToErr), . } . }) . } . 298,809 ( 0.00%) pub(super) fn match_projection_projections( . &mut self, . obligation: &ProjectionTyObligation<'tcx>, . env_predicate: PolyProjectionPredicate<'tcx>, . potentially_unnormalized_candidates: bool, . ) -> bool { . let mut nested_obligations = Vec::new(); 166,005 ( 0.00%) let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars( 99,603 ( 0.00%) obligation.cause.span, . LateBoundRegionConversionTime::HigherRankedType, . env_predicate, . ); 66,402 ( 0.00%) let infer_projection = if potentially_unnormalized_candidates { 4,728 ( 0.00%) ensure_sufficient_stack(|| { 2,364 ( 0.00%) project::normalize_with_depth_to( . self, 591 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 1,773 ( 0.00%) obligation.recursion_depth + 1, 1,182 ( 0.00%) infer_predicate.projection_ty, . &mut nested_obligations, . ) . }) . } else { 65,220 ( 0.00%) infer_predicate.projection_ty . }; . 33,201 ( 0.00%) self.infcx 66,402 ( 0.00%) .at(&obligation.cause, obligation.param_env) 66,402 ( 0.00%) .sup(obligation.predicate, infer_projection) 213,258 ( 0.00%) .map_or(false, |InferOk { obligations, value: () }| { . self.evaluate_predicates_recursively( . TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), . nested_obligations.into_iter().chain(obligations), . ) 31,502 ( 0.00%) .map_or(false, |res| res.may_apply()) . }) 298,809 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // WINNOW . // . // Winnowing is the process of attempting to resolve ambiguity by . // probing further. During the winnowing process, we unify all . // type variables and then we also attempt to evaluate recursive . // bounds to see if they are satisfied. -- line 1544 ---------------------------------------- -- line 1550 ---------------------------------------- . /// See the comment for "SelectionCandidate" for more details. . fn candidate_should_be_dropped_in_favor_of( . &mut self, . sized_predicate: bool, . victim: &EvaluatedCandidate<'tcx>, . other: &EvaluatedCandidate<'tcx>, . needs_infer: bool, . ) -> bool { 6,365,022 ( 0.01%) if victim.candidate == other.candidate { . return true; . } . . // Check if a bound would previously have been removed when normalizing . // the param_env so that it can be given the lowest priority. See . // #50825 for the motivation for this. . let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| { 2,409 ( 0.00%) cand.is_global() && !cand.has_late_bound_regions() . }; . . // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`, . // `DiscriminantKindCandidate`, and `ConstDropCandidate` to anything else. . // . // This is a fix for #53123 and prevents winnowing from accidentally extending the . // lifetime of a variable. 114,686,135 ( 0.10%) match (&other.candidate, &victim.candidate) { . (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => { . bug!( . "default implementations shouldn't be recorded \ . when there are other valid candidates" . ); . } . . // (*) -- line 1582 ---------------------------------------- -- line 1591 ---------------------------------------- . _, . BuiltinCandidate { has_nested: false } . | DiscriminantKindCandidate . | PointeeCandidate . | ConstDropCandidate(_), . ) => false, . . (ParamCandidate(other), ParamCandidate(victim)) => { 3,632 ( 0.00%) let same_except_bound_vars = other.skip_binder().trait_ref 4,540 ( 0.00%) == victim.skip_binder().trait_ref . && other.skip_binder().constness == victim.skip_binder().constness . && other.skip_binder().polarity == victim.skip_binder().polarity . && !other.skip_binder().trait_ref.has_escaping_bound_vars(); . if same_except_bound_vars { . // See issue #84398. In short, we can generate multiple ParamCandidates which are . // the same except for unused bound vars. Just pick the one with the fewest bound vars . // or the current one if tied (they should both evaluate to the same answer). This is . // probably best characterized as a "hack", since we might prefer to just do our -- line 1608 ---------------------------------------- -- line 1620 ---------------------------------------- . } . . // Drop otherwise equivalent non-const fn pointer candidates . (FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true, . . // If obligation is a sized predicate or the where-clause bound is . // global, prefer the projection or object candidate. See issue . // #50825 and #89352. 24 ( 0.00%) (ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => { 484 ( 0.00%) sized_predicate || is_global(cand) . } 342 ( 0.00%) (ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => { 810 ( 0.00%) !(sized_predicate || is_global(cand)) . } . . // Global bounds from the where clause should be ignored . // here (see issue #50825). Otherwise, we have a where . // clause so don't go around looking for impls. . // Arbitrarily give param candidates priority . // over projection and object candidates. . ( 19,065 ( 0.00%) ParamCandidate(ref cand), . ImplCandidate(..) . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } -- line 1649 ---------------------------------------- -- line 1654 ---------------------------------------- . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { has_nested: true } . | TraitAliasCandidate(..), 4,626 ( 0.00%) ParamCandidate(ref cand), . ) => { . // Prefer these to a global where-clause bound . // (see issue #50825). 2,590 ( 0.00%) is_global(cand) && other.evaluation.must_apply_modulo_regions() . } . . (ProjectionCandidate(i), ProjectionCandidate(j)) . | (ObjectCandidate(i), ObjectCandidate(j)) => { . // Arbitrarily pick the lower numbered candidate for backwards . // compatibility reasons. Don't let this affect inference. . i < j && !needs_infer . } . (ObjectCandidate(_), ProjectionCandidate(_)) . | (ProjectionCandidate(_), ObjectCandidate(_)) => { . bug!("Have both object and projection candidate") . } . . // Arbitrarily give projection and object candidates priority. . ( 12,730,374 ( 0.01%) ObjectCandidate(_) | ProjectionCandidate(_), 330 ( 0.00%) ImplCandidate(..) . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } . | TraitAliasCandidate(..), -- line 1691 ---------------------------------------- -- line 1696 ---------------------------------------- . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } . | TraitAliasCandidate(..), 25,460,088 ( 0.02%) ObjectCandidate(_) | ProjectionCandidate(_), . ) => false, . 63,650,220 ( 0.05%) (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => { . // See if we can toss out `victim` based on specialization. . // This requires us to know *for sure* that the `other` impl applies . // i.e., `EvaluatedToOk`. . // . // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary . // to me but is required for `std` to compile, so I didn't change it . // for now. . let tcx = self.tcx(); 25,460,088 ( 0.02%) if other.evaluation.must_apply_modulo_regions() { 50,871,944 ( 0.04%) if tcx.specializes((other_def, victim_def)) { . return true; . } . } . 31,825,110 ( 0.03%) if other.evaluation.must_apply_considering_regions() { 25,428,448 ( 0.02%) match tcx.impls_are_allowed_to_overlap(other_def, victim_def) { . Some(ty::ImplOverlapKind::Permitted { marker: true }) => { . // Subtle: If the predicate we are evaluating has inference . // variables, do *not* allow discarding candidates due to . // marker trait impls. . // . // Without this restriction, we could end up accidentally . // constrainting inference variables based on an arbitrarily . // chosen trait impl. -- line 1731 ---------------------------------------- -- line 1790 ---------------------------------------- . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { has_nested: true } . | TraitAliasCandidate(..), . ) => false, . } . } . 266,110 ( 0.00%) fn sized_conditions( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> BuiltinImplConditions<'tcx> { . use self::BuiltinImplConditions::{Ambiguous, None, Where}; . . // NOTE: binder moved to (*) 79,833 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); . 133,887 ( 0.00%) match self_ty.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 1815 ---------------------------------------- -- line 1817 ---------------------------------------- . | ty::Ref(..) . | ty::Generator(..) . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => { . // safe for everything 5,345 ( 0.00%) Where(ty::Binder::dummy(Vec::new())) . } . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None, . . ty::Tuple(tys) => Where( . obligation . .predicate 5,282 ( 0.00%) .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()), . ), . . ty::Adt(def, substs) => { 17,624 ( 0.00%) let sized_crit = def.sized_constraint(self.tcx()); . // (*) binder moved here 44,060 ( 0.00%) Where( . obligation.predicate.rebind({ 8,812 ( 0.00%) sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect() . }), . ) . } . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None, . ty::Infer(ty::TyVar(_)) => Ambiguous, . . ty::Placeholder(..) . | ty::Bound(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); . } . } 212,888 ( 0.00%) } . 126,232 ( 0.00%) fn copy_clone_conditions( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> BuiltinImplConditions<'tcx> { . // NOTE: binder moved to (*) 31,558 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); . . use self::BuiltinImplConditions::{Ambiguous, None, Where}; . 79,725 ( 0.00%) match *self_ty.kind() { . ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) . | ty::FnDef(..) . | ty::FnPtr(_) 106 ( 0.00%) | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())), . . ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::Char . | ty::RawPtr(..) . | ty::Never -- line 1879 ---------------------------------------- -- line 1886 ---------------------------------------- . ty::Dynamic(..) . | ty::Str . | ty::Slice(..) . | ty::Generator(..) . | ty::GeneratorWitness(..) . | ty::Foreign(..) . | ty::Ref(_, _, hir::Mutability::Mut) => None, . 595 ( 0.00%) ty::Tuple(tys) => { . // (*) binder moved here 3,042 ( 0.00%) Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect())) . } . 261 ( 0.00%) ty::Closure(_, substs) => { . // (*) binder moved here 783 ( 0.00%) let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); 522 ( 0.00%) if let ty::Infer(ty::TyVar(_)) = ty.kind() { . // Not yet resolved. . Ambiguous . } else { 1,827 ( 0.00%) Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect())) . } . } . . ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => { . // Fallback to whatever user-defined impls exist in this case. . None . } . -- line 1914 ---------------------------------------- -- line 1920 ---------------------------------------- . } . . ty::Placeholder(..) . | ty::Bound(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); . } . } 94,674 ( 0.00%) } . . /// For default impls, we need to break apart a type into its . /// "constituent types" -- meaning, the types that it contains. . /// . /// Here are some (simple) examples: . /// . /// ``` . /// (i32, u32) -> [i32, u32] -- line 1936 ---------------------------------------- -- line 1937 ---------------------------------------- . /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32] . /// Bar where struct Bar { x: T, y: u32 } -> [i32, u32] . /// Zed where enum Zed { A(T), B(u32) } -> [i32, u32] . /// ``` . fn constituent_types_for_ty( . &self, . t: ty::Binder<'tcx, Ty<'tcx>>, . ) -> ty::Binder<'tcx, Vec>> { 3,996 ( 0.00%) match *t.skip_binder().kind() { . ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::Str . | ty::Error(_) -- line 1953 ---------------------------------------- -- line 1968 ---------------------------------------- . ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => { . t.rebind(vec![element_ty]) . } . . ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]), . . ty::Tuple(ref tys) => { . // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet 82 ( 0.00%) t.rebind(tys.iter().map(|k| k.expect_ty()).collect()) . } . . ty::Closure(_, ref substs) => { . let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); . t.rebind(vec![ty]) . } . . ty::Generator(_, ref substs, _) => { -- line 1984 ---------------------------------------- -- line 1988 ---------------------------------------- . } . . ty::GeneratorWitness(types) => { . debug_assert!(!types.has_escaping_bound_vars()); . types.map_bound(|types| types.to_vec()) . } . . // For `PhantomData`, we pass `T`. 1,084 ( 0.00%) ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()), . 542 ( 0.00%) ty::Adt(def, substs) => { 505 ( 0.00%) t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect()) . } . . ty::Opaque(def_id, substs) => { . // We can resolve the `impl Trait` to its concrete type, . // which enforces a DAG between the functions requiring . // the auto trait bounds in question. . t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]) . } . } . } . 32,064 ( 0.00%) fn collect_predicates_for_types( . &mut self, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . trait_def_id: DefId, . types: ty::Binder<'tcx, Vec>>, . ) -> Vec> { . // Because the types were potentially derived from -- line 2019 ---------------------------------------- -- line 2030 ---------------------------------------- . // 2. Produce something like `&'0 i32 : Copy` . // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy` . . types . .as_ref() . .skip_binder() // binder moved -\ . .iter() . .flat_map(|ty| { 7,002 ( 0.00%) let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/ . 28,008 ( 0.00%) self.infcx.commit_unconditionally(|_| { 7,002 ( 0.00%) let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty); 11,670 ( 0.00%) let Normalized { value: normalized_ty, mut obligations } = 23,340 ( 0.00%) ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 2,334 ( 0.00%) param_env, . cause.clone(), 2,334 ( 0.00%) recursion_depth, 2,334 ( 0.00%) placeholder_ty, . ) . }); 25,674 ( 0.00%) let placeholder_obligation = predicate_for_trait_def( . self.tcx(), 2,334 ( 0.00%) param_env, . cause.clone(), 4,668 ( 0.00%) trait_def_id, . recursion_depth, . normalized_ty, . &[], . ); 14,004 ( 0.00%) obligations.push(placeholder_obligation); . obligations . }) . }) . .collect() 16,032 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // Matching . // . // Matching is a common path used for both evaluation and . // confirmation. It basically unifies types that appear in impls . // and traits. This does affect the surrounding environment; . // therefore, when used during evaluation, match routines must be -- line 2074 ---------------------------------------- -- line 2075 ---------------------------------------- . // run inside of a `probe()` so that their side-effects are . // contained. . . fn rematch_impl( . &mut self, . impl_def_id: DefId, . obligation: &TraitObligation<'tcx>, . ) -> Normalized<'tcx, SubstsRef<'tcx>> { 16,647,145 ( 0.01%) match self.match_impl(impl_def_id, obligation) { 13,317,716 ( 0.01%) Ok(substs) => substs, . Err(()) => { . bug!( . "Impl {:?} was matchable against {:?} but now is not", . impl_def_id, . obligation . ); . } . } . } . 199,320,754 ( 0.17%) #[tracing::instrument(level = "debug", skip(self))] . fn match_impl( . &mut self, . impl_def_id: DefId, . obligation: &TraitObligation<'tcx>, . ) -> Result>, ()> { . let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap(); . . // Before we create the substitutions and everything, first . // consider a "quick reject". This avoids creating more types . // and so forth that we need to. . if self.fast_reject_trait_refs(obligation, &impl_trait_ref) { 495,964 ( 0.00%) return Err(()); . } . . let placeholder_obligation = 71,698,088 ( 0.06%) self.infcx().replace_bound_vars_with_placeholders(obligation.predicate); 30,727,752 ( 0.03%) let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref; . 51,212,920 ( 0.04%) let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id); . 20,485,168 ( 0.02%) let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs); . . debug!(?impl_trait_ref); . 61,455,504 ( 0.05%) let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } = 71,698,088 ( 0.06%) ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 10,242,584 ( 0.01%) obligation.param_env, . obligation.cause.clone(), 30,727,752 ( 0.03%) obligation.recursion_depth + 1, 20,485,168 ( 0.02%) impl_trait_ref, . ) . }); . . debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref); . . let cause = ObligationCause::new( 10,242,584 ( 0.01%) obligation.cause.span, 20,485,168 ( 0.02%) obligation.cause.body_id, 92,183,256 ( 0.08%) ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id), . ); . 20,485,168 ( 0.02%) let InferOk { obligations, .. } = self . .infcx 10,242,584 ( 0.01%) .at(&cause, obligation.param_env) . .eq(placeholder_obligation_trait_ref, impl_trait_ref) . .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?; . nested_obligations.extend(obligations); . 13,386,822 ( 0.01%) if !self.intercrate . && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation . { . debug!("match_impl: reservation impls only apply in intercrate mode"); . return Err(()); . } . . debug!(?impl_substs, ?nested_obligations, "match_impl: success"); 39,672,702 ( 0.03%) Ok(Normalized { value: impl_substs, obligations: nested_obligations }) . } . . fn fast_reject_trait_refs( . &mut self, . obligation: &TraitObligation<'_>, . impl_trait_ref: &ty::TraitRef<'_>, . ) -> bool { . // We can avoid creating type variables and doing the full . // substitution if we find that any of the input types, when . // simplified, do not match. . 31,471,698 ( 0.03%) iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any( . |(obligation_arg, impl_arg)| { 67,195,502 ( 0.06%) match (obligation_arg.unpack(), impl_arg.unpack()) { . (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => { . // Note, we simplify parameters for the obligation but not the . // impl so that we do not reject a blanket impl but do reject . // more concrete impls if we're searching for `T: Trait`. 89,428,888 ( 0.08%) let simplified_obligation_ty = fast_reject::simplify_type( . self.tcx(), . obligation_ty, . SimplifyParams::Yes, . StripReferences::No, . ); 67,071,666 ( 0.06%) let simplified_impl_ty = fast_reject::simplify_type( . self.tcx(), . impl_ty, . SimplifyParams::No, . StripReferences::No, . ); . 33,535,833 ( 0.03%) simplified_obligation_ty.is_some() . && simplified_impl_ty.is_some() . && simplified_obligation_ty != simplified_impl_ty . } . (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => { . // Lifetimes can never cause a rejection. . false . } . (GenericArgKind::Const(_), GenericArgKind::Const(_)) => { -- line 2194 ---------------------------------------- -- line 2201 ---------------------------------------- . } . }, . ) . } . . /// Normalize `where_clause_trait_ref` and try to match it against . /// `obligation`. If successful, return any predicates that . /// result from the normalization. 2,009,790 ( 0.00%) fn match_where_clause_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . where_clause_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, ()> { . self.match_poly_trait_ref(obligation, where_clause_trait_ref) 1,786,480 ( 0.00%) } . . /// Returns `Ok` if `poly_trait_ref` being true implies that the . /// obligation is satisfied. . #[instrument(skip(self), level = "debug")] . fn match_poly_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . poly_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, ()> { 524,482 ( 0.00%) self.infcx 223,310 ( 0.00%) .at(&obligation.cause, obligation.param_env) 1,573,446 ( 0.00%) .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref) . .map(|InferOk { obligations, .. }| obligations) . .map_err(|_| ()) . } . . /////////////////////////////////////////////////////////////////////////// . // Miscellany . . fn match_fresh_trait_refs( . &self, . previous: ty::PolyTraitPredicate<'tcx>, . current: ty::PolyTraitPredicate<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> bool { 29,754 ( 0.00%) let mut matcher = ty::_match::Match::new(self.tcx(), param_env); . matcher.relate(previous, current).is_ok() . } . . fn push_stack<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . obligation: &'o TraitObligation<'tcx>, . ) -> TraitObligationStack<'o, 'tcx> { 4,742,822 ( 0.00%) let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener); . . let dfn = previous_stack.cache.next_dfn(); 286,298 ( 0.00%) let depth = previous_stack.depth() + 1; 6,255,339 ( 0.01%) TraitObligationStack { . obligation, 3,856,919 ( 0.00%) fresh_trait_pred, . reached_depth: Cell::new(depth), . previous: previous_stack, . dfn, . depth, . } . } . . #[instrument(skip(self), level = "debug")] . fn closure_trait_ref_unnormalized( . &mut self, . obligation: &TraitObligation<'tcx>, . substs: SubstsRef<'tcx>, . ) -> ty::PolyTraitRef<'tcx> { 2,475 ( 0.00%) let closure_sig = substs.as_closure().sig(); . . debug!(?closure_sig); . . // (1) Feels icky to skip the binder here, but OTOH we know . // that the self-type is an unboxed closure type and hence is . // in fact unparameterized (or at least does not reference any . // regions bound in the obligation). Still probably some . // refactoring could make this nicer. 8,250 ( 0.00%) closure_trait_ref_and_return_type( . self.tcx(), 4,950 ( 0.00%) obligation.predicate.def_id(), 825 ( 0.00%) obligation.predicate.skip_binder().self_ty(), // (1) 3,300 ( 0.00%) closure_sig, . util::TupleArgumentsFlag::No, . ) . .map_bound(|(trait_ref, _)| trait_ref) . } . . fn generator_trait_ref_unnormalized( . &mut self, . obligation: &TraitObligation<'tcx>, -- line 2291 ---------------------------------------- -- line 2307 ---------------------------------------- . ) . .map_bound(|(trait_ref, ..)| trait_ref) . } . . /// Returns the obligations that are implied by instantiating an . /// impl or trait. The obligations are substituted and fully . /// normalized. This is used when confirming an impl or default . /// impl. 76,595,175 ( 0.07%) #[tracing::instrument(level = "debug", skip(self, cause, param_env))] . fn impl_or_trait_obligations( . &mut self, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . param_env: ty::ParamEnv<'tcx>, . def_id: DefId, // of impl or trait . substs: SubstsRef<'tcx>, // for impl or trait . ) -> Vec> { -- line 2323 ---------------------------------------- -- line 2334 ---------------------------------------- . // V: Iterator, V: Sized, . // ::Item: Copy . // When we substitute, say, `V => IntoIter, U => $0`, the last . // obligation will normalize to `<$0 as Iterator>::Item = $1` and . // `$1: Copy`, so we must ensure the obligations are emitted in . // that order. . let predicates = tcx.predicates_of(def_id); . debug!(?predicates); 3,330,225 ( 0.00%) assert_eq!(predicates.parent, None); 9,990,675 ( 0.01%) let mut obligations = Vec::with_capacity(predicates.predicates.len()); . for (predicate, _) in predicates.predicates { . debug!(?predicate); 1,865,720 ( 0.00%) let predicate = normalize_with_depth_to( . self, . param_env, . cause.clone(), . recursion_depth, 373,144 ( 0.00%) predicate.subst(tcx, substs), . &mut obligations, . ); 3,731,440 ( 0.00%) obligations.push(Obligation { . cause: cause.clone(), . recursion_depth, . param_env, . predicate, . }); . } . . // We are performing deduplication here to avoid exponential blowups -- line 2362 ---------------------------------------- -- line 2363 ---------------------------------------- . // (#38528) from happening, but the real cause of the duplication is . // unknown. What we know is that the deduplication avoids exponential . // amount of predicates being propagated when processing deeply nested . // types. . // . // This code is hot enough that it's worth avoiding the allocation . // required for the FxHashSet when possible. Special-casing lengths 0, . // 1 and 2 covers roughly 75-80% of the cases. 265,686 ( 0.00%) if obligations.len() <= 1 { . // No possibility of duplicates. 76,531 ( 0.00%) } else if obligations.len() == 2 { . // Only two elements. Drop the second if they are equal. . if obligations[0] == obligations[1] { . obligations.truncate(1); . } . } else { . // Three or more elements. Use a general deduplication process. . let mut seen = FxHashSet::default(); 53,676 ( 0.00%) obligations.retain(|i| seen.insert(i.clone())); . } . 13,320,900 ( 0.01%) obligations . } . } . . trait TraitObligationExt<'tcx> { . fn derived_cause( . &self, . variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>, . ) -> ObligationCause<'tcx>; -- line 2392 ---------------------------------------- -- line 2408 ---------------------------------------- . */ . . let obligation = self; . . // NOTE(flaper87): As of now, it keeps track of the whole error . // chain. Ideally, we should have a way to configure this either . // by using -Z verbose or just a CLI argument. . let derived_cause = DerivedObligationCause { 13,334,888 ( 0.01%) parent_trait_pred: obligation.predicate, 6,664,743 ( 0.01%) parent_code: obligation.cause.clone_code(), . }; . let derived_code = variant(derived_cause); 40,000,371 ( 0.03%) ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code) . } . } . . impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> { . fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> { . TraitObligationStackList::with(self) . } . . fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> { 3,492,163 ( 0.00%) self.previous.cache . } . . fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> { . self.list() . } . . /// Indicates that attempting to evaluate this stack entry . /// required accessing something from the stack at depth `reached_depth`. 1,060 ( 0.00%) fn update_reached_depth(&self, reached_depth: usize) { 530 ( 0.00%) assert!( 530 ( 0.00%) self.depth >= reached_depth, . "invoked `update_reached_depth` with something under this stack: \ . self.depth={} reached_depth={}", . self.depth, . reached_depth, . ); . debug!(reached_depth, "update_reached_depth"); . let mut p = self; 1,590 ( 0.00%) while reached_depth < p.depth { . debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant"); 530 ( 0.00%) p.reached_depth.set(p.reached_depth.get().min(reached_depth)); 530 ( 0.00%) p = p.previous.head.unwrap(); . } 1,060 ( 0.00%) } . } . . /// The "provisional evaluation cache" is used to store intermediate cache results . /// when solving auto traits. Auto traits are unusual in that they can support . /// cycles. So, for example, a "proof tree" like this would be ok: . /// . /// - `Foo: Send` :- . /// - `Bar: Send` :- -- line 2462 ---------------------------------------- -- line 2540 ---------------------------------------- . /// evaluation. When we create an entry in the evaluation cache using this provisional . /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from . /// the cache will have all of the necessary incr comp dependencies tracked. . dep_node: DepNodeIndex, . } . . impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> { . fn default() -> Self { 821,621 ( 0.00%) Self { dfn: Cell::new(0), map: Default::default() } . } . } . . impl<'tcx> ProvisionalEvaluationCache<'tcx> { . /// Get the next DFN in sequence (basically a counter). . fn next_dfn(&self) -> usize { 143,149 ( 0.00%) let result = self.dfn.get(); 572,596 ( 0.00%) self.dfn.set(result + 1); . result . } . . /// Check the provisional cache for any result for . /// `fresh_trait_ref`. If there is a hit, then you must consider . /// it an access to the stack slots at depth . /// `reached_depth` (from the returned value). . fn get_provisional( -- line 2564 ---------------------------------------- -- line 2663 ---------------------------------------- . fn on_completion( . &self, . dfn: usize, . mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex), . ) { . debug!(?dfn, "on_completion"); . . for (fresh_trait_pred, eval) in 488,628 ( 0.00%) self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn) . { . debug!(?fresh_trait_pred, ?eval, "on_completion"); . . op(fresh_trait_pred, eval.result, eval.dep_node); . } . } . } . -- line 2679 ---------------------------------------- -- line 2692 ---------------------------------------- . TraitObligationStackList { cache: r.cache(), head: Some(r) } . } . . fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> { . self.head . } . . fn depth(&self) -> usize { 390,332 ( 0.00%) if let Some(head) = self.head { head.depth } else { 0 } . } . } . . impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> { . type Item = &'o TraitObligationStack<'o, 'tcx>; . . fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> { 344,658 ( 0.00%) let o = self.head?; 69,290 ( 0.00%) *self = o.previous; . Some(o) . } . } . . impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "TraitObligationStack({:?})", self.obligation) . } -- line 2717 ---------------------------------------- 223,615,218 ( 0.19%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 184,199,832 ( 0.16%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 115,124,895 ( 0.10%) .intern(kind, |kind| { 377,730 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 755,460 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 207,224,811 ( 0.18%) } . . #[inline(never)] 40,188,640 ( 0.03%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 35,165,060 ( 0.03%) .intern(kind, |kind| { 1,037,610 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 45,212,220 ( 0.04%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 2,380,328 ( 0.00%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 1,725,076 ( 0.00%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 345,084 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 345,084 ( 0.00%) self.data.get(&id.local_id) 1,383,856 ( 0.00%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 23,184 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 15,456 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 155,226 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 1,836,841 ( 0.00%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 155,226 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 444,822 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 296,548 ( 0.00%) match *qpath { 720,474 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 169,170 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 741,370 ( 0.00%) } . 4,207 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 31,703 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 4,207 ( 0.00%) } . 55,734 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 110,260 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 111,468 ( 0.00%) } . 105,324 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 105,324 ( 0.00%) } . 165,387 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 165,387 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 165,387 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 36,933 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 7,260 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 49,248 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 24,624 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 66,534 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 33,267 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 14,880 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 7,440 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 342,914 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 171,457 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 575,064 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 287,532 ( 0.00%) } . 2,320,194 ( 0.00%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 386,699 ( 0.00%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 1,933,495 ( 0.00%) } . 504,010 ( 0.00%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 504,010 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 1,008,020 ( 0.00%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 86,268 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 43,134 ( 0.00%) } . 182,621 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 182,621 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 365,242 ( 0.00%) } . 122,339 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 122,339 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 244,678 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 49,044 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 454,940 ( 0.00%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 448,665 ( 0.00%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 207,094 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 103,547 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 351,270 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 175,635 ( 0.00%) } . 203,169 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 406,338 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 406,338 ( 0.00%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 21,140 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 4,228 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 8,400 ( 0.00%) } . 26,145 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 5,229 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 14,504 ( 0.00%) } . 27,496 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 54,992 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 82,520 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 54,992 ( 0.00%) } . 127,494 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 169,992 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 109,480 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 33,491 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 56,420 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 28,210 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 112,178 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 56,089 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 34,382 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 17,191 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 40,332 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 50,415 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 18,024 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 9,012 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } . } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 33,480 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 16,740 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 15,456 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 7,728 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 18,024 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 9,012 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 957 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 319 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 638 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 9,012 ( 0.00%) &self.coercion_casts 9,012 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 58 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 4,213 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 7,976 ( 0.00%) pub fn is_identity(&self) -> bool { 15,952 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 7,976 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 22,346 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 10,653 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 542 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . 382 ( 0.00%) GenericArgKind::Const(ct) => match ct.val { 360 ( 0.00%) ty::ConstKind::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 120 ( 0.00%) assert_eq!(debruijn, ty::INNERMOST); . cvar == b . } . _ => false, . }, . } . }) . } . } 15,952 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 25,278 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 106,086 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 375,800 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 150,320 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 300,640 ( 0.00%) } . 27,603 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 9,201 ( 0.00%) self.arena.alloc(Steal::new(thir)) 36,804 ( 0.00%) } . 184,015 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 36,803 ( 0.00%) self.arena.alloc(Steal::new(mir)) 257,621 ( 0.00%) } . 36,804 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 9,201 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 46,005 ( 0.00%) } . 1,260 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 2,240 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 560 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. . pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. . let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); . let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) . } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 59,240 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 29,620 ( 0.00%) let attrs = self.get_attrs(def_id); 125,885 ( 0.00%) let get = |name| { 29,620 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); 464 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 232 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 116 ( 0.00%) ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 148,100 ( 0.00%) }; 44,430 ( 0.00%) ( 44,430 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 22,215 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 59,240 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 215,173 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 30,739 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 228,611 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 245,912 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 15,172,507 ( 0.01%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 19,507,509 ( 0.02%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 574 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 656 ( 0.00%) } . . /// Obtain the diagnostic item's name 171,325 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 195,800 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 1,401,981 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 1,602,264 ( 0.00%) } . 110,026 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 141,462 ( 0.00%) } . 73,853,577 ( 0.06%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 84,404,088 ( 0.07%) } . 490 ( 0.00%) pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 148,175 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 23,748 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } 400 ( 0.00%) } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. 12 ( 0.00%) pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath { . // Accessing the DefPath is ok, since it is part of DefPathHash. 18 ( 0.00%) if let Some(id) = id.as_local() { 18 ( 0.00%) self.untracked_resolutions.definitions.def_path(id) . } else { . self.untracked_resolutions.cstore.def_path(id) . } 18 ( 0.00%) } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 46,734 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 873 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 99,146 ( 0.00%) &*self.untracked_resolutions.cstore 49,573 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 14,625 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 63,897 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 18,024 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 27,036 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 9,012 ( 0.00%) self.sess.opts.borrowck_mode 36,048 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { 10,075,669 ( 0.01%) let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. 10,065,003 ( 0.01%) features.generic_const_exprs . } . . #[inline] . pub fn local_crate_exports_generics(self) -> bool { . debug_assert!(self.sess.opts.share_generics()); . 8 ( 0.00%) self.sess.crate_types().iter().any(|crate_type| { 18 ( 0.00%) match crate_type { . CrateType::Executable . | CrateType::Staticlib . | CrateType::ProcMacro . | CrateType::Cdylib => false, . . // FIXME rust-lang/rust#64319, rust-lang/rust#64872: . // We want to block export of generics from dylibs, . // but we must fix rust-lang/rust#65890 before we can -- line 1450 ---------------------------------------- -- line 1540 ---------------------------------------- . // FIXME(#42706) -- in some cases, we could do better here. . return true; . } . false . } . . /// Determines whether identifiers in the assembly have strict naming rules. . /// Currently, only NVPTX* targets need it. 118 ( 0.00%) pub fn has_strict_asm_symbol_naming(self) -> bool { 118 ( 0.00%) self.sess.target.arch.contains("nvptx") 236 ( 0.00%) } . . /// Returns `&'static core::panic::Location<'static>`. . pub fn caller_location_ty(self) -> Ty<'tcx> { . self.mk_imm_ref( . self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) . .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) . } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 24,090 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 17,520 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 39,420 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 19,710 ( 0.00%) } . 245 ( 0.00%) pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit 280 ( 0.00%) } . 7,708,694 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 8,809,936 ( 0.01%) } . 413 ( 0.00%) pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit 472 ( 0.00%) } . 7,756 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 8,864 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1614 ---------------------------------------- . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option; . } . . macro_rules! nop_lift { . ($set:ident; $ty:ty => $lifted:ty) => { . impl<'a, 'tcx> Lift<'tcx> for $ty { . type Lifted = $lifted; . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { 88 ( 0.00%) if tcx.interners.$set.contains_pointer_to(&Interned(self)) { . Some(unsafe { mem::transmute(self) }) . } else { . None . } . } . } . }; . } -- line 1630 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 2 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 920,170 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 3,769,890 ( 0.00%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1791 ---------------------------------------- . . /// Allows access to the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with_context(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 24 ( 0.00%) with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls"))) . } . . /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument . /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime . /// as the `TyCtxt` passed in. . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 1,818,310 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 1,803,320 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 23,026,403 ( 0.02%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 688,204 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 4,897,809 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 229,372 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 41,887,837 ( 0.04%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 362,103 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 11,765,836 ( 0.01%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 89,823 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 92,408,534 ( 0.08%) pub fn $method(self, v: $ty) -> &'tcx $ty { 66,750,992 ( 0.06%) self.interners.$name.intern(v, |v| { 19,028 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 103,949,892 ( 0.09%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 418,617,214 ( 0.36%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 376,531,758 ( 0.32%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2129 ---------------------------------------- . /// unsafe. . pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { . assert_eq!(sig.unsafety(), hir::Unsafety::Normal); . self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig })) . } . . /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name` . /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`. 57,876 ( 0.00%) pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool { . self.super_traits_of(trait_def_id).any(|trait_did| { . self.associated_items(trait_did) . .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did) . .is_some() . }) 43,407 ( 0.00%) } . . /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally) . /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used . /// to identify which traits may define a given associated type to help avoid cycle errors. . /// Returns a `DefId` iterator. . fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator + 'tcx { . let mut set = FxHashSet::default(); 9,646 ( 0.00%) let mut stack = vec![trait_def_id]; . . set.insert(trait_def_id); . 43,407 ( 0.00%) iter::from_fn(move || -> Option { 101,700 ( 0.00%) let trait_did = stack.pop()?; 50,850 ( 0.00%) let generic_predicates = self.super_predicates_of(trait_did); . . for (predicate, _) in generic_predicates.predicates { 244,692 ( 0.00%) if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() { 128,778 ( 0.00%) if set.insert(data.def_id()) { . stack.push(data.def_id()); . } . } . } . . Some(trait_did) . }) . } -- line 2169 ---------------------------------------- -- line 2188 ---------------------------------------- . self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) . } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 1,003,064 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 151,301,561 ( 0.13%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 54,601,835 ( 0.05%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 419,803,576 ( 0.36%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 48,200,054 ( 0.04%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 419,803,576 ( 0.36%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 877 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 877 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 7,621 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 7,621 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { 714 ( 0.00%) match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } 714 ( 0.00%) } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 1,946 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . -- line 2259 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 17,347 ( 0.00%) pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { . self.mk_ty(Array(ty, ty::Const::from_usize(self, n))) 18,312 ( 0.00%) } . . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { 6,468 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 10,530 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 92,326 ( 0.00%) iter.intern_with(|ts| { 37,235 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 108,245 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 82,764 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 3,339 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { 24 ( 0.00%) if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 5,890 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 769,178 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 2432 ---------------------------------------- . . #[inline] . pub fn mk_ty_infer(self, it: InferTy) -> Ty<'tcx> { . self.mk_ty(Infer(it)) . } . . #[inline] . pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> &'tcx ty::Const<'tcx> { 336,238 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(ic), ty }) . } . . #[inline] . pub fn mk_ty_param(self, index: u32, name: Symbol) -> Ty<'tcx> { . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 38,031 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 470,708 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 320,452 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 47,304 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 107,854 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { 21,732 ( 0.00%) self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 470,708 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 6,452 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 6,452 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 12,904 ( 0.00%) } . 21 ( 0.00%) pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { 63 ( 0.00%) self.mk_place_elem(place, PlaceElem::Deref) 42 ( 0.00%) } . 495 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 495 ( 0.00%) self.mk_place_elem( . place, 990 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 990 ( 0.00%) } . . pub fn mk_place_downcast_unnamed( . self, . place: Place<'tcx>, . variant_index: VariantIdx, . ) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index)) . } -- line 2496 ---------------------------------------- -- line 2497 ---------------------------------------- . . pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Index(index)) . } . . /// This method copies `Place`'s projection, add an element and reintern it. Should not be used . /// to build a full `Place` it's just a convenient way to grab a projection and modify it in . /// flight. 63,594 ( 0.00%) pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } 70,660 ( 0.00%) } . 18,396 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 2,628 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 70 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 10,512 ( 0.00%) self._intern_poly_existential_predicates(eps) 21,024 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 459,747 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 434,432 ( 0.00%) self._intern_predicates(preds) . } 76,816 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 462,941 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 306 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 91,444,405 ( 0.08%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 20,026,616 ( 0.02%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 104,582 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 58,740 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 665,403 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 497,366 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 16,824,364 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 33,540,904 ( 0.03%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 25,144 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 6,236 ( 0.00%) c_variadic, 7,748 ( 0.00%) unsafety, 9,448 ( 0.00%) abi, 1,880 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 10,492 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 84 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 18,919 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 56,265,298 ( 0.05%) iter.intern_with(|xs| self.intern_substs(xs)) . } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 45,626 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 191,458 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 382,916 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 100,645,369 ( 0.09%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 1,369,242 ( 0.00%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 1,369,242 ( 0.00%) let hir = self.hir(); . loop { 3,011,721 ( 0.00%) if id == bound { . return bound; . } . 4,076,797 ( 0.00%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 2,424,903 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 1,956,060 ( 0.00%) } . 77,104 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 405,832 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 30,100 ( 0.00%) let next = self.hir().get_parent_node(id); 90,300 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 77,104 ( 0.00%) } . 980 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 13,606 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 3,226 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 560 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 89,705 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 25,630 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 25,630 ( 0.00%) Some(&*candidates) 102,520 ( 0.00%) } . 111,594 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 143,478 ( 0.00%) } . 18,324 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 889 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 16,288 ( 0.00%) } . 260,827 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 335,349 ( 0.00%) } . 317,313 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 317,313 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 1,660 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 166 ( 0.00%) if self.is_const_fn_raw(def_id) { 32 ( 0.00%) match self.lookup_const_stability(def_id) { 60 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. 8 ( 0.00%) self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 1,494 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 175,808 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 486,638,782 ( 0.42%) E::intern_with(self, f) 169,902 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 110,459,723 ( 0.09%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 39,626,950 ( 0.03%) match iter.size_hint() { . (0, Some(0)) => { 12 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 155 ( 0.00%) assert!(iter.next().is_none()); 311,767 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 1,723 ( 0.00%) assert!(iter.next().is_none()); 315,396 ( 0.00%) f(&[t0, t1]) . } 18,144 ( 0.00%) _ => f(&iter.collect::>()), . } 10,477,617 ( 0.01%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 178,736 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 752 ( 0.00%) f(&iter.cloned().collect::>()) 143,666 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 172,664,047 ( 0.15%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 116,255,184 ( 0.10%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 7,830 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 13,459,140 ( 0.01%) f(&[t0]) . } . (2, Some(2)) => { 2,132 ( 0.00%) let t0 = iter.next().unwrap()?; 2,132 ( 0.00%) let t1 = iter.next().unwrap()?; 3,198 ( 0.00%) assert!(iter.next().is_none()); 496,128 ( 0.00%) f(&[t0, t1]) . } 1,271,009 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 194,291,682 ( 0.17%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 1,818,310 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 83 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = 81 ( 0.00%) |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 125,592 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 162,538,110 ( 0.14%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sharded.rs -------------------------------------------------------------------------------- Ir -- line 31 ---------------------------------------- . fn default() -> Self { . Self::new(T::default) . } . } . . impl Sharded { . #[inline] . pub fn new(mut value: impl FnMut() -> T) -> Self { 2 ( 0.00%) Sharded { shards: [(); SHARDS].map(|()| CacheAligned(Lock::new(value()))) } . } . . /// The shard is selected by hashing `val` with `FxHasher`. . #[inline] . pub fn get_shard_by_value(&self, val: &K) -> &Lock { . if SHARDS == 1 { &self.shards[0].0 } else { self.get_shard_by_hash(make_hash(val)) } . } . . #[inline] . pub fn get_shard_by_hash(&self, hash: u64) -> &Lock { . &self.shards[get_shard_index_by_hash(hash)].0 . } . . #[inline] . pub fn get_shard_by_index(&self, i: usize) -> &Lock { 1,803,320 ( 0.00%) &self.shards[i].0 . } . . pub fn lock_shards(&self) -> Vec> { . (0..SHARDS).map(|i| self.shards[i].0.lock()).collect() . } . . pub fn try_lock_shards(&self) -> Option>> { . (0..SHARDS).map(|i| self.shards[i].0.try_lock()).collect() -- line 63 ---------------------------------------- -- line 79 ---------------------------------------- . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash(value); . let mut shard = self.get_shard_by_hash(hash).lock(); . let entry = shard.raw_entry_mut().from_key_hashed_nocheck(hash, value); . . match entry { 41,588,029 ( 0.04%) RawEntryMut::Occupied(e) => *e.key(), . RawEntryMut::Vacant(e) => { . let v = make(); . e.insert_hashed_nocheck(hash, v, ()); . v . } . } . } . -- line 95 ---------------------------------------- -- line 99 ---------------------------------------- . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash(&value); . let mut shard = self.get_shard_by_hash(hash).lock(); . let entry = shard.raw_entry_mut().from_key_hashed_nocheck(hash, &value); . . match entry { 39,217,719 ( 0.03%) RawEntryMut::Occupied(e) => *e.key(), . RawEntryMut::Vacant(e) => { 2,073,369 ( 0.00%) let v = make(value); . e.insert_hashed_nocheck(hash, v, ()); . v . } . } 7,852 ( 0.00%) } . } . . pub trait IntoPointer { . /// Returns a pointer which outlives `self`. . fn into_pointer(&self) -> *const (); . } . . impl ShardedHashMap { 110 ( 0.00%) pub fn contains_pointer_to(&self, value: &T) -> bool { . let hash = make_hash(&value); . let shard = self.get_shard_by_hash(hash).lock(); . let value = value.into_pointer(); 23 ( 0.00%) shard.raw_entry().from_hash(hash, |entry| entry.into_pointer() == value).is_some() 110 ( 0.00%) } . } . . #[inline] . fn make_hash(val: &K) -> u64 { 118,795,228 ( 0.10%) let mut state = FxHasher::default(); 34,582,085 ( 0.03%) val.hash(&mut state); . state.finish() . } . . /// Get a shard with a pre-computed hash value. If `get_shard_by_value` is . /// ever used in combination with `get_shard_by_hash` on a single `Sharded` . /// instance, then `hash` must be computed with `FxHasher`. Otherwise, . /// `hash` can be computed with any hasher, so long as that hasher is used . /// consistently for each `Sharded` instance. -- line 142 ---------------------------------------- 38,056,288 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts/kind.rs -------------------------------------------------------------------------------- Ir -- line 7 ---------------------------------------- . use crate::ty::{self, TyCtxt, TypeFoldable}; . use rustc_errors::ErrorReported; . use rustc_hir::def_id::DefId; . use rustc_macros::HashStable; . use rustc_target::abi::Size; . . use super::ScalarInt; . /// An unevaluated, potentially generic, constant. 7,745 ( 0.00%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)] . #[derive(Hash, HashStable)] . pub struct Unevaluated<'tcx, P = Option> { . pub def: ty::WithOptConstParam, 50,162,052 ( 0.04%) pub substs: SubstsRef<'tcx>, 30,100,409 ( 0.03%) pub promoted: P, . } . . impl<'tcx> Unevaluated<'tcx> { . #[inline] . pub fn shrink(self) -> Unevaluated<'tcx, ()> { . debug_assert_eq!(self.promoted, None); 33,412 ( 0.00%) Unevaluated { def: self.def, substs: self.substs, promoted: () } . } . } . . impl<'tcx> Unevaluated<'tcx, ()> { . #[inline] . pub fn expand(self) -> Unevaluated<'tcx> { . Unevaluated { def: self.def, substs: self.substs, promoted: None } . } -- line 35 ---------------------------------------- -- line 38 ---------------------------------------- . impl<'tcx, P: Default> Unevaluated<'tcx, P> { . #[inline] . pub fn new(def: ty::WithOptConstParam, substs: SubstsRef<'tcx>) -> Unevaluated<'tcx, P> { . Unevaluated { def, substs, promoted: Default::default() } . } . } . . /// Represents a constant in Rust. 170,791,902 ( 0.15%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable)] 51,828,243 ( 0.04%) #[derive(Hash, HashStable)] . pub enum ConstKind<'tcx> { . /// A const generic parameter. 214,110 ( 0.00%) Param(ty::ParamConst), . . /// Infer the value of the const. . Infer(InferConst<'tcx>), . . /// Bound const variable, used only when preparing a trait query. 4,746 ( 0.00%) Bound(ty::DebruijnIndex, ty::BoundVar), . . /// A placeholder const - universally quantified higher-ranked const. . Placeholder(ty::PlaceholderConst<'tcx>), . . /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other . /// variants when the code is monomorphic enough for that. . Unevaluated(Unevaluated<'tcx>), . . /// Used to hold computed value. 20,305,090 ( 0.02%) Value(ConstValue<'tcx>), . . /// A placeholder for a const which could not be computed; this is . /// propagated to avoid useless error messages. . Error(ty::DelaySpanBugEmitted), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(ConstKind<'_>, 40); . . impl<'tcx> ConstKind<'tcx> { . #[inline] . pub fn try_to_value(self) -> Option> { 213,826 ( 0.00%) if let ConstKind::Value(val) = self { Some(val) } else { None } . } . . #[inline] . pub fn try_to_scalar(self) -> Option> { . self.try_to_value()?.try_to_scalar() . } . . #[inline] . pub fn try_to_scalar_int(self) -> Option { . Some(self.try_to_value()?.try_to_scalar()?.assert_int()) . } . . #[inline] . pub fn try_to_bits(self, size: Size) -> Option { 54,357 ( 0.00%) self.try_to_scalar_int()?.to_bits(size).ok() . } . . #[inline] . pub fn try_to_bool(self) -> Option { 6,594 ( 0.00%) self.try_to_scalar_int()?.try_into().ok() . } . . #[inline] . pub fn try_to_machine_usize(self, tcx: TyCtxt<'tcx>) -> Option { 23,408 ( 0.00%) self.try_to_value()?.try_to_machine_usize(tcx) 528 ( 0.00%) } . } . . /// An inference variable for a const, for use in const generics. 4,270,999 ( 0.00%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Hash)] . #[derive(HashStable)] . pub enum InferConst<'tcx> { . /// Infer the value of the const. . Var(ty::ConstVid<'tcx>), . /// A fresh const variable. See `infer::freshen` for more details. . Fresh(u32), . } . . impl<'tcx> ConstKind<'tcx> { . #[inline] . /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the . /// unevaluated constant. 6,426 ( 0.00%) pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Self { 19,367 ( 0.00%) self.try_eval(tcx, param_env).and_then(Result::ok).map_or(self, ConstKind::Value) 5,712 ( 0.00%) } . . #[inline] . /// Tries to evaluate the constant if it is `Unevaluated`. If that isn't possible or necessary . /// return `None`. 160,046,355 ( 0.14%) pub(super) fn try_eval( . self, . tcx: TyCtxt<'tcx>, . param_env: ParamEnv<'tcx>, . ) -> Option, ErrorReported>> { 60,124,184 ( 0.05%) if let ConstKind::Unevaluated(unevaluated) = self { . use crate::mir::interpret::ErrorHandled; . . // HACK(eddyb) this erases lifetimes even though `const_eval_resolve` . // also does later, but we want to do it before checking for . // inference variables. . // Note that we erase regions *before* calling `with_reveal_all_normalized`, . // so that we don't try to invoke this query with . // any region variables. 40,113,328 ( 0.03%) let param_env_and = tcx . .erase_regions(param_env) . .with_reveal_all_normalized(tcx) . .and(tcx.erase_regions(unevaluated)); . . // HACK(eddyb) when the query key would contain inference variables, . // attempt using identity substs and `ParamEnv` instead, that will succeed . // when the expression doesn't depend on any parameters. . // FIXME(eddyb, skinny121) pass `InferCtxt` into here when it's available, so that . // we can call `infcx.const_eval_resolve` which handles inference variables. 10,028,332 ( 0.01%) let param_env_and = if param_env_and.needs_infer() { . tcx.param_env(unevaluated.def.did).and(ty::Unevaluated { . def: unevaluated.def, . substs: InternalSubsts::identity_for_item(tcx, unevaluated.def.did), . promoted: unevaluated.promoted, . }) . } else { . param_env_and . }; . . // FIXME(eddyb) maybe the `const_eval_*` methods should take . // `ty::ParamEnvAnd` instead of having them separate. . let (param_env, unevaluated) = param_env_and.into_parts(); . // try to resolve e.g. associated constants to their definition on an impl, and then . // evaluate the const. 180,511,144 ( 0.16%) match tcx.const_eval_resolve(param_env, unevaluated, None) { . // NOTE(eddyb) `val` contains no lifetimes/types/consts, . // and we use the original type, so nothing from `substs` . // (which may be identity substs, see above), . // can leak through `val` into the const we return. 50,141,660 ( 0.04%) Ok(val) => Some(Ok(val)), . Err(ErrorHandled::TooGeneric | ErrorHandled::Linted) => None, . Err(ErrorHandled::Reported(e)) => Some(Err(e)), . } . } else { 1,114 ( 0.00%) None . } 160,046,912 ( 0.14%) } . } 239,814,242 ( 0.21%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . use rustc_target::spec::abi; . use std::borrow::Cow; . use std::cmp::Ordering; . use std::marker::PhantomData; . use std::ops::Range; . use ty::util::IntTypeExt; . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 10 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 11,681 ( 0.00%) pub ty: Ty<'tcx>, 58,405 ( 0.00%) pub mutbl: hir::Mutability, . } . . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . /// A "free" region `fr` can be interpreted as "some region . /// at least as big as the scope `fr.scope`". . pub struct FreeRegion { 148,460 ( 0.00%) pub scope: DefId, 303,794 ( 0.00%) pub bound_region: BoundRegionKind, . } . 3,936,922 ( 0.00%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] 42 ( 0.00%) #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 146,329 ( 0.00%) BrAnon(u32), . . /// Named region parameters for functions (a in &'a T) . /// . /// The `DefId` is needed to distinguish free regions in . /// the event of shadowing. 740 ( 0.00%) BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 6,238 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 1,091,312 ( 0.00%) pub var: BoundVar, 983,894 ( 0.00%) pub kind: BoundRegionKind, . } . . impl BoundRegionKind { . pub fn is_named(&self) -> bool { . match *self { . BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime, . _ => false, . } . } . } . . /// Defines the kinds of types. . /// . /// N.B., if you change this, you'll probably want to change the corresponding . /// AST structure in `rustc_ast/src/ast.rs` as well. 607,301,673 ( 0.52%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] 6,077 ( 0.00%) #[derive(HashStable)] . #[rustc_diagnostic_item = "TyKind"] . pub enum TyKind<'tcx> { . /// The primitive boolean type. Written as `bool`. . Bool, . . /// The primitive character type; holds a Unicode scalar value . /// (a non-surrogate code point). Written as `char`. . Char, -- line 90 ---------------------------------------- -- line 99 ---------------------------------------- . Float(ty::FloatTy), . . /// Algebraic data types (ADT). For example: structures, enumerations and unions. . /// . /// InternalSubsts here, possibly against intuition, *may* contain `Param`s. . /// That is, even after substitution it is possible that there are type . /// variables. This happens when the `Adt` corresponds to an ADT . /// definition and not a concrete use of it. 198,739,521 ( 0.17%) Adt(&'tcx AdtDef, SubstsRef<'tcx>), . . /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. . Foreign(DefId), . . /// The pointee of a string slice. Written as `str`. . Str, . . /// An array with the given length. Written as `[T; n]`. 665,404 ( 0.00%) Array(Ty<'tcx>, &'tcx ty::Const<'tcx>), . . /// The pointee of an array slice. Written as `[T]`. . Slice(Ty<'tcx>), . . /// A raw pointer. Written as `*mut T` or `*const T` . RawPtr(TypeAndMut<'tcx>), . . /// A reference; a pointer with an associated lifetime. Written as . /// `&'a mut T` or `&'a T`. 12,636,656 ( 0.01%) Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), . . /// The anonymous type of a function declaration/definition. Each . /// function has a unique type, which is output (for a function . /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. . /// . /// For example the type of `bar` here: . /// . /// ```rust -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . /// . /// ```rust . /// fn foo() -> i32 { 1 } . /// let bar: fn() -> i32 = foo; . /// ``` . FnPtr(PolyFnSig<'tcx>), . . /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. 106,303 ( 0.00%) Dynamic(&'tcx List>>, ty::Region<'tcx>), . . /// The anonymous type of a closure. Used to represent the type of . /// `|a| a`. . Closure(DefId, SubstsRef<'tcx>), . . /// The anonymous type of a generator. Used to represent the type of . /// `|a| yield a`. . Generator(DefId, SubstsRef<'tcx>, hir::Movability), -- line 159 ---------------------------------------- -- line 180 ---------------------------------------- . /// The substitutions are for the generics of the function in question. . /// After typeck, the concrete type can be found in the `types` map. . Opaque(DefId, SubstsRef<'tcx>), . . /// A type parameter; for example, `T` in `fn f(x: T) {}`. . Param(ParamTy), . . /// Bound type variable, used only when preparing a trait query. 59,507 ( 0.00%) Bound(ty::DebruijnIndex, BoundTy), . . /// A placeholder type - universally quantified higher-ranked type. . Placeholder(ty::PlaceholderType), . . /// A type variable used during type checking. . Infer(InferTy), . . /// A placeholder for a type which could not be computed; this is -- line 196 ---------------------------------------- -- line 330 ---------------------------------------- . pub closure_kind_ty: T, . pub closure_sig_as_fn_ptr_ty: T, . pub tupled_upvars_ty: T, . } . . impl<'tcx> ClosureSubsts<'tcx> { . /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` . /// for the closure parent, alongside additional closure-specific components. 189 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 378 ( 0.00%) parts.parent_substs.iter().copied().chain( 756 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 378 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 3,147 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 24,736 ( 0.00%) [ 6,559 ( 0.00%) ref parent_substs @ .., 7,147 ( 0.00%) closure_kind_ty, 3,321 ( 0.00%) closure_sig_as_fn_ptr_ty, 5,051 ( 0.00%) tupled_upvars_ty, 12,588 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 9,441 ( 0.00%) } . . /// Returns `true` only if enough of the synthetic types are known to . /// allow using all of the methods on `ClosureSubsts` without panicking. . /// . /// Used primarily by `ty::print::pretty` to be able to handle closure . /// types that haven't had their synthetic types substituted in. 4 ( 0.00%) pub fn is_valid(self) -> bool { 8 ( 0.00%) self.substs.len() >= 3 8 ( 0.00%) && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) 8 ( 0.00%) } . . /// Returns the substitutions of the closure's parent. . pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { . self.split().parent_substs . } . . /// Returns an iterator over the list of types of captured paths by the closure. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] 546 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 1,844 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 716 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() 364 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 14,246 ( 0.00%) self.split().tupled_upvars_ty.expect_ty() . } . . /// Returns the closure kind for this closure; may return a type . /// variable during inference. To get the closure kind during . /// inference, use `infcx.closure_kind(substs)`. 1,853 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 3,706 ( 0.00%) } . . /// Returns the `fn` pointer type representing the closure signature for this . /// closure. . // FIXME(eddyb) this should be unnecessary, as the shallowly resolved . // type is known at the time of the creation of `ClosureSubsts`, . // see `rustc_typeck::check::closure`. . pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { . self.split().closure_sig_as_fn_ptr_ty.expect_ty() . } . . /// Returns the closure kind for this closure; only usable outside . /// of an inference context, because in that context we know that . /// there are no type variables. . /// . /// If you have an inference context, use `infcx.closure_kind()`. 63 ( 0.00%) pub fn kind(self) -> ty::ClosureKind { 63 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 126 ( 0.00%) } . . /// Extracts the signature from the closure. 1,615 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 3,230 ( 0.00%) match ty.kind() { 6,460 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 4,845 ( 0.00%) } . } . . /// Similar to `ClosureSubsts`; see the above documentation for more. . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GeneratorSubsts<'tcx> { . pub substs: SubstsRef<'tcx>, . } . -- line 448 ---------------------------------------- -- line 676 ---------------------------------------- . } . . impl<'tcx> UpvarSubsts<'tcx> { . /// Returns an iterator over the list of types of captured paths by the closure/generator. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] . pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 504 ( 0.00%) let tupled_tys = match self { 693 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 1,134 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 945 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() . } . . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 882 ( 0.00%) match self { 1,058 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . } . } . } . . /// An inline const is modeled like . /// . /// const InlineConst<'l0...'li, T0...Tj, R>: R; -- line 710 ---------------------------------------- -- line 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 76,005 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] 87,162 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub enum ExistentialPredicate<'tcx> { . /// E.g., `Iterator`. . Trait(ExistentialTraitRef<'tcx>), . /// E.g., `Iterator::Item = T`. . Projection(ExistentialProjection<'tcx>), . /// E.g., `Send`. 18 ( 0.00%) AutoTrait(DefId), . } . . impl<'tcx> ExistentialPredicate<'tcx> { . /// Compares via an ordering that will not change if modules are reordered or other changes are . /// made to the tree. In particular, this ordering is preserved across incremental compilations. 70 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 80 ( 0.00%) match (*self, *other) { . (Trait(_), Trait(_)) => Ordering::Equal, . (Projection(ref a), Projection(ref b)) => { . tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) . } . (AutoTrait(ref a), AutoTrait(ref b)) => { . tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b)) . } . (Trait(_), _) => Ordering::Less, . (Projection(_), Trait(_)) => Ordering::Greater, . (Projection(_), _) => Ordering::Less, . (AutoTrait(_), _) => Ordering::Greater, . } 84 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { 9,666 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; 5,370 ( 0.00%) match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) . } . ExistentialPredicate::Projection(p) => { . self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) . } . ExistentialPredicate::AutoTrait(did) => { . let trait_ref = self.rebind(ty::TraitRef { . def_id: did, . substs: tcx.mk_substs_trait(self_ty, &[]), . }); . trait_ref.without_const().to_predicate(tcx) . } . } 8,592 ( 0.00%) } . } . . impl<'tcx> List>> { . /// Returns the "principal `DefId`" of this set of existential predicates. . /// . /// A Rust trait object type consists (in addition to a lifetime bound) . /// of a set of trait bounds, which are separated into any number . /// of auto-trait bounds, and at most one non-auto-trait bound. The -- line 826 ---------------------------------------- -- line 839 ---------------------------------------- . /// are the set `{Sync}`. . /// . /// It is also possible to have a "trivial" trait object that . /// consists only of auto traits, with no principal - for example, . /// `dyn Send + Sync`. In that case, the set of auto-trait bounds . /// is `{Send, Sync}`, while there is no principal. These trait objects . /// have a "trivial" vtable consisting of just the size, alignment, . /// and destructor. 10 ( 0.00%) pub fn principal(&self) -> Option>> { 3,274 ( 0.00%) self[0] 3,244 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, 40 ( 0.00%) }) . .transpose() 30 ( 0.00%) } . 1,074 ( 0.00%) pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) 2,148 ( 0.00%) } . . #[inline] . pub fn projection_bounds<'a>( . &'a self, . ) -> impl Iterator>> + 'a { . self.iter().filter_map(|predicate| { . predicate 24 ( 0.00%) .map_bound(|pred| match pred { . ExistentialPredicate::Projection(projection) => Some(projection), . _ => None, . }) . .transpose() . }) . } . . #[inline] -- line 874 ---------------------------------------- -- line 886 ---------------------------------------- . /// T: Foo . /// . /// This would be represented by a trait-reference where the `DefId` is the . /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, . /// and `U` as parameter 1. . /// . /// Trait references also appear in object types like `Foo`, but in . /// that case the `Self` parameter is absent from the substitutions. 53,887 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 359,371,278 ( 0.31%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 79,972 ( 0.00%) pub def_id: DefId, 146,579,540 ( 0.13%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 41,884 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 167,536 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 1,854 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 824 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 1,236 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 1,648 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 23,216 ( 0.00%) pub fn from_method( . tcx: TyCtxt<'tcx>, . trait_id: DefId, . substs: SubstsRef<'tcx>, . ) -> ty::TraitRef<'tcx> { . let defs = tcx.generics_of(trait_id); . 2,902 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 31,922 ( 0.00%) } . } . . pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>; . . impl<'tcx> PolyTraitRef<'tcx> { . pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> { . self.map_bound_ref(|tr| tr.self_ty()) . } . . pub fn def_id(&self) -> DefId { 904,584 ( 0.00%) self.skip_binder().def_id 301,528 ( 0.00%) } . 203,320 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 406,640 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 203,320 ( 0.00%) } . } . . /// An existential reference to a trait, where `Self` is erased. . /// For example, the trait object `Trait<'a, 'b, X, Y>` is: . /// . /// exists T. T: Trait<'a, 'b, X, Y> . /// . /// The substitutions don't include the erased `Self`, only trait . /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). 68 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 44,108 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 5,248 ( 0.00%) pub def_id: DefId, 47,970 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { 16 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. . trait_ref.substs.type_at(0); . . ty::ExistentialTraitRef { . def_id: trait_ref.def_id, . substs: tcx.intern_substs(&trait_ref.substs[1..]), . } 16 ( 0.00%) } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. . pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> { . // otherwise the escaping vars would be captured by the binder . // debug_assert!(!self_ty.has_escaping_bound_vars()); -- line 985 ---------------------------------------- -- line 994 ---------------------------------------- . pub fn def_id(&self) -> DefId { . self.skip_binder().def_id . } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. 12 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> { 20 ( 0.00%) self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) 16 ( 0.00%) } . } . 353,561 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 100 ( 0.00%) #[derive(HashStable)] . pub enum BoundVariableKind { . Ty(BoundTyKind), . Region(BoundRegionKind), . Const, . } . . /// Binder is a binder for higher-ranked lifetimes or types. It is part of the . /// compiler's representation for things like `for<'a> Fn(&'a isize)` . /// (which would be represented by the type `PolyTraitRef == . /// Binder<'tcx, TraitRef>`). Note that when we instantiate, . /// erase, or otherwise "discharge" these bound vars, we change the . /// type from `Binder<'tcx, T>` to just `T` (see . /// e.g., `liberate_late_bound_regions`). . /// . /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. 141,318 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 19,568,228 ( 0.02%) pub struct Binder<'tcx, T>(T, &'tcx List); . . impl<'tcx, T> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . /// Wraps `value` in a binder, asserting that `value` does not . /// contain any bound vars that would be bound by the . /// binder. This is commonly used to 'inject' a value T into a . /// different binding level. 274,025 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 1,535,629 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 4,622,268 ( 0.00%) Binder(value, ty::List::empty()) 273,471 ( 0.00%) } . . pub fn bind_with_vars(value: T, vars: &'tcx List) -> Binder<'tcx, T> { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(vars); . value.visit_with(&mut validator); . } 19,729,314 ( 0.02%) Binder(value, vars) . } . } . . impl<'tcx, T> Binder<'tcx, T> { . /// Skips the binder and returns the "bound" value. This is a . /// risky thing to do because it's easy to get confused about . /// De Bruijn indices and the like. It is usually better to . /// discharge the binder using `no_bound_vars` or -- line 1053 ---------------------------------------- -- line 1059 ---------------------------------------- . /// accounting. . /// . /// Some examples where `skip_binder` is reasonable: . /// . /// - extracting the `DefId` from a PolyTraitRef; . /// - comparing the self type of a PolyTraitRef to see if it is equal to . /// a type parameter `X`, since the type `X` does not reference any regions . pub fn skip_binder(self) -> T { 161,002,539 ( 0.14%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 1,064,063 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 531,487 ( 0.00%) Binder(&self.0, self.1) . } . . pub fn map_bound_ref_unchecked(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . let value = f(&self.0); . Binder(value, self.1) -- line 1083 ---------------------------------------- -- line 1085 ---------------------------------------- . . pub fn map_bound_ref>(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . self.as_ref().map_bound(f) . } . 1,512 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 1,011,562 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 6,949,345 ( 0.01%) Binder(value, self.1) 1,512 ( 0.00%) } . . pub fn try_map_bound, E>(self, f: F) -> Result, E> . where . F: FnOnce(T) -> Result, . { . let value = f(self.0)?; . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 1,295,180 ( 0.00%) Ok(Binder(value, self.1)) . } . . /// Wraps a `value` in a binder, using the same bound variables as the . /// current `Binder`. This should not be used if the new value *changes* . /// the bound variables. Note: the (old or new) value itself does not . /// necessarily need to *name* all the bound variables. . /// . /// This currently doesn't do anything different than `bind`, because we -- line 1122 ---------------------------------------- -- line 1126 ---------------------------------------- . pub fn rebind(&self, value: U) -> Binder<'tcx, U> . where . U: TypeFoldable<'tcx>, . { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.bound_vars()); . value.visit_with(&mut validator); . } 3,953,939 ( 0.00%) Binder(value, self.1) . } . . /// Unwraps and returns the value within, but only if it contains . /// no bound vars at all. (In other words, if this binder -- . /// and indeed any enclosing binder -- doesn't bind anything at . /// all.) Otherwise, returns `None`. . /// . /// (One could imagine having a method that just unwraps a single -- line 1142 ---------------------------------------- -- line 1143 ---------------------------------------- . /// binder, but permits late-bound vars bound by enclosing . /// binders, but that would require adjusting the debruijn . /// indices, and given the shallow binding structure we often use, . /// would not be that useful.) . pub fn no_bound_vars(self) -> Option . where . T: TypeFoldable<'tcx>, . { 9,572,071 ( 0.01%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 1,350 ( 0.00%) } . . /// Splits the contents into two things that share the same binder . /// level as the original, returning two distinct binders. . /// . /// `f` should consider bound regions at depth 1 to be free, and . /// anything it produces with bound regions at depth 1 will be . /// bound in the resulting return values. . pub fn split(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>) -- line 1160 ---------------------------------------- -- line 1170 ---------------------------------------- . pub fn transpose(self) -> Option> { . let bound_vars = self.1; . self.0.map(|v| Binder(v, bound_vars)) . } . } . . /// Represents the projection of an associated type. In explicit UFCS . /// form this would be written `>::N`. 32,915 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 24,805,924 ( 0.02%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 2,792,888 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The `DefId` of the `TraitItem` for the associated type `N`. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(item_def_id).container`. 8,976,885 ( 0.01%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 1,416,114 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 404,604 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 1,618,416 ( 0.00%) } . . /// Extracts the underlying trait reference and own substs from this projection. . /// For example, if this is a projection of `::Item<'a>`, . /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs 481,684 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 206,436 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 344,060 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 619,308 ( 0.00%) } . . /// Extracts the underlying trait reference from this projection. . /// For example, if this is a projection of `::Item`, . /// then this function would return a `T: Iterator` trait reference. . /// . /// WARNING: This will drop the substs for generic associated types . /// consider calling [Self::trait_ref_and_own_substs] to get those . /// as well. 1,819,026 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 202,114 ( 0.00%) let def_id = self.trait_def_id(tcx); 202,114 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 2,223,254 ( 0.00%) } . 400,768 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 1,202,304 ( 0.00%) self.substs.type_at(0) 801,536 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GenSig<'tcx> { . pub resume_ty: Ty<'tcx>, . pub yield_ty: Ty<'tcx>, . pub return_ty: Ty<'tcx>, . } -- line 1233 ---------------------------------------- -- line 1235 ---------------------------------------- . pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>; . . /// Signature of a function type, which we have arbitrarily . /// decided to use to refer to the input/output types. . /// . /// - `inputs`: is the list of arguments and their modes. . /// - `output`: is the return type. . /// - `c_variadic`: indicates whether this is a C-variadic function. 407,830 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 316,656 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 28,839 ( 0.00%) pub inputs_and_output: &'tcx List>, 299,923 ( 0.00%) pub c_variadic: bool, 62,419 ( 0.00%) pub unsafety: hir::Unsafety, 268,009 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 199,191 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 842,223 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 398,382 ( 0.00%) } . 125,925 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 920,382 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 251,850 ( 0.00%) } . . // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible . // method. . fn fake() -> FnSig<'tcx> { . FnSig { . inputs_and_output: List::empty(), . c_variadic: false, . unsafety: hir::Unsafety::Normal, -- line 1267 ---------------------------------------- -- line 1270 ---------------------------------------- . } . } . . pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; . . impl<'tcx> PolyFnSig<'tcx> { . #[inline] . pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> { 25,410 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 64,613 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.inputs()[index]) . } . pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List>> { . self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output) 3,864 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 37,561 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 7,726 ( 0.00%) self.skip_binder().c_variadic 3,863 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 39,232 ( 0.00%) self.skip_binder().unsafety 19,616 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 214,488 ( 0.00%) self.skip_binder().abi 53,622 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 18,272 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 8 ( 0.00%) #[derive(HashStable)] . pub struct ParamTy { 262,118 ( 0.00%) pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 18,320 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 9,160 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { 9,898 ( 0.00%) ParamTy::new(def.index, def.name) 4,949 ( 0.00%) } . . #[inline] . pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { . tcx.mk_ty_param(self.index, self.name) . } . } . . #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] . #[derive(HashStable)] . pub struct ParamConst { 214,110 ( 0.00%) pub index: u32, 182,748 ( 0.00%) pub name: Symbol, . } . . impl ParamConst { . pub fn new(index: u32, name: Symbol) -> ParamConst { . ParamConst { index, name } . } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamConst { -- line 1338 ---------------------------------------- -- line 1440 ---------------------------------------- . /// the inference variable is supposed to satisfy the relation . /// *for every value of the placeholder region*. To ensure that doesn't . /// happen, you can use `leak_check`. This is more clearly explained . /// by the [rustc dev guide]. . /// . /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ . /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 64,201,710 ( 0.06%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 370 ( 0.00%) pub enum RegionKind { . /// Region bound in a type or fn declaration which will be . /// substituted 'early' -- that is, at the same time when type . /// parameters are substituted. . ReEarlyBound(EarlyBoundRegion), . . /// Region bound in a function scope, which will be substituted when the . /// function is called. 1,966,060 ( 0.00%) ReLateBound(ty::DebruijnIndex, BoundRegion), . . /// When checking a function body, the types of all arguments and so forth . /// that refer to bound region parameters are modified to refer to free . /// region parameters. . ReFree(FreeRegion), . . /// Static data that has an "infinite" lifetime. Top in the region lattice. . ReStatic, -- line 1465 ---------------------------------------- -- line 1478 ---------------------------------------- . /// regions visible from `U`, but not less than regions not visible . /// from `U`. . ReEmpty(ty::UniverseIndex), . . /// Erased region, used by trait selection, in MIR and during codegen. . ReErased, . } . 45,844 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { 441,373 ( 0.00%) pub def_id: DefId, 445,395 ( 0.00%) pub index: u32, 273,448 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 46,509,474 ( 0.04%) pub index: u32, 46,489,245 ( 0.04%) pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } . } -- line 1505 ---------------------------------------- -- line 1513 ---------------------------------------- . rustc_index::newtype_index! { . pub struct BoundVar { .. } . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct BoundTy { . pub var: BoundVar, 59,507 ( 0.00%) pub kind: BoundTyKind, . } . 1,011,802 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundTyKind { . Anon, . Param(Symbol), . } . . impl From for BoundTy { . fn from(var: BoundVar) -> Self { -- line 1532 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 52,692 ( 0.00%) matches!(*self, ty::ReLateBound(..)) . } . . #[inline] . pub fn is_placeholder(&self) -> bool { . matches!(*self, ty::RePlaceholder(..)) . } . . #[inline] . pub fn bound_at_or_above_binder(&self, index: ty::DebruijnIndex) -> bool { 1,269,759 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 974,532 ( 0.00%) match *self { . ty::ReVar(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; . flags = flags | TypeFlags::HAS_RE_INFER; . } . ty::RePlaceholder(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; -- line 1651 ---------------------------------------- -- line 1669 ---------------------------------------- . ty::ReErased => { . flags = flags | TypeFlags::HAS_RE_ERASED; . } . } . . debug!("type_flags({:?}) = {:?}", self, flags); . . flags 144,698 ( 0.00%) } . . /// Given an early-bound or free region, returns the `DefId` where it was bound. . /// For example, consider the regions in this snippet of code: . /// . /// ``` . /// impl<'a> Foo { . /// ^^ -- early bound, declared on an impl . /// -- line 1685 ---------------------------------------- -- line 1713 ---------------------------------------- . . #[inline(always)] . pub fn flags(&self) -> TypeFlags { . self.flags . } . . #[inline] . pub fn is_unit(&self) -> bool { 18,538 ( 0.00%) match self.kind() { 4,441 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 305,226 ( 0.00%) matches!(self.kind(), Never) . } . . #[inline] . pub fn is_primitive(&self) -> bool { . self.kind().is_primitive() . } . . #[inline] -- line 1737 ---------------------------------------- -- line 1741 ---------------------------------------- . . #[inline] . pub fn is_ref(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_ty_var(&self) -> bool { 548,341 ( 0.00%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 866,300 ( 0.00%) match self.kind() { 57,526 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 567 ( 0.00%) matches!(self.kind(), Infer(_)) . } . . #[inline] . pub fn is_phantom_data(&self) -> bool { 18 ( 0.00%) if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false } . } . . #[inline] . pub fn is_bool(&self) -> bool { . *self.kind() == Bool . } . . /// Returns `true` if this type is a `str`. . #[inline] . pub fn is_str(&self) -> bool { . *self.kind() == Str . } . . #[inline] . pub fn is_param(&self, index: u32) -> bool { 9,247 ( 0.00%) match self.kind() { . ty::Param(ref data) => data.index == index, . _ => false, . } . } . . #[inline] . pub fn is_slice(&self) -> bool { . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 3,025 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { . match self.kind() { . Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 1,306 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 2,612 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => ty, . Str => tcx.mk_mach_uint(ty::UintTy::U8), . _ => bug!("`sequence_element_type` called on non-sequence value: {}", self), . } 1,306 ( 0.00%) } . . pub fn simd_size_and_type(&self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) { . match self.kind() { . Adt(def, substs) => { . assert!(def.repr.simd(), "`simd_size_and_type` called on non-SIMD type"); . let variant = def.non_enum_variant(); . let f0_ty = variant.fields[0].ty(tcx, substs); . -- line 1824 ---------------------------------------- -- line 1838 ---------------------------------------- . } . } . _ => bug!("`simd_size_and_type` called on invalid type"), . } . } . . #[inline] . pub fn is_region_ptr(&self) -> bool { 298 ( 0.00%) matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_mutable_ptr(&self) -> bool { . matches!( . self.kind(), . RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) . | Ref(_, _, hir::Mutability::Mut) -- line 1854 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 36,713 ( 0.00%) matches!(self.kind(), RawPtr(_)) . } . . /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer). . #[inline] . pub fn is_any_ptr(&self) -> bool { 254 ( 0.00%) self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr() . } . . #[inline] . pub fn is_box(&self) -> bool { 460,568 ( 0.00%) match self.kind() { 59,700 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. . pub fn boxed_ty(&self) -> Ty<'tcx> { . match self.kind() { . Adt(def, substs) if def.is_box() => substs.type_at(0), -- line 1889 ---------------------------------------- -- line 1891 ---------------------------------------- . } . } . . /// A scalar type is one that denotes an atomic datum, with no sub-components. . /// (A RawPtr is scalar because it represents a non-managed pointer, so its . /// contents are abstract to rustc.) . #[inline] . pub fn is_scalar(&self) -> bool { 8,984 ( 0.00%) matches!( 19,545 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) . ) . } . . /// Returns `true` if this type is a floating point type. . #[inline] . pub fn is_floating_point(&self) -> bool { 496 ( 0.00%) matches!(self.kind(), Float(_) | Infer(FloatVar(_))) . } . . #[inline] . pub fn is_trait(&self) -> bool { 6 ( 0.00%) matches!(self.kind(), Dynamic(..)) . } . . #[inline] . pub fn is_enum(&self) -> bool { 3,446 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum()) . } . . #[inline] . pub fn is_union(&self) -> bool { 48,008 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { 14,844 ( 0.00%) matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 29,867 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 49,614 ( 0.00%) matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_)) . } . . #[inline] . pub fn is_fresh_ty(&self) -> bool { . matches!(self.kind(), Infer(FreshTy(_))) . } . . #[inline] . pub fn is_fresh(&self) -> bool { 90,513 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] . pub fn is_numeric(&self) -> bool { . self.is_integral() || self.is_floating_point() . } . . #[inline] . pub fn is_signed(&self) -> bool { 30 ( 0.00%) matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { 7,080 ( 0.00%) matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] . pub fn has_concrete_skeleton(&self) -> bool { . !matches!(self.kind(), Param(_) | Infer(_) | Error(_)) . } . . /// Returns the type and mutability of `*ty`. . /// . /// The parameter `explicit` indicates if this is an *explicit* dereference. . /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. 71,027 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 454,411 ( 0.00%) match self.kind() { 4,802 ( 0.00%) Adt(def, _) if def.is_box() => { . Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 281,304 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), 5,872 ( 0.00%) RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 142,054 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { 18,235 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } 2,374 ( 0.00%) } . 724,176 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 362,088 ( 0.00%) match self.kind() { 271,566 ( 0.00%) FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), . FnPtr(f) => *f, . Error(_) => { . // ignore errors (#54954) . ty::Binder::dummy(FnSig::fake()) . } . Closure(..) => bug!( . "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", . ), . _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), . } 814,698 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 393 ( 0.00%) matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { . matches!(self.kind(), FnPtr(_)) . } . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 9,130 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 865 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 13,246 ( 0.00%) match self.kind() { 8,011 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 1,730 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 435 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 870 ( 0.00%) match self.kind() { 870 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 870 ( 0.00%) } . . /// If the type contains variants, returns the valid range of variant indices. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] . pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option> { . match self.kind() { . TyKind::Adt(adt, _) => Some(adt.variant_range()), -- line 2068 ---------------------------------------- -- line 2073 ---------------------------------------- . } . } . . /// If the type contains variants, returns the variant for `variant_index`. . /// Panics if `variant_index` is out of range. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] 1,980 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 5,286 ( 0.00%) match self.kind() { 1,870 ( 0.00%) TyKind::Adt(adt, _) if adt.variants.is_empty() => { . // This can actually happen during CTFE, see . // https://github.com/rust-lang/rust/issues/89765. . None . } 935 ( 0.00%) TyKind::Adt(adt, _) if adt.is_enum() => { . Some(adt.discriminant_for_variant(tcx, variant_index)) . } . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } 1,584 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 15,650 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 7,825 ( 0.00%) match self.kind() { 12,520 ( 0.00%) ty::Adt(adt, _) if adt.is_enum() => adt.repr.discr_type().to_ty(tcx), . ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), . . ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => { . let assoc_items = tcx.associated_item_def_ids( . tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), . ); . tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()])) . } -- line 2113 ---------------------------------------- -- line 2135 ---------------------------------------- . | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, . . ty::Bound(..) . | ty::Placeholder(_) . | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`discriminant_ty` applied to unexpected type: {:?}", self) . } . } 12,520 ( 0.00%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. . pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { . let tail = tcx.struct_tail_with_normalize(self, normalize); -- line 2151 ---------------------------------------- -- line 2200 ---------------------------------------- . /// function converts such a special type into the closure . /// kind. To go the other way, use . /// `tcx.closure_kind_ty(closure_kind)`. . /// . /// Note that during type checking, we use an inference variable . /// to represent the closure kind, because it has not yet been . /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`) . /// is complete, that type variable will be unified. 4,586 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 9,172 ( 0.00%) match self.kind() { 8,936 ( 0.00%) Int(int_ty) => match int_ty { . ty::IntTy::I8 => Some(ty::ClosureKind::Fn), . ty::IntTy::I16 => Some(ty::ClosureKind::FnMut), . ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce), . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . }, . . // "Bound" types appear in canonical queries when the . // closure type is not yet known . Bound(..) | Infer(_) => None, . . Error(_) => Some(ty::ClosureKind::Fn), . . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . } 4,586 ( 0.00%) } . . /// Fast path helper for testing if a type is `Sized`. . /// . /// Returning true means the type is known to be sized. Returning . /// `false` means nothing -- could be sized, might not be. . /// . /// Note that we could never rely on the fact that a type such as `[_]` is . /// trivially `!Sized` because we could be in a type environment with a . /// bound such as `[_]: Copy`. A function with such a bound obviously never . /// can be called, but that doesn't mean it shouldn't typecheck. This is why . /// this method doesn't return `Option`. 1,404,315 ( 0.00%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 936,210 ( 0.00%) match self.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 2246 ---------------------------------------- -- line 2250 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => true, . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false, . 25,505 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 63,219 ( 0.00%) ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(), . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false, . . ty::Infer(ty::TyVar(_)) => false, . . ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`is_trivially_sized` applied to unexpected type: {:?}", self) . } . } 1,404,315 ( 0.00%) } . } . . /// Extra information about why we ended up with a particular variance. . /// This is only used to add more information to error messages, and . /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo` . /// may lead to confusing notes in error messages, it will never cause . /// a miscompilation or unsoundness. . /// -- line 2280 ---------------------------------------- -- line 2295 ---------------------------------------- . /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`) . param_index: u32, . }, . } . . impl<'tcx> VarianceDiagInfo<'tcx> { . /// Mirrors `Variance::xform` - used to 'combine' the existing . /// and new `VarianceDiagInfo`s when our variance changes. 318,840 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 478,260 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 159,420 ( 0.00%) } . } 540,166,366 ( 0.46%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 9,012 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 9,012 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 18,024 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 1,360,975 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 9,254,630 ( 0.01%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 816,585 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 1,633,170 ( 0.00%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 671,378 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 29,032,832 ( 0.02%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 85,254 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 8,072 ( 0.00%) self.float_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn const_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 34,121,345 ( 0.03%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 5,040,382 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 5,246,911 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 2,755,280 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 3,613,124 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 190,967 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 49,082 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 35,442 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 38,875 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 272,195 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 816,585 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 272,195 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 151,731 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 185,449 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 84,295 ( 0.00%) self.with_opaque_type_inference(table_owner) 118,013 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 18,402 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 9,201 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 52,120 ( 0.00%) self 27,603 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 414,771 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 702,322 ( 0.00%) let (value, subst) = 44,874 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 1,043,500 ( 0.00%) f(infcx, value, subst) . }) 450,772 ( 0.00%) } . 1,331,421 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 743,636 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 11,308,088 ( 0.01%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 272,195 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 272,195 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 1,503,137 ( 0.00%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 19,936 ( 0.00%) let InferOk { value, obligations } = self; 70,240 ( 0.00%) for obligation in obligations { 4,706 ( 0.00%) fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 232,013 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 928,052 ( 0.00%) self.obligations 232,013 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 552,358 ( 0.00%) } . 5,346,272 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 6,014,556 ( 0.01%) t.fold_with(&mut self.freshener()) 6,014,556 ( 0.01%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 2,938 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 5,876 ( 0.00%) match *ty.kind() { 1,469 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 5,876 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } . _ => None, . } 5,876 ( 0.00%) } . 668,284 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 668,284 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 1,481,580 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 1,481,580 ( 0.00%) } . 37,804 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 18,902 ( 0.00%) let mut inner = self.inner.borrow_mut(); 18,902 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 2,935 ( 0.00%) .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) 7,802 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) 435 ( 0.00%) .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 66,157 ( 0.00%) } . 11,175,981 ( 0.01%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 44,915,980 ( 0.04%) CombineFields { . infcx: self, 112,289,950 ( 0.10%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 11,175,981 ( 0.01%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 760 ---------------------------------------- . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. . pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 74,778 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result . } . 53,634,066 ( 0.05%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 160,902,198 ( 0.14%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 26,817,033 ( 0.02%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 107,268,132 ( 0.09%) } . 168,972,078 ( 0.15%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 15,361,098 ( 0.01%) undo_snapshot, 15,361,098 ( 0.01%) region_constraints_snapshot, 15,361,098 ( 0.01%) universe, 15,361,098 ( 0.01%) was_in_snapshot, 30,722,196 ( 0.03%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 15,361,098 ( 0.01%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 171,839,025 ( 0.15%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 11,455,935 ( 0.01%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 11,455,935 ( 0.01%) was_in_snapshot, 22,911,870 ( 0.02%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 30,228,433 ( 0.03%) #[instrument(skip(self, f), level = "debug")] 36,985,036 ( 0.03%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 3,362,276 ( 0.00%) let snapshot = self.start_snapshot(); 10,159,524 ( 0.01%) let r = f(&snapshot); 23,535,932 ( 0.02%) self.commit_from(snapshot); 20,377,749 ( 0.02%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 108,215,210 ( 0.09%) #[instrument(skip(self, f), level = "debug")] 132,365,842 ( 0.11%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 12,663,728 ( 0.01%) let snapshot = self.start_snapshot(); 60,462,662 ( 0.05%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 11,695,141 ( 0.01%) match r { . Ok(_) => { 57,929,950 ( 0.05%) self.commit_from(snapshot); . } . Err(_) => { 42,694,345 ( 0.04%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 72,379,598 ( 0.06%) r . } . . /// Execute `f` then unroll any bindings it creates. 73,287,106 ( 0.06%) #[instrument(skip(self, f), level = "debug")] 88,089,753 ( 0.08%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 22,110,514 ( 0.02%) let snapshot = self.start_snapshot(); 40,417,840 ( 0.03%) let r = f(&snapshot); 99,423,353 ( 0.09%) self.rollback_to("probe", snapshot); 313,775 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. 473,202 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 630,936 ( 0.00%) pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 105,156 ( 0.00%) let snapshot = self.start_snapshot(); 52,578 ( 0.00%) let was_skip_leak_check = self.skip_leak_check.get(); 105,156 ( 0.00%) if should_skip { . self.skip_leak_check.set(true); . } 210,312 ( 0.00%) let r = f(&snapshot); 473,202 ( 0.00%) self.rollback_to("probe", snapshot); . self.skip_leak_check.set(was_skip_leak_check); 630,936 ( 0.00%) r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 7,081,766 ( 0.01%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 14,163,532 ( 0.01%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 10,622,649 ( 0.01%) } . 2 ( 0.00%) pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { 4 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); 3 ( 0.00%) } . 2,112 ( 0.00%) pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 1,584 ( 0.00%) } . 58,740 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 44,055 ( 0.00%) } . 380,710 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 342,639 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. . #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, -- line 947 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 1,203 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 802 ( 0.00%) let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); 2,005 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 1,604 ( 0.00%) } . 44,928 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 3,744 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 3,744 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 28,166 ( 0.00%) match (r_a.kind(), r_b.kind()) { 6,616 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 6,616 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 436 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 872 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 33,696 ( 0.00%) } . 80,148 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 66,790 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 53,432 ( 0.00%) } . . /// Number of type variables created so far. 439 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 878 ( 0.00%) } . 368,268 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 1,841,340 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 552,402 ( 0.00%) } . 193,902 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 1,201,825 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 290,853 ( 0.00%) } . 43,656 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 240,108 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 21,828 ( 0.00%) self.tcx.mk_ty_var(vid) 65,484 ( 0.00%) } . 3,696 ( 0.00%) pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { 6,468 ( 0.00%) self.tcx.mk_const_var(self.next_const_var_id(origin), ty) 3,696 ( 0.00%) } . 3,468 ( 0.00%) pub fn next_const_var_in_universe( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . universe: ty::UniverseIndex, . ) -> &'tcx ty::Const<'tcx> { 3,468 ( 0.00%) let vid = self . .inner . .borrow_mut() . .const_unification_table() 9,248 ( 0.00%) .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } }); 1,156 ( 0.00%) self.tcx.mk_const_var(vid, ty) 4,624 ( 0.00%) } . 1,848 ( 0.00%) pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { 6,468 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { 3,696 ( 0.00%) origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) 2,772 ( 0.00%) } . . fn next_int_var_id(&self) -> IntVid { 11,595 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 6,957 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 9,276 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { 555 ( 0.00%) self.inner.borrow_mut().float_unification_table().new_key(None) . } . 333 ( 0.00%) pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) 444 ( 0.00%) } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 66,466 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 2,997,098 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 132,932 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 1,240,742 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 8,064,823 ( 0.01%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 3,101,855 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 1,861,113 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 53,212 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 79,818 ( 0.00%) } . . /// Number of region variables created so far. 73,986 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 110,979 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 114,362 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 228,724 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 880 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 7,788 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 1,760 ( 0.00%) } . 9,688,216 ( 0.01%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 5,320,899 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 367,118 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 2,870,400 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 3,588,000 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 717,600 ( 0.00%) param.name, 717,600 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 717,600 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 1,389,399 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 126,309 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 1,010,472 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 31,068,222 ( 0.03%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 68,091,344 ( 0.06%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 20,712,148 ( 0.02%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 20,962 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 430,565 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 31,443 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 416,731 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 1,131,127 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 59,533 ( 0.00%) assert!( 178,599 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 59,533 ( 0.00%) }; . . let region_rels = 59,533 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 535,797 ( 0.00%) let (lexical_region_resolutions, errors) = 1,428,792 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 238,132 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 59,533 ( 0.00%) assert!(old_value.is_none()); . . errors 535,797 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 595,330 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 119,066 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 178,599 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 119,066 ( 0.00%) self.report_region_errors(&errors); . } 297,665 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate -- line 1307 ---------------------------------------- -- line 1319 ---------------------------------------- . } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 253,040 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 46,005 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 174,819 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 9,201 ( 0.00%) .into_infos_and_data(); 9,201 ( 0.00%) assert!(data.is_empty()); . var_infos 73,608 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 151,654 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 454,962 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 530,789 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 3,509,705 ( 0.00%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 94,096 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 141,144 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. 1,053,648 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 3,354,461 ( 0.00%) if !value.needs_infer() { 5,543,667 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 2,946,092 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 2,773,041 ( 0.00%) value.fold_with(&mut r) 949,014 ( 0.00%) } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> . where . T: TypeFoldable<'tcx>, . { . value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value() . } . 5,302 ( 0.00%) pub fn probe_const_var( . &self, . vid: ty::ConstVid<'tcx>, . ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> { 18,557 ( 0.00%) match self.inner.borrow_mut().const_unification_table().probe_value(vid).val { . ConstVariableValue::Known { value } => Ok(value), . ConstVariableValue::Unknown { universe } => Err(universe), . } 18,557 ( 0.00%) } . . pub fn fully_resolve>(&self, value: T) -> FixupResult<'tcx, T> { . /*! . * Attempts to resolve all type/region/const variables in . * `value`. Region inference must have been run already (e.g., . * by calling `resolve_regions_and_report_errors`). If some . * variable was never unified, an `Err` results. . * -- line 1437 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 117,387 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 698,522 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 11,145,858 ( 0.01%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 78,258 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 586,376 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 219,891 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 1,246,049 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 513,079 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. 3,704 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 7,408 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 5,556 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 41,099,703 ( 0.04%) self.universe.get() 11,799,148 ( 0.01%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 1,266 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 1,750 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 1,266 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 45,926,880 ( 0.04%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 23,747,596 ( 0.02%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 12,680,064 ( 0.01%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 141,500 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 53,379 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . 9,540 ( 0.00%) ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) 2,928 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 51,667,740 ( 0.04%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 3,838,110 ( 0.00%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 698 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. 2,916 ( 0.00%) self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() . } . . TyOrConstInferVar::Const(v) => { . // If `probe_value` returns a `Known` value, it never equals . // `ty::ConstKind::Infer(ty::InferConst::Var(v))`. . // . // Not `inlined_probe_value(v)` because this call site is colder. 36,499 ( 0.00%) match self.inner.borrow_mut().const_unification_table().probe_value(v).val { . ConstVariableValue::Unknown { .. } => false, . ConstVariableValue::Known { .. } => true, . } . } . } . } . } . -- line 1704 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 71,322 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 71,322 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 6,156 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 688,035 ( 0.00%) match *ty.kind() { 152,382 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 72 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), 336 ( 0.00%) ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 6,156 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { 1,884 ( 0.00%) match ct.val { 942 ( 0.00%) ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } . } . } . . struct ShallowResolver<'a, 'tcx> { . infcx: &'a InferCtxt<'a, 'tcx>, . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 7,971,641 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 1,870,960 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 1,866,854 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 2,328,435 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 1,397,061 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 2,338,700 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 148 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 370 ( 0.00%) match *self { 74 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 246,829 ( 0.00%) match *cause.code() { 30,684 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 153,420 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 59,624,607 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/at.rs -------------------------------------------------------------------------------- Ir -- line 44 ---------------------------------------- . . impl<'a, 'tcx> InferCtxt<'a, 'tcx> { . #[inline] . pub fn at( . &'a self, . cause: &'a ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> At<'a, 'tcx> { 1,059,981 ( 0.00%) At { infcx: self, cause, param_env } . } . } . . pub trait ToTrace<'tcx>: Relate<'tcx> + Copy { . fn to_trace( . tcx: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx>; . } . . impl<'a, 'tcx> At<'a, 'tcx> { . /// Hacky routine for equating two impl headers in coherence. 420,624 ( 0.00%) pub fn eq_impl_headers( . self, . expected: &ty::ImplHeader<'tcx>, . actual: &ty::ImplHeader<'tcx>, . ) -> InferResult<'tcx, ()> { . debug!("eq_impl_header({:?} = {:?})", expected, actual); 525,780 ( 0.00%) match (expected.trait_ref, actual.trait_ref) { . (Some(a_ref), Some(b_ref)) => self.eq(a_ref, b_ref), 1,590 ( 0.00%) (None, None) => self.eq(expected.self_ty, actual.self_ty), . _ => bug!("mk_eq_impl_headers given mismatched impl kinds"), . } 473,202 ( 0.00%) } . . /// Makes `a <: b`, where `a` may or may not be expected. . pub fn sub_exp(self, a_is_expected: bool, a: T, b: T) -> InferResult<'tcx, ()> . where . T: ToTrace<'tcx>, . { 4,498,103 ( 0.00%) self.trace_exp(a_is_expected, a, b).sub(a, b) . } . . /// Makes `actual <: expected`. For example, if type-checking a . /// call like `foo(x)`, where `foo: fn(i32)`, you might have . /// `sup(i32, x)`, since the "expected" type is the type that . /// appears in the signature. . pub fn sup(self, expected: T, actual: T) -> InferResult<'tcx, ()> . where -- line 94 ---------------------------------------- -- line 109 ---------------------------------------- . pub fn eq_exp(self, a_is_expected: bool, a: T, b: T) -> InferResult<'tcx, ()> . where . T: ToTrace<'tcx>, . { . self.trace_exp(a_is_expected, a, b).eq(a, b) . } . . /// Makes `expected <: actual`. 18,020 ( 0.00%) pub fn eq(self, expected: T, actual: T) -> InferResult<'tcx, ()> . where . T: ToTrace<'tcx>, . { 5,406 ( 0.00%) self.trace(expected, actual).eq(expected, actual) 16,218 ( 0.00%) } . 29,580 ( 0.00%) pub fn relate(self, expected: T, variance: ty::Variance, actual: T) -> InferResult<'tcx, ()> . where . T: ToTrace<'tcx>, . { 14,790 ( 0.00%) match variance { . ty::Variance::Covariant => self.sub(expected, actual), 8,874 ( 0.00%) ty::Variance::Invariant => self.eq(expected, actual), . ty::Variance::Contravariant => self.sup(expected, actual), . . // We could make this make sense but it's not readily . // exposed and I don't feel like dealing with it. Note . // that bivariance in general does a bit more than just . // *nothing*, it checks that the types are the same . // "modulo variance" basically. . ty::Variance::Bivariant => panic!("Bivariant given to `relate()`"), . } 26,622 ( 0.00%) } . . /// Computes the least-upper-bound, or mutual supertype, of two . /// values. The order of the arguments doesn't matter, but since . /// this can result in an error (e.g., if asked to compute LUB of . /// u32 and i32), it is meaningful to call one of them the . /// "expected type". . pub fn lub(self, expected: T, actual: T) -> InferResult<'tcx, T> . where -- line 148 ---------------------------------------- -- line 174 ---------------------------------------- . . /// Like `trace`, but the expected value is determined by the . /// boolean argument (if true, then the first argument `a` is the . /// "expected" value). . pub fn trace_exp(self, a_is_expected: bool, a: T, b: T) -> Trace<'a, 'tcx> . where . T: ToTrace<'tcx>, . { 134,551,120 ( 0.12%) let trace = ToTrace::to_trace(self.infcx.tcx, self.cause, a_is_expected, a, b); . Trace { at: self, trace, a_is_expected } . } . } . . impl<'a, 'tcx> Trace<'a, 'tcx> { . /// Makes `a <: b` where `a` may or may not be expected (if . /// `a_is_expected` is true, then `a` is expected). . #[instrument(skip(self), level = "debug")] . pub fn sub(self, a: T, b: T) -> InferResult<'tcx, ()> . where . T: Relate<'tcx>, . { 4,077,738 ( 0.00%) let Trace { at, trace, a_is_expected } = self; 16,464,183 ( 0.01%) at.infcx.commit_if_ok(|_| { 10,451,758 ( 0.01%) let mut fields = at.infcx.combine_fields(trace, at.param_env); 1,118,611 ( 0.00%) fields 2,240,441 ( 0.00%) .sub(a_is_expected) 5,298,334 ( 0.00%) .relate(a, b) 2,987,836 ( 0.00%) .map(move |_| InferOk { value: (), obligations: fields.obligations }) . }) . } . . /// Makes `a == b`; the expectation is set by the call to . /// `trace()`. . #[instrument(skip(self), level = "debug")] . pub fn eq(self, a: T, b: T) -> InferResult<'tcx, ()> . where . T: Relate<'tcx>, . { 62,782,022 ( 0.05%) let Trace { at, trace, a_is_expected } = self; 230,618,351 ( 0.20%) at.infcx.commit_if_ok(|_| { 146,055,372 ( 0.13%) let mut fields = at.infcx.combine_fields(trace, at.param_env); 31,391,469 ( 0.03%) fields 31,391,469 ( 0.03%) .equate(a_is_expected) 62,599,128 ( 0.05%) .relate(a, b) 41,925,396 ( 0.04%) .map(move |_| InferOk { value: (), obligations: fields.obligations }) . }) . } . . #[instrument(skip(self), level = "debug")] . pub fn lub(self, a: T, b: T) -> InferResult<'tcx, T> . where . T: Relate<'tcx>, . { 3,435 ( 0.00%) let Trace { at, trace, a_is_expected } = self; 15,114 ( 0.00%) at.infcx.commit_if_ok(|_| { 9,618 ( 0.00%) let mut fields = at.infcx.combine_fields(trace, at.param_env); 2,061 ( 0.00%) fields 2,061 ( 0.00%) .lub(a_is_expected) 2,748 ( 0.00%) .relate(a, b) 2,748 ( 0.00%) .map(move |t| InferOk { value: t, obligations: fields.obligations }) . }) . } . . #[instrument(skip(self), level = "debug")] . pub fn glb(self, a: T, b: T) -> InferResult<'tcx, T> . where . T: Relate<'tcx>, . { -- line 241 ---------------------------------------- -- line 253 ---------------------------------------- . impl<'tcx> ToTrace<'tcx> for Ty<'tcx> { . fn to_trace( . _: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx> { 1,474,501 ( 0.00%) TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) } 421,286 ( 0.00%) } . } . . impl<'tcx> ToTrace<'tcx> for ty::Region<'tcx> { . fn to_trace( . _: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx> { 785,379 ( 0.00%) TypeTrace { cause: cause.clone(), values: Regions(ExpectedFound::new(a_is_expected, a, b)) } 224,394 ( 0.00%) } . } . . impl<'tcx> ToTrace<'tcx> for &'tcx Const<'tcx> { . fn to_trace( . _: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx> { 1,617 ( 0.00%) TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } 462 ( 0.00%) } . } . . impl<'tcx> ToTrace<'tcx> for ty::TraitRef<'tcx> { 20,486,212 ( 0.02%) fn to_trace( . _: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx> { 51,215,530 ( 0.04%) TypeTrace { . cause: cause.clone(), 40,972,424 ( 0.04%) values: TraitRefs(ExpectedFound::new(a_is_expected, a, b)), . } 40,972,424 ( 0.04%) } . } . . impl<'tcx> ToTrace<'tcx> for ty::PolyTraitRef<'tcx> { 1,121,830 ( 0.00%) fn to_trace( . _: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx> { 2,804,575 ( 0.00%) TypeTrace { . cause: cause.clone(), 10,096,470 ( 0.01%) values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)), . } 2,243,660 ( 0.00%) } . } . . impl<'tcx> ToTrace<'tcx> for ty::ProjectionTy<'tcx> { 586,668 ( 0.00%) fn to_trace( . tcx: TyCtxt<'tcx>, . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Self, . b: Self, . ) -> TypeTrace<'tcx> { . let a_ty = tcx.mk_projection(a.item_def_id, a.substs); . let b_ty = tcx.mk_projection(b.item_def_id, b.substs); 342,223 ( 0.00%) TypeTrace { . cause: cause.clone(), . values: Types(ExpectedFound::new(a_is_expected, a_ty, b_ty)), . } 440,001 ( 0.00%) } . } 50,268,571 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/queries.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . use crate::ty::{self, TyCtxt}; . use rustc_hir::def_id::DefId; . use rustc_span::Span; . . impl<'tcx> TyCtxt<'tcx> { . /// Evaluates a constant without providing any substitutions. This is useful to evaluate consts . /// that can't take any generic arguments like statics, const items or enum discriminants. If a . /// generic parameter is used within the constant `ErrorHandled::ToGeneric` will be returned. 913 ( 0.00%) pub fn const_eval_poly(self, def_id: DefId) -> EvalToConstValueResult<'tcx> { . // In some situations def_id will have substitutions within scope, but they aren't allowed . // to be used. So we can't use `Instance::mono`, instead we feed unresolved substitutions . // into `const_eval` which will return `ErrorHandled::ToGeneric` if any of them are . // encountered. 415 ( 0.00%) let substs = InternalSubsts::identity_for_item(self, def_id); 332 ( 0.00%) let instance = ty::Instance::new(def_id, substs); . let cid = GlobalId { instance, promoted: None }; 166 ( 0.00%) let param_env = self.param_env(def_id).with_reveal_all_normalized(self); 996 ( 0.00%) self.const_eval_global_id(param_env, cid, None) 747 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still . /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is . /// returned. 90,254,988 ( 0.08%) #[instrument(level = "debug", skip(self))] 130,368,316 ( 0.11%) pub fn const_eval_resolve( . self, . param_env: ty::ParamEnv<'tcx>, . ct: ty::Unevaluated<'tcx>, . span: Option, . ) -> EvalToConstValueResult<'tcx> { 100,283,320 ( 0.09%) match ty::Instance::resolve_opt_const_arg(self, param_env, ct.def, ct.substs) { . Ok(Some(instance)) => { 10,028,332 ( 0.01%) let cid = GlobalId { instance, promoted: ct.promoted }; 120,339,984 ( 0.10%) self.const_eval_global_id(param_env, cid, span) . } . Ok(None) => Err(ErrorHandled::TooGeneric), . Err(error_reported) => Err(ErrorHandled::Reported(error_reported)), . } . } . . pub fn const_eval_instance( . self, -- line 52 ---------------------------------------- -- line 53 ---------------------------------------- . param_env: ty::ParamEnv<'tcx>, . instance: ty::Instance<'tcx>, . span: Option, . ) -> EvalToConstValueResult<'tcx> { . self.const_eval_global_id(param_env, GlobalId { instance, promoted: None }, span) . } . . /// Evaluate a constant. 140,397,810 ( 0.12%) pub fn const_eval_global_id( . self, . param_env: ty::ParamEnv<'tcx>, . cid: GlobalId<'tcx>, . span: Option, . ) -> EvalToConstValueResult<'tcx> { . let param_env = param_env.with_const(); . // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should . // improve caching of queries. 60,170,490 ( 0.05%) let inputs = self.erase_regions(param_env.and(cid)); 20,056,830 ( 0.02%) if let Some(span) = span { . self.at(span).eval_to_const_value_raw(inputs) . } else { . self.eval_to_const_value_raw(inputs) . } 90,255,735 ( 0.08%) } . . /// Evaluate a static's initializer, returning the allocation of the initializer's memory. . pub fn eval_static_initializer( . self, . def_id: DefId, . ) -> Result<&'tcx mir::Allocation, ErrorHandled> { . trace!("eval_static_initializer: Need to compute {:?}", def_id); . assert!(self.is_static(def_id)); -- line 84 ---------------------------------------- 70,198,351 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/zip.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . b: B, . // index, len and a_len are only used by the specialized version of zip . index: usize, . len: usize, . a_len: usize, . } . impl Zip { . pub(in crate::iter) fn new(a: A, b: B) -> Zip { 24 ( 0.00%) ZipImpl::new(a, b) . } . fn super_nth(&mut self, mut n: usize) -> Option<(A::Item, B::Item)> { . while let Some(x) = Iterator::next(self) { . if n == 0 { . return Some(x); . } . n -= 1; . } -- line 31 ---------------------------------------- -- line 63 ---------------------------------------- . /// assert!(iter.next().is_none()); . /// ``` . #[stable(feature = "iter_zip", since = "1.59.0")] . pub fn zip(a: A, b: B) -> Zip . where . A: IntoIterator, . B: IntoIterator, . { 343,915 ( 0.00%) ZipImpl::new(a.into_iter(), b.into_iter()) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for Zip . where . A: Iterator, . B: Iterator, . { -- line 79 ---------------------------------------- -- line 136 ---------------------------------------- . Self: Iterator + TrustedRandomAccessNoCoerce; . } . . // Work around limitations of specialization, requiring `default` impls to be repeated . // in intermediary impls. . macro_rules! zip_impl_general_defaults { . () => { . default fn new(a: A, b: B) -> Self { 48 ( 0.00%) Zip { . a, . b, . index: 0, // unused . len: 0, // unused . a_len: 0, // unused . } . } . . #[inline] . default fn next(&mut self) -> Option<(A::Item, B::Item)> { 1,382,626 ( 0.00%) let x = self.a.next()?; 1,056,014 ( 0.00%) let y = self.b.next()?; 65,028 ( 0.00%) Some((x, y)) 98,188 ( 0.00%) } . . #[inline] . default fn nth(&mut self, n: usize) -> Option { . self.super_nth(n) . } . . #[inline] . default fn next_back(&mut self) -> Option<(A::Item, B::Item)> -- line 166 ---------------------------------------- -- line 203 ---------------------------------------- . B: Iterator, . { . type Item = (A::Item, B::Item); . . zip_impl_general_defaults! {} . . #[inline] . default fn size_hint(&self) -> (usize, Option) { 578 ( 0.00%) let (a_lower, a_upper) = self.a.size_hint(); 63 ( 0.00%) let (b_lower, b_upper) = self.b.size_hint(); . . let lower = cmp::min(a_lower, b_lower); . . let upper = match (a_upper, b_upper) { . (Some(x), Some(y)) => Some(cmp::min(x, y)), . (Some(x), None) => Some(x), . (None, Some(y)) => Some(y), . (None, None) => None, -- line 220 ---------------------------------------- -- line 236 ---------------------------------------- . where . A: TrustedRandomAccessNoCoerce + Iterator, . B: TrustedRandomAccessNoCoerce + Iterator, . { . zip_impl_general_defaults! {} . . #[inline] . default fn size_hint(&self) -> (usize, Option) { 5,220 ( 0.00%) let size = cmp::min(self.a.size(), self.b.size()); . (size, Some(size)) . } . . #[inline] . unsafe fn get_unchecked(&mut self, idx: usize) -> ::Item { 664 ( 0.00%) let idx = self.index + idx; . // SAFETY: the caller must uphold the contract for . // `Iterator::__iterator_get_unchecked`. . unsafe { (self.a.__iterator_get_unchecked(idx), self.b.__iterator_get_unchecked(idx)) } . } . } . . #[doc(hidden)] . impl ZipImpl for Zip . where . A: TrustedRandomAccess + Iterator, . B: TrustedRandomAccess + Iterator, . { . fn new(a: A, b: B) -> Self { . let a_len = a.size(); . let len = cmp::min(a_len, b.size()); 1,022 ( 0.00%) Zip { a, b, index: 0, len, a_len } . } . . #[inline] . fn next(&mut self) -> Option<(A::Item, B::Item)> { 444,463,256 ( 0.38%) if self.index < self.len { . let i = self.index; . // since get_unchecked executes code which can panic we increment the counters beforehand . // so that the same index won't be accessed twice, as required by TrustedRandomAccess 107,561,747 ( 0.09%) self.index += 1; . // SAFETY: `i` is smaller than `self.len`, thus smaller than `self.a.len()` and `self.b.len()` . unsafe { 250 ( 0.00%) Some((self.a.__iterator_get_unchecked(i), self.b.__iterator_get_unchecked(i))) . } 30 ( 0.00%) } else if A::MAY_HAVE_SIDE_EFFECT && self.index < self.a_len { . let i = self.index; . // as above, increment before executing code that may panic . self.index += 1; . self.len += 1; . // match the base implementation's potential side effects . // SAFETY: we just checked that `i` < `self.a.len()` . unsafe { . self.a.__iterator_get_unchecked(i); -- line 288 ---------------------------------------- -- line 290 ---------------------------------------- . None . } else { . None . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 65,421,226 ( 0.06%) let len = self.len - self.index; 1,272 ( 0.00%) (len, Some(len)) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option { . let delta = cmp::min(n, self.len - self.index); . let end = self.index + delta; . while self.index < end { . let i = self.index; -- line 307 ---------------------------------------- -- line 353 ---------------------------------------- . let sz_b = self.b.size(); . if B::MAY_HAVE_SIDE_EFFECT && sz_b > self.len { . for _ in 0..sz_b - self.len { . self.b.next_back(); . } . } . } . } 1,614 ( 0.00%) if self.index < self.len { . // since get_unchecked executes code which can panic we increment the counters beforehand . // so that the same index won't be accessed twice, as required by TrustedRandomAccess . self.len -= 1; . self.a_len -= 1; . let i = self.len; . // SAFETY: `i` is smaller than the previous value of `self.len`, . // which is also smaller than or equal to `self.a.len()` and `self.b.len()` . unsafe { -- line 369 ---------------------------------------- -- line 535 ---------------------------------------- . #[unstable(feature = "trusted_random_access", issue = "none")] . #[rustc_specialization_trait] . pub unsafe trait TrustedRandomAccessNoCoerce: Sized { . // Convenience method. . fn size(&self) -> usize . where . Self: Iterator, . { 23,338 ( 0.00%) self.size_hint().0 . } . /// `true` if getting an iterator element may have side effects. . /// Remember to take inner iterators into account. . const MAY_HAVE_SIDE_EFFECT: bool; . } . . /// Like `Iterator::__iterator_get_unchecked`, but doesn't require the compiler to . /// know that `U: TrustedRandomAccess`. -- line 551 ---------------------------------------- -- line 555 ---------------------------------------- . /// Same requirements calling `get_unchecked` directly. . #[doc(hidden)] . pub(in crate::iter::adapters) unsafe fn try_get_unchecked(it: &mut I, idx: usize) -> I::Item . where . I: Iterator, . { . // SAFETY: the caller must uphold the contract for . // `Iterator::__iterator_get_unchecked`. 103,185 ( 0.00%) unsafe { it.try_get_unchecked(idx) } . } . . unsafe trait SpecTrustedRandomAccess: Iterator { . /// If `Self: TrustedRandomAccess`, it must be safe to call . /// `Iterator::__iterator_get_unchecked(self, index)`. . unsafe fn try_get_unchecked(&mut self, index: usize) -> Self::Item; . } . -- line 571 ---------------------------------------- 114,179,779 ( 0.10%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 3,244,414 ( 0.00%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 935,980 ( 0.00%) self.inline.as_mut_ptr() as *mut A::Item . } . #[inline] . fn from_inline(inline: MaybeUninit) -> SmallVecData { . SmallVecData { . inline: core::mem::ManuallyDrop::new(inline), . } . } . #[inline] . unsafe fn into_inline(self) -> MaybeUninit { . core::mem::ManuallyDrop::into_inner(self.inline) . } . #[inline] . unsafe fn heap(&self) -> (*mut A::Item, usize) { 433,417 ( 0.00%) self.heap . } . #[inline] . unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { . &mut self.heap . } . #[inline] . fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData { . SmallVecData { heap: (ptr, len) } -- line 452 ---------------------------------------- -- line 557 ---------------------------------------- . #[inline] . pub fn new() -> SmallVec { . // Try to detect invalid custom implementations of `Array`. Hopefully, . // this check should be optimized away entirely for valid ones. . assert!( . mem::size_of::() == A::size() * mem::size_of::() . && mem::align_of::() >= mem::align_of::() . ); 20,014,830 ( 0.02%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 579 ---------------------------------------- . /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100); . /// . /// assert!(v.is_empty()); . /// assert!(v.capacity() >= 100); . /// ``` . #[inline] . pub fn with_capacity(n: usize) -> Self { . let mut v = SmallVec::new(); 120 ( 0.00%) v.reserve_exact(n); . v . } . . /// Construct a new `SmallVec` from a `Vec`. . /// . /// Elements will be copied to the inline buffer if vec.capacity() <= Self::inline_capacity(). . /// . /// ```rust -- line 595 ---------------------------------------- -- line 597 ---------------------------------------- . /// . /// let vec = vec![1, 2, 3, 4, 5]; . /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_vec(mut vec: Vec) -> SmallVec { 16 ( 0.00%) if vec.capacity() <= Self::inline_capacity() { . unsafe { . let mut data = SmallVecData::::from_inline(MaybeUninit::uninit()); . let len = vec.len(); . vec.set_len(0); . ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut(), len); . . SmallVec { . capacity: len, . data, . } . } . } else { . let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len()); . mem::forget(vec); . 42 ( 0.00%) SmallVec { . capacity: cap, . data: SmallVecData::from_heap(ptr, len), . } . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. -- line 629 ---------------------------------------- -- line 635 ---------------------------------------- . /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf(buf: A) -> SmallVec { . SmallVec { . capacity: A::size(), 148,414 ( 0.00%) data: SmallVecData::from_inline(MaybeUninit::new(buf)), . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length, which must be less or . /// equal to the size of `buf`. . /// . /// ```rust -- line 651 ---------------------------------------- -- line 653 ---------------------------------------- . /// . /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; . /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { 260 ( 0.00%) assert!(len <= A::size()); 780 ( 0.00%) unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length. The user is responsible . /// for ensuring that `len <= A::size()`. . /// . /// ```rust . /// use smallvec::SmallVec; -- line 670 ---------------------------------------- -- line 674 ---------------------------------------- . /// let small_vec: SmallVec<_> = unsafe { . /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) . /// }; . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { 130 ( 0.00%) SmallVec { . capacity: len, . data: SmallVecData::from_inline(buf), . } . } . . /// Sets the length of a vector. . /// . /// This will explicitly set the size of the vector, without actually . /// modifying its buffers, so it is up to the caller to ensure that the . /// vector is actually the specified size. . pub unsafe fn set_len(&mut self, new_len: usize) { . let (_, len_ptr, _) = self.triple_mut(); 1,773,420 ( 0.00%) *len_ptr = new_len; . } . . /// The maximum number of elements this vector can hold inline . #[inline] . fn inline_capacity() -> usize { . if mem::size_of::() > 0 { . A::size() . } else { -- line 703 ---------------------------------------- -- line 725 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.triple().1 . } . . /// Returns `true` if the vector is empty . #[inline] . pub fn is_empty(&self) -> bool { 774,540 ( 0.00%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 74,650,589 ( 0.06%) if self.spilled() { . let (ptr, len) = self.data.heap(); . (ptr, len, self.capacity) . } else { . (self.data.inline(), self.capacity, Self::inline_capacity()) . } . } . } . . /// Returns a tuple with (data ptr, len ptr, capacity) . #[inline] . fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { . unsafe { 130,072,735 ( 0.11%) if self.spilled() { 2,522,341 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 138,392,211 ( 0.12%) self.capacity > Self::inline_capacity() . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// Note 1: The element range is removed even if the iterator is only . /// partially consumed or not consumed at all. . /// -- line 784 ---------------------------------------- -- line 821 ---------------------------------------- . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Append an item to the vector. . #[inline] 782,105 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 24,220,329 ( 0.02%) if *len == cap { 12,311 ( 0.00%) self.reserve(1); 48,732 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 46,640 ( 0.00%) ptr::write(ptr.add(*len), value); 28,020,287 ( 0.02%) *len += 1; . } 625,684 ( 0.00%) } . . /// Remove an item from the end of the vector and return it, or None if empty. . #[inline] . pub fn pop(&mut self) -> Option { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 3,702,836 ( 0.00%) if *len_ptr == 0 { . return None; . } 1,044,718 ( 0.00%) let last_index = *len_ptr - 1; 1,062,100 ( 0.00%) *len_ptr = last_index; 911,035 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 204 ( 0.00%) } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` . /// # use smallvec::{SmallVec, smallvec}; . /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3]; -- line 863 ---------------------------------------- -- line 879 ---------------------------------------- . /// or if the capacity computation overflows `usize`. . pub fn grow(&mut self, new_cap: usize) { . infallible(self.try_grow(new_cap)) . } . . /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. . /// . /// Panics if `new_cap` is less than the vector's length 2,939,422 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 2,874 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 816,392 ( 0.00%) assert!(new_cap >= len); 816,392 ( 0.00%) if new_cap <= self.inline_size() { . if unspilled { . return Ok(()); . } . self.data = SmallVecData::from_inline(MaybeUninit::uninit()); . ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); . self.capacity = len; . deallocate(ptr, cap); 816,392 ( 0.00%) } else if new_cap != cap { 807,724 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 408,196 ( 0.00%) if unspilled { . new_alloc = NonNull::new(alloc::alloc::alloc(layout)) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . ptr::copy_nonoverlapping(ptr, new_alloc, len); . } else { . // This should never fail since the same succeeded . // when previously allocating `ptr`. 12,732 ( 0.00%) let old_layout = layout_array::(cap)?; . . let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); . new_alloc = NonNull::new(new_ptr) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . } 816,392 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 1,572,605 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 2,942,296 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. . /// . /// Panics if the capacity computation overflows `usize`. . #[inline] 6,762,885 ( 0.01%) pub fn reserve(&mut self, additional: usize) { 3,077,229 ( 0.00%) infallible(self.try_reserve(additional)) 7,710,016 ( 0.01%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 12,149,161 ( 0.01%) pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . // prefer triple_mut() even if triple() would work . // so that the optimizer removes duplicated calls to it . // from callers like insert() 86,829 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 61,261,014 ( 0.05%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .and_then(usize::checked_next_power_of_two) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 10,972 ( 0.00%) self.try_grow(new_cap) 12,946,150 ( 0.01%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. 120 ( 0.00%) pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) 120 ( 0.00%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 22,196,912 ( 0.02%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 363,485 ( 0.00%) self.try_grow(new_cap) 363,485 ( 0.00%) } . . /// Shrink the capacity of the vector as much as possible. . /// . /// When possible, this will move data from an external heap buffer to the vector's inline . /// storage. . pub fn shrink_to_fit(&mut self) { . if !self.spilled() { . return; -- line 981 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 593,036 ( 0.00%) while len < *len_ptr { . let last_index = *len_ptr - 1; . *len_ptr = last_index; . ptr::drop_in_place(ptr.add(last_index)); . } . } . } . . /// Extracts a slice containing the entire vector. -- line 1015 ---------------------------------------- -- line 1044 ---------------------------------------- . pub fn clear(&mut self) { . self.truncate(0); . } . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. 64 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 64,435 ( 0.00%) let len = *len_ptr; 196,077 ( 0.00%) assert!(index < len); 227,232 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 130,718 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 80 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 723,259 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 67,541 ( 0.00%) let len = *len_ptr; 133,292 ( 0.00%) assert!(index <= len); 266,584 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 133,292 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 460,258 ( 0.00%) } . . /// Insert multiple elements at position `index`, shifting all following elements toward the . /// back. . pub fn insert_many>(&mut self, index: usize, iterable: I) { . let mut iter = iterable.into_iter(); . if index == self.len() { . return self.extend(iter); . } -- line 1088 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place and preserves the order of the retained . /// elements. 1,479,006 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 1,413,744 ( 0.00%) if !f(&mut self[i]) { 66,574 ( 0.00%) del += 1; 400,462 ( 0.00%) } else if del > 0 { 48,090 ( 0.00%) self.swap(i - del, i); . } . } 328,668 ( 0.00%) self.truncate(len - del); 1,314,672 ( 0.00%) } . . /// Removes consecutive duplicate elements. . pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); . } -- line 1228 ---------------------------------------- -- line 1418 ---------------------------------------- . capacity: len, . data: SmallVecData::from_inline(unsafe { . let mut data: MaybeUninit = MaybeUninit::uninit(); . ptr::copy_nonoverlapping( . slice.as_ptr(), . data.as_mut_ptr() as *mut A::Item, . len, . ); 13,725 ( 0.00%) data . }), . } . } else { . let mut b = slice.to_vec(); . let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); . mem::forget(b); . SmallVec { . capacity: cap, -- line 1434 ---------------------------------------- -- line 1436 ---------------------------------------- . } . } . } . . /// Copy elements from a slice into the vector at position `index`, shifting any following . /// elements toward the back. . /// . /// For slices of `Copy` types, this is more efficient than `insert`. 5,945,137 ( 0.01%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 1,930,956 ( 0.00%) assert!(index <= len); . . unsafe { . let slice_ptr = slice.as_ptr(); . let ptr = self.as_mut_ptr().add(index); . ptr::copy(ptr, ptr.add(slice.len()), len - index); . ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); 1,287,304 ( 0.00%) self.set_len(len + slice.len()); . } 5,149,216 ( 0.00%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 2,133,140 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. . /// . /// If `len` is less than the current length, the vector simply truncated. . /// . /// If `len` is greater than the current length, `value` is appended to the . /// vector until its length equals `len`. 1,900 ( 0.00%) pub fn resize(&mut self, len: usize, value: A::Item) { . let old_len = self.len(); . 380 ( 0.00%) if len > old_len { . self.extend(repeat(value).take(len - old_len)); . } else { . self.truncate(len); . } 1,330 ( 0.00%) } . . /// Creates a `SmallVec` with `n` copies of `elem`. . /// ``` . /// use smallvec::SmallVec; . /// . /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); . /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); . /// ``` . pub fn from_elem(elem: A::Item, n: usize) -> Self { 66 ( 0.00%) if n > Self::inline_capacity() { . vec![elem; n].into() . } else { . let mut v = SmallVec::::new(); . unsafe { . let (ptr, len_ptr, _) = v.triple_mut(); . let mut local_len = SetLenOnDrop::new(len_ptr); . . for i in 0..n { . ::core::ptr::write(ptr.add(i), elem.clone()); . local_len.increment_len(1); . } . } 81 ( 0.00%) v . } . } . } . . impl ops::Deref for SmallVec { . type Target = [A::Item]; . #[inline] . fn deref(&self) -> &[A::Item] { -- line 1518 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 401,689 ( 0.00%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1691 ---------------------------------------- . fn from(array: A) -> SmallVec { . SmallVec::from_buf(array) . } . } . . impl> ops::Index for SmallVec { . type Output = I::Output; . 60 ( 0.00%) fn index(&self, index: I) -> &I::Output { . &(**self)[index] 180 ( 0.00%) } . } . . impl> ops::IndexMut for SmallVec { . fn index_mut(&mut self, index: I) -> &mut I::Output { . &mut (&mut **self)[index] . } . } . -- line 1709 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 30,143,493 ( 0.03%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 35,876,651 ( 0.03%) fn extend>(&mut self, iterable: I) { 24,351,610 ( 0.02%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 1,751,959 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 31,369,843 ( 0.03%) while len.get() < cap { 54,904,078 ( 0.05%) if let Some(out) = iter.next() { 32 ( 0.00%) ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 696,734 ( 0.00%) for elem in iter { 14,594 ( 0.00%) self.push(elem); . } 34,626,616 ( 0.03%) } . } . . impl fmt::Debug for SmallVec . where . A::Item: fmt::Debug, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_list().entries(self.iter()).finish() -- line 1759 ---------------------------------------- -- line 1764 ---------------------------------------- . #[inline] . fn default() -> SmallVec { . SmallVec::new() . } . } . . #[cfg(feature = "may_dangle")] . unsafe impl<#[may_dangle] A: Array> Drop for SmallVec { 5,660,046 ( 0.00%) fn drop(&mut self) { . unsafe { 42,333,038 ( 0.04%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 6,238,581 ( 0.01%) } . } . . #[cfg(not(feature = "may_dangle"))] . impl Drop for SmallVec { . fn drop(&mut self) { . unsafe { . if self.spilled() { . let (ptr, len) = self.data.heap(); -- line 1789 ---------------------------------------- -- line 1888 ---------------------------------------- . A::Item: Clone, . { . fn clone(&self) -> IntoIter { . SmallVec::from(self.as_slice()).into_iter() . } . } . . impl Drop for IntoIter { 327,634 ( 0.00%) fn drop(&mut self) { 2,896,429 ( 0.00%) for _ in self {} 362,544 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 7,071,454 ( 0.01%) if self.current == self.end { 414 ( 0.00%) None . } else { . unsafe { . let current = self.current; 2,402,590 ( 0.00%) self.current += 1; 212,902 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 97,478 ( 0.00%) let size = self.end - self.current; . (size, Some(size)) . } . } . . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . if self.current == self.end { -- line 1927 ---------------------------------------- -- line 1955 ---------------------------------------- . impl IntoIterator for SmallVec { . type IntoIter = IntoIter; . type Item = A::Item; . fn into_iter(mut self) -> Self::IntoIter { . unsafe { . // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements . let len = self.len(); . self.set_len(0); 413,712 ( 0.00%) IntoIter { 7,184,392 ( 0.01%) data: self, . current: 0, . end: len, . } . } . } . } . . impl<'a, A: Array> IntoIterator for &'a SmallVec { -- line 1972 ---------------------------------------- -- line 2000 ---------------------------------------- . len: &'a mut usize, . local_len: usize, . } . . impl<'a> SetLenOnDrop<'a> { . #[inline] . fn new(len: &'a mut usize) -> Self { . SetLenOnDrop { 4,377,184 ( 0.00%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 11,033,858 ( 0.01%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 8,159,348 ( 0.01%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 108,582,623 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 7,624 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 3,812 ( 0.00%) from_str_radix(src, radix) 11,436 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 3,300,825 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 6,492,405 ( 0.01%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 5,432,010 ( 0.00%) intrinsics::cttz(self) as u32 . } . . /// Returns the number of leading ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 155 ---------------------------------------- -- line 204 ---------------------------------------- . #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn rotate_left(self, n: u32) -> Self { 379,287,778 ( 0.33%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 4,415 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 12,407,576 ( 0.01%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 1,047,960 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 596 ---------------------------------------- . without modifying the original"] . #[inline] . pub const fn checked_div(self, rhs: Self) -> Option { . if unlikely!(rhs == 0) { . None . } else { . // SAFETY: div by zero has been checked above and unsigned types have no other . // failure modes for division 144 ( 0.00%) Some(unsafe { intrinsics::unchecked_div(self, rhs) }) . } . } . . /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` . /// if `rhs == 0`. . /// . /// # Examples . /// -- line 612 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 4,028,294 ( 0.00%) intrinsics::saturating_add(self, rhs) . } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1051 ---------------------------------------- -- line 1084 ---------------------------------------- . #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_sub(self, rhs: Self) -> Self { 167,691 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1104 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn saturating_mul(self, rhs: Self) -> Self { 120 ( 0.00%) match self.checked_mul(rhs) { . Some(x) => x, . None => Self::MAX, . } . } . . /// Saturating integer division. Computes `self / rhs`, saturating at the . /// numeric bounds instead of overflowing. . /// -- line 1120 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 71,480,074 ( 0.06%) intrinsics::wrapping_add(self, rhs) . } . . /// Wrapping (modular) addition with a signed integer. Computes . /// `self + rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_sub(self, rhs: Self) -> Self { 36,375,905 ( 0.03%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 498,006,540 ( 0.43%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 1,151 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 1491 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")] . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 19 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 23,580,146 ( 0.02%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 38 ( 0.00%) } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. . /// . #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] -- line 1510 ---------------------------------------- -- line 1587 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")] . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 528 ( 0.00%) pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 2,267,796 ( 0.00%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 1,056 ( 0.00%) } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. . /// . /// # Examples -- line 1606 ---------------------------------------- -- line 1674 ---------------------------------------- . /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 34,055,553 ( 0.03%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 1838 ---------------------------------------- . #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { 381 ( 0.00%) (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) . } . . /// Shifts self right by `rhs` bits. . /// . /// Returns a tuple of the shifted version of self along with a boolean . /// indicating whether the shift value was larger than or equal to the . /// number of bits. If the shift value is too large, then value is . /// masked (N-1) where N is the number of bits, and this value is then -- line 1854 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 276 ( 0.00%) self.count_ones() == 1 . } . . // Returns one less than next power of two. . // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) . // . // 8u8.one_less_than_next_power_of_two() == 7 . // 6u8.one_less_than_next_power_of_two() == 7 . // . // This method cannot overflow, as in the `next_power_of_two` . // overflow cases it instead ends up returning the maximum value . // of the type, and can return 0 for 0. . #[inline] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . const fn one_less_than_next_power_of_two(self) -> Self { 89,496 ( 0.00%) if self <= 1 { return 0; } . 399,778 ( 0.00%) let p = self - 1; . // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros. . // That means the shift is always in-bounds, and some processors . // (such as intel pre-haswell) have more efficient ctlz . // intrinsics when the argument is non-zero. 1,196,068 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 402,628 ( 0.00%) <$SelfT>::MAX >> z . } . . /// Returns the smallest power of two greater than or equal to `self`. . /// . /// When return value overflows (i.e., `self > (1 << (N-1))` for type . /// `uN`), it panics in debug mode and the return value is wrapped to 0 in . /// release mode (the only situation in which method can return 0). . /// -- line 2171 ---------------------------------------- -- line 2179 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . #[rustc_inherit_overflow_checks] . pub const fn next_power_of_two(self) -> Self { 709,852 ( 0.00%) self.one_less_than_next_power_of_two() + 1 . } . . /// Returns the smallest power of two greater than or equal to `n`. If . /// the next power of two is greater than the type's maximum value, . /// `None` is returned, otherwise the power of two is wrapped in `Some`. . /// . /// # Examples . /// -- line 2195 ---------------------------------------- 2,212,606 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs -------------------------------------------------------------------------------- Ir -- line 270 ---------------------------------------- . /// . /// let s = RandomState::new(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[inline] . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] . pub fn with_hasher(hash_builder: S) -> HashMap { 12,775,058 ( 0.01%) HashMap { base: base::HashMap::with_hasher(hash_builder) } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// . /// The hash map will be able to hold at least `capacity` elements without . /// reallocating. If `capacity` is 0, the hash map will not allocate. . /// -- line 286 ---------------------------------------- -- line 300 ---------------------------------------- . /// . /// let s = RandomState::new(); . /// let mut map = HashMap::with_capacity_and_hasher(10, s); . /// map.insert(1, 2); . /// ``` . #[inline] . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] . pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap { 24,845 ( 0.00%) HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) } . } . . /// Returns the number of elements the map can hold without reallocating. . /// . /// This number is a lower bound; the `HashMap` might be able to hold . /// more, but is guaranteed to be able to hold at least this many. . /// . /// # Examples -- line 316 ---------------------------------------- -- line 468 ---------------------------------------- . /// ]); . /// . /// for (key, val) in map.iter() { . /// println!("key: {} val: {}", key, val); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn iter(&self) -> Iter<'_, K, V> { 112,470 ( 0.00%) Iter { base: self.base.iter() } . } . . /// An iterator visiting all key-value pairs in arbitrary order, . /// with mutable references to the values. . /// The iterator element type is `(&'a K, &'a mut V)`. . /// . /// # Examples . /// -- line 484 ---------------------------------------- -- line 643 ---------------------------------------- . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 1 ( 0.00%) self.base.clear(); . } . . /// Returns a reference to the map's [`BuildHasher`]. . /// . /// # Examples . /// . /// ``` . /// use std::collections::HashMap; -- line 659 ---------------------------------------- -- line 688 ---------------------------------------- . /// ``` . /// use std::collections::HashMap; . /// let mut map: HashMap<&str, i32> = HashMap::new(); . /// map.reserve(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 1 ( 0.00%) self.base.reserve(additional) . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `HashMap`. The collection may reserve more space to avoid . /// frequent reallocations. . /// . /// # Errors . /// -- line 704 ---------------------------------------- -- line 784 ---------------------------------------- . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { 11,005,097 ( 0.01%) map_entry(self.base.rustc_entry(key)) . } . . /// Returns a reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 800 ---------------------------------------- -- line 805 ---------------------------------------- . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.get(&1), Some(&"a")); . /// assert_eq!(map.get(&2), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 3,332,910 ( 0.00%) pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . self.base.get(k) 4,799,160 ( 0.00%) } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// # Examples -- line 827 ---------------------------------------- -- line 862 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { 484,612 ( 0.00%) self.base.contains_key(k) . } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 878 ---------------------------------------- -- line 890 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { 7,659 ( 0.00%) self.base.get_mut(k) . } . . /// Inserts a key-value pair into the map. . /// . /// If the map did not have this key present, [`None`] is returned. . /// . /// If the map did have this key present, the value is updated, and the old . /// value is returned. The key is not updated, though; this matters for -- line 906 ---------------------------------------- -- line 920 ---------------------------------------- . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn insert(&mut self, k: K, v: V) -> Option { 20,284,238 ( 0.02%) self.base.insert(k, v) . } . . /// Tries to insert a key-value pair into the map, and returns . /// a mutable reference to the value in the entry. . /// . /// If the map already had this key present, nothing is updated, and . /// an error containing the occupied entry and the value is returned. . /// -- line 936 ---------------------------------------- -- line 978 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { 994,574 ( 0.00%) self.base.remove(k) . } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. -- line 994 ---------------------------------------- -- line 1083 ---------------------------------------- . impl Clone for HashMap . where . K: Clone, . V: Clone, . S: Clone, . { . #[inline] . fn clone(&self) -> Self { 10,479 ( 0.00%) Self { base: self.base.clone() } . } . . #[inline] . fn clone_from(&mut self, other: &Self) { . self.base.clone_from(&other.base); . } . } . -- line 1099 ---------------------------------------- -- line 1155 ---------------------------------------- . type Output = V; . . /// Returns a reference to the value corresponding to the supplied key. . /// . /// # Panics . /// . /// Panics if the key is not present in the `HashMap`. . #[inline] 23,749 ( 0.00%) fn index(&self, key: &Q) -> &V { . self.get(key).expect("no entry found for key") 42,154 ( 0.00%) } . } . . #[stable(feature = "std_collections_from_array", since = "1.56.0")] . // Note: as what is currently the most convenient built-in way to construct . // a HashMap, a simple usage of this function must not *require* the user . // to provide a type annotation in order to infer the third type parameter . // (the hasher parameter, conventionally "S"). . // To that end, this impl is defined using RandomState as the concrete -- line 1173 ---------------------------------------- -- line 1557 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S> . where . K: Borrow, . Q: Eq, . { 202,477,976 ( 0.17%) map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k)) . } . . /// Creates a `RawEntryMut` from the given hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S> . where . for<'b> F: FnMut(&'b K) -> bool, -- line 1573 ---------------------------------------- -- line 1594 ---------------------------------------- . /// Access an entry by a key and its hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Hash + Eq, . { 287,556,488 ( 0.25%) self.map.base.raw_entry().from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_hash(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, -- line 1610 ---------------------------------------- -- line 2338 ---------------------------------------- . /// assert_eq!(map["poneyland"], 3); . /// . /// *map.entry("poneyland").or_insert(10) *= 2; . /// assert_eq!(map["poneyland"], 6); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn or_insert(self, default: V) -> &'a mut V { 278,180 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), . Vacant(entry) => entry.insert(default), . } . } . . /// Ensures a value is in the entry by inserting the result of the default function if empty, . /// and returns a mutable reference to the value in the entry. . /// -- line 2354 ---------------------------------------- -- line 2362 ---------------------------------------- . /// . /// map.entry("poneyland").or_insert_with(|| s); . /// . /// assert_eq!(map["poneyland"], "hoho".to_string()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn or_insert_with V>(self, default: F) -> &'a mut V { 990,109 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), . Vacant(entry) => entry.insert(default()), . } . } . . /// Ensures a value is in the entry by inserting, if empty, the result of the default function. . /// This method allows for generating key-derived values for insertion by providing the default . /// function a reference to the key that was moved during the `.entry(key)` method call. -- line 2378 ---------------------------------------- -- line 2443 ---------------------------------------- . /// assert_eq!(map["poneyland"], 43); . /// ``` . #[inline] . #[stable(feature = "entry_and_modify", since = "1.26.0")] . pub fn and_modify(self, f: F) -> Self . where . F: FnOnce(&mut V), . { 568 ( 0.00%) match self { . Occupied(mut entry) => { . f(entry.get_mut()); . Occupied(entry) . } . Vacant(entry) => Vacant(entry), . } . } . -- line 2459 ---------------------------------------- -- line 2496 ---------------------------------------- . /// map.entry("poneyland").or_default(); . /// . /// assert_eq!(map["poneyland"], None); . /// # } . /// ``` . #[inline] . #[stable(feature = "entry_or_default", since = "1.28.0")] . pub fn or_default(self) -> &'a mut V { 234,888 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), . Vacant(entry) => entry.insert(Default::default()), . } . } . } . . impl<'a, K, V> OccupiedEntry<'a, K, V> { . /// Gets a reference to the key in the entry. -- line 2512 ---------------------------------------- -- line 2790 ---------------------------------------- . /// if let Entry::Vacant(o) = map.entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn insert(self, value: V) -> &'a mut V { 3,087,997 ( 0.00%) self.base.insert(value) . } . . /// Sets the value of the entry with the `VacantEntry`'s key, . /// and returns an `OccupiedEntry`. . /// . /// # Examples . /// . /// ``` -- line 2806 ---------------------------------------- -- line 2823 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher + Default, . { 2,605 ( 0.00%) fn from_iter>(iter: T) -> HashMap { . let mut map = HashMap::with_hasher(Default::default()); . map.extend(iter); . map 2,606 ( 0.00%) } . } . . /// Inserts all new key-values from the iterator and replaces values with existing . /// keys with new values returned from the iterator. . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . { . #[inline] . fn extend>(&mut self, iter: T) { 587,533 ( 0.00%) self.base.extend(iter) . } . . #[inline] . fn extend_one(&mut self, (k, v): (K, V)) { . self.base.insert(k, v); . } . . #[inline] -- line 2856 ---------------------------------------- -- line 2928 ---------------------------------------- . // many hash maps are created on a thread. To solve this performance . // trap we cache the first set of randomly generated keys per-thread. . // . // Later in #36481 it was discovered that exposing a deterministic . // iteration order allows a form of DOS attack. To counter that we . // increment one of the seeds on every RandomState creation, giving . // every corresponding HashMap a different iteration order. . thread_local!(static KEYS: Cell<(u64, u64)> = { 1 ( 0.00%) Cell::new(sys::hashmap_random_keys()) . }); . . KEYS.with(|keys| { 3 ( 0.00%) let (k0, k1) = keys.get(); . keys.set((k0.wrapping_add(1), k1)); . RandomState { k0, k1 } . }) . } . } . . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] . impl BuildHasher for RandomState { -- line 2948 ---------------------------------------- -- line 2967 ---------------------------------------- . /// Creates a new `DefaultHasher`. . /// . /// This hasher is not guaranteed to be the same as all other . /// `DefaultHasher` instances, but is the same as all other `DefaultHasher` . /// instances created through `new` or `default`. . #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] . #[allow(deprecated)] . #[must_use] 3 ( 0.00%) pub fn new() -> DefaultHasher { 12 ( 0.00%) DefaultHasher(SipHasher13::new_with_keys(0, 0)) 3 ( 0.00%) } . } . . #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] . impl Default for DefaultHasher { . /// Creates a new `DefaultHasher` using [`new`]. . /// See its documentation for more. . /// . /// [`new`]: DefaultHasher::new -- line 2985 ---------------------------------------- -- line 2986 ---------------------------------------- . fn default() -> DefaultHasher { . DefaultHasher::new() . } . } . . #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] . impl Hasher for DefaultHasher { . #[inline] 1,076 ( 0.00%) fn write(&mut self, msg: &[u8]) { . self.0.write(msg) 1,076 ( 0.00%) } . . #[inline] . fn finish(&self) -> u64 { . self.0.finish() . } . } . . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] -- line 3004 ---------------------------------------- -- line 3014 ---------------------------------------- . impl fmt::Debug for RandomState { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("RandomState").finish_non_exhaustive() . } . } . . #[inline] . fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> { 574,756 ( 0.00%) match raw { 368 ( 0.00%) base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }), 12,338 ( 0.00%) base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }), . } . } . . #[inline] . pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError { . match err { . hashbrown::TryReserveError::CapacityOverflow => { . TryReserveErrorKind::CapacityOverflow.into() -- line 3032 ---------------------------------------- -- line 3036 ---------------------------------------- . } . } . } . . #[inline] . fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>( . raw: base::RawEntryMut<'a, K, V, S>, . ) -> RawEntryMut<'a, K, V, S> { 162,870,826 ( 0.14%) match raw { . base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }), . base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }), . } . } . . #[allow(dead_code)] . fn assert_covariance() { . fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { -- line 3052 ---------------------------------------- 88,277,466 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 108,433,306 ( 0.09%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 81,324,978 ( 0.07%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 2,806,188 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 4,209,282 ( 0.00%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 27,809,863 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 6,845,480 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 13,690,960 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . . /// An entity in the Rust type system, which can be one of . /// several kinds (types, lifetimes, and consts). . /// To reduce memory usage, a `GenericArg` is an interned pointer, . /// with the lowest 2 bits being reserved for a tag to . /// indicate the type (`Ty`, `Region`, or `Const`) it points to. . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct GenericArg<'tcx> { 62,899,038 ( 0.05%) ptr: NonZeroUsize, 167,157,548 ( 0.14%) marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>, . } . . const TAG_MASK: usize = 0b11; . const TYPE_TAG: usize = 0b00; . const REGION_TAG: usize = 0b01; . const CONST_TAG: usize = 0b10; . 118,337 ( 0.00%) #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] . pub enum GenericArgKind<'tcx> { . Lifetime(ty::Region<'tcx>), . Type(Ty<'tcx>), . Const(&'tcx ty::Const<'tcx>), . } . . impl<'tcx> GenericArgKind<'tcx> { 26,761 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 26,761 ( 0.00%) let (tag, ptr) = match self { . GenericArgKind::Lifetime(lt) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0); . (REGION_TAG, lt as *const _ as usize) . } . GenericArgKind::Type(ty) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0); -- line 56 ---------------------------------------- -- line 58 ---------------------------------------- . } . GenericArgKind::Const(ct) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0); . (CONST_TAG, ct as *const _ as usize) . } . }; . 20,101,345 ( 0.02%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 26,761 ( 0.00%) } . } . . impl<'tcx> fmt::Debug for GenericArg<'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.fmt(f), . GenericArgKind::Type(ty) => ty.fmt(f), . GenericArgKind::Const(ct) => ct.fmt(f), . } . } . } . . impl<'tcx> Ord for GenericArg<'tcx> { 72 ( 0.00%) fn cmp(&self, other: &GenericArg<'_>) -> Ordering { 48 ( 0.00%) self.unpack().cmp(&other.unpack()) . } . } . . impl<'tcx> PartialOrd for GenericArg<'tcx> { . fn partial_cmp(&self, other: &GenericArg<'_>) -> Option { . Some(self.cmp(&other)) . } . } . . impl<'tcx> From> for GenericArg<'tcx> { 1,528,272 ( 0.00%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 1,528,272 ( 0.00%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 110,120,758 ( 0.09%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 110,120,758 ( 0.09%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { 17,618,293 ( 0.02%) fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() 17,618,293 ( 0.02%) } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 1,181,565,118 ( 1.01%) match ptr & TAG_MASK { 1,135,473 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 301,075,656 ( 0.26%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 708,858 ( 0.00%) CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)), . _ => intrinsics::unreachable(), . } . } . } . . /// Unpack the `GenericArg` as a type when it is known certainly to be a type. . /// This is true in cases where `Substs` is used in places where the kinds are known . /// to be limited (e.g. in tuples, where the only parameters are type parameters). . pub fn expect_ty(self) -> Ty<'tcx> { . match self.unpack() { . GenericArgKind::Type(ty) => ty, . _ => bug!("expected a type, but found another kind"), . } 315,138 ( 0.00%) } . . /// Unpack the `GenericArg` as a const when it is known certainly to be a const. . pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { . match self.unpack() { . GenericArgKind::Const(c) => c, . _ => bug!("expected a const, but found another kind"), . } . } -- line 140 ---------------------------------------- -- line 155 ---------------------------------------- . impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into), . GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into), 28,434 ( 0.00%) GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into), . } . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.visit_with(visitor), . GenericArgKind::Type(ty) => ty.visit_with(visitor), 2,948 ( 0.00%) GenericArgKind::Const(ct) => ct.visit_with(visitor), . } . } . } . . impl<'tcx, E: TyEncoder<'tcx>> Encodable for GenericArg<'tcx> { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { 146,263 ( 0.00%) self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 133,805 ( 0.00%) fn decode(d: &mut D) -> GenericArg<'tcx> { 133,805 ( 0.00%) GenericArgKind::decode(d).pack() . } . } . . /// A substitution mapping generic parameters to new values. . pub type InternalSubsts<'tcx> = List>; . . pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; . . impl<'a, 'tcx> InternalSubsts<'tcx> { . /// Interpret these substitutions as the substitutions of a closure type. . /// Closure substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and closure kind; . /// see `ty::ClosureSubsts` struct for more comments. 6,326 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 6,326 ( 0.00%) } . . /// Interpret these substitutions as the substitutions of a generator type. . /// Generator substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and generator kind; . /// see `ty::GeneratorSubsts` struct for more comments. . pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { . GeneratorSubsts { substs: self } . } -- line 208 ---------------------------------------- -- line 211 ---------------------------------------- . /// Inline const substitutions have a particular structure controlled by the . /// compiler that encodes information like the inferred type; . /// see `ty::InlineConstSubsts` struct for more comments. . pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { . InlineConstSubsts { substs: self } . } . . /// Creates an `InternalSubsts` that maps each generic parameter to itself. 282,440 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 184,760 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 254,196 ( 0.00%) } . . /// Creates an `InternalSubsts` for generic parameter definitions, . /// by calling closures to obtain each kind. . /// The closures get to observe the `InternalSubsts` as they're . /// being built, which can be used to correctly . /// substitute defaults of generic parameters. 93,496,873 ( 0.08%) pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . let defs = tcx.generics_of(def_id); . let count = defs.count(); . let mut substs = SmallVec::with_capacity(count); 31,264,368 ( 0.03%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 20,780,700 ( 0.02%) tcx.intern_substs(&substs) 93,513,915 ( 0.08%) } . . pub fn extend_to(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . Self::for_item(tcx, def_id, |param, substs| { . self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) . }) . } . 104,452,819 ( 0.09%) pub fn fill_item( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . tcx: TyCtxt<'tcx>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { 41,813,010 ( 0.04%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 121,843 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 83,553,888 ( 0.07%) } . 9,520 ( 0.00%) pub fn fill_single( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . substs.reserve(defs.params.len()); . for param in &defs.params { 4 ( 0.00%) let kind = mk_kind(param, substs); 6,599,480 ( 0.01%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } 9,520 ( 0.00%) } . . #[inline] . pub fn types(&'a self) -> impl DoubleEndedIterator> + 'a { . self.iter() . .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) . } . . #[inline] -- line 284 ---------------------------------------- -- line 302 ---------------------------------------- . self.iter().filter_map(|k| match k.unpack() { . GenericArgKind::Lifetime(_) => None, . generic => Some(generic), . }) . } . . #[inline] . pub fn type_at(&self, i: usize) -> Ty<'tcx> { 6,051,819 ( 0.01%) if let GenericArgKind::Type(ty) = self[i].unpack() { . ty . } else { . bug!("expected type for param #{} in {:?}", i, self); . } . } . . #[inline] . pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { -- line 318 ---------------------------------------- -- line 350 ---------------------------------------- . /// impl X for U { fn f() {} } . /// ``` . /// . /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. . /// * If `source_ancestor` is the def_id of the trait. . /// * If `target_substs` is `[U]`, the substs for the impl. . /// * Then we will return `[U, T]`, the subst for `f` in the impl that . /// are needed for it to match the trait. 428,484 ( 0.00%) pub fn rebase_onto( . &self, . tcx: TyCtxt<'tcx>, . source_ancestor: DefId, . target_substs: SubstsRef<'tcx>, . ) -> SubstsRef<'tcx> { . let defs = tcx.generics_of(source_ancestor); 122,424 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 489,696 ( 0.00%) } . 13 ( 0.00%) pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { . tcx.mk_substs(self.iter().take(generics.count())) 26 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { 219,809,331 ( 0.19%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // The match arms are in order of frequency. The 1, 2, and 0 cases are . // typically hit in 90--99.99% of cases. When folding doesn't change . // the substs, it's faster to reuse the existing substs rather than . // calling `intern_substs`. 412,389,348 ( 0.35%) match self.len() { . 1 => { 65,744,869 ( 0.06%) let param0 = self[0].try_fold_with(folder)?; 218,390,142 ( 0.19%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 19,817,237 ( 0.02%) let param0 = self[0].try_fold_with(folder)?; 57,065,350 ( 0.05%) let param1 = self[1].try_fold_with(folder)?; 72,330,183 ( 0.06%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 6,745,953 ( 0.01%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 11,433,142 ( 0.01%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 113,486 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 1,587,492 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 252,589,728 ( 0.22%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 16,817,849 ( 0.01%) self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . /////////////////////////////////////////////////////////////////////////// . // Public trait `Subst` . // . // Just call `foo.subst(tcx, substs)` to perform a substitution across . // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when -- line 420 ---------------------------------------- -- line 435 ---------------------------------------- . . impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T { . fn subst_spanned( . self, . tcx: TyCtxt<'tcx>, . substs: &[GenericArg<'tcx>], . span: Option, . ) -> T { 90,229,646 ( 0.08%) let mut folder = SubstFolder { tcx, substs, span, binders_passed: 0 }; . self.fold_with(&mut folder) . } . } . . /////////////////////////////////////////////////////////////////////////// . // The actual substitution engine itself is a type folder. . . struct SubstFolder<'a, 'tcx> { -- line 451 ---------------------------------------- -- line 456 ---------------------------------------- . span: Option, . . /// Number of region binders we have passed through while doing the substitution . binders_passed: u32, . } . . impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 6,214,219 ( 0.01%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 6,378,468 ( 0.01%) self.binders_passed += 1; 1,543,741 ( 0.00%) let t = t.super_fold_with(self); 6,378,468 ( 0.01%) self.binders_passed -= 1; . t . } . 4,243,590 ( 0.00%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . // Note: This routine only handles regions that are bound on . // type declarations and other outer declarations, not those . // bound in *fn types*. Region substitution of the bound . // regions that appear in a function signature is done using . // the specialized routine `ty::replace_late_regions()`. 1,414,530 ( 0.00%) match *r { 987,462 ( 0.00%) ty::ReEarlyBound(data) => { 987,462 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 493,731 ( 0.00%) Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), . _ => { . let span = self.span.unwrap_or(DUMMY_SP); . let msg = format!( . "Region parameter out of range \ . when substituting in region {} (index={})", . data.name, data.index . ); . span_bug!(span, "{}", msg); . } . } . } . _ => r, . } 4,950,855 ( 0.00%) } . 55,873,416 ( 0.05%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 18,624,472 ( 0.02%) if !t.needs_subst() { . return t; . } . 15,407,012 ( 0.01%) match *t.kind() { 28,184,760 ( 0.02%) ty::Param(p) => self.ty_for_param(p, t), 12,399,324 ( 0.01%) _ => t.super_fold_with(self), . } 82,789,590 ( 0.07%) } . 3,846,409 ( 0.00%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 3,278,829 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 1,021,644 ( 0.00%) c.super_fold_with(self) . } 3,487,768 ( 0.00%) } . . #[inline] . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } . . impl<'a, 'tcx> SubstFolder<'a, 'tcx> { . fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { . // Look up the type in the substitutions. It really should be in there. 11,273,904 ( 0.01%) let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ty = match opt_ty { . Some(GenericArgKind::Type(ty)) => ty, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected type for `{:?}` ({:?}/{}) but found {:?} \ . when substituting, substs={:?}", -- line 539 ---------------------------------------- -- line 562 ---------------------------------------- . } . . fn const_for_param( . &self, . p: ParamConst, . source_ct: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { . // Look up the const in the substitutions. It really should be in there. 871,942 ( 0.00%) let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ct = match opt_ct { . Some(GenericArgKind::Const(ct)) => ct, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected const for `{:?}` ({:?}/{}) but found {:?} \ . when substituting substs={:?}", -- line 578 ---------------------------------------- -- line 645 ---------------------------------------- . fn shift_vars_through_binders>(&self, val: T) -> T { . debug!( . "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", . val, . self.binders_passed, . val.has_escaping_bound_vars() . ); . 20,784,491 ( 0.02%) if self.binders_passed == 0 || !val.has_escaping_bound_vars() { . return val; . } . . let result = ty::fold::shift_vars(self.tcx(), val, self.binders_passed); . debug!("shift_vars: shifted result = {:?}", result); . . result . } . . fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { 1,044,936 ( 0.00%) if self.binders_passed == 0 || !region.has_escaping_bound_vars() { . return region; . } . ty::fold::shift_region(self.tcx, region, self.binders_passed) . } . } . . /// Stores the user-given substs to reach some fully qualified path . /// (e.g., `::Item` or `::Item`). . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 45,930 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSubsts<'tcx> { . /// The substitutions for the item as given by the user. 5 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The self type, in the case of a `::Item` path (when applied . /// to an inherent impl). See `UserSelfTy` below. 19,906 ( 0.00%) pub user_self_ty: Option>, . } . . /// Specifies the user-given self type. In the case of a path that . /// refers to a member in an inherent impl, this self type is . /// sometimes needed to constrain the type parameters on the impl. For . /// example, in this code: . /// . /// ``` -- line 689 ---------------------------------------- -- line 696 ---------------------------------------- . /// self type `Foo`. Then we can instantiate the parameters of . /// the impl (with the substs from `UserSubsts`) and apply those to . /// the self type, giving `Foo`. Finally, we unify that with . /// the self type here, which contains `?A` to be `&'static u32` . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSelfTy<'tcx> { . pub impl_def_id: DefId, 7,893 ( 0.00%) pub self_ty: Ty<'tcx>, . } 525,366,916 ( 0.45%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/instance.rs -------------------------------------------------------------------------------- Ir -- line 11 ---------------------------------------- . . use std::fmt; . . /// A monomorphized `InstanceDef`. . /// . /// Monomorphization happens on-the-fly and no monomorphized MIR is ever created. Instead, this type . /// simply couples a potentially generic `InstanceDef` with some substs, and codegen and const eval . /// will do all required substitution as they run. 100,342,684 ( 0.09%) #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable, Lift)] . pub struct Instance<'tcx> { 40,599,600 ( 0.03%) pub def: InstanceDef<'tcx>, 240 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . 121,654,143 ( 0.10%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 189,269 ( 0.00%) #[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub enum InstanceDef<'tcx> { . /// A user-defined callable item. . /// . /// This includes: . /// - `fn` items . /// - closures . /// - generators . Item(ty::WithOptConstParam), -- line 35 ---------------------------------------- -- line 80 ---------------------------------------- . /// The `DefId` is the ID of the `call_once` method in `FnOnce`. . ClosureOnceShim { call_once: DefId, track_caller: bool }, . . /// `core::ptr::drop_in_place::`. . /// . /// The `DefId` is for `core::ptr::drop_in_place`. . /// The `Option>` is either `Some(T)`, or `None` for empty drop . /// glue. 105 ( 0.00%) DropGlue(DefId, Option>), . . /// Compiler-generated `::clone` implementation. . /// . /// For all types that automatically implement `Copy`, a trivial `Clone` impl is provided too. . /// Additionally, arrays, tuples, and closures get a `Clone` shim even if they aren't `Copy`. . /// . /// The `DefId` is for `Clone::clone`, the `Ty` is the type `T` with the builtin `Clone` impl. . CloneShim(DefId, Ty<'tcx>), . } . . impl<'tcx> Instance<'tcx> { . /// Returns the `Ty` corresponding to this `Instance`, with generic substitutions applied and . /// lifetimes erased, allowing a `ParamEnv` to be specified for use during normalization. 176 ( 0.00%) pub fn ty(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Ty<'tcx> { 44 ( 0.00%) let ty = tcx.type_of(self.def.def_id()); 66 ( 0.00%) tcx.subst_and_normalize_erasing_regions(self.substs, param_env, &ty) 176 ( 0.00%) } . . /// Finds a crate that contains a monomorphization of this instance that . /// can be linked to from the local crate. A return value of `None` means . /// no upstream crate provides such an exported monomorphization. . /// . /// This method already takes into account the global `-Zshare-generics` . /// setting, always returning `None` if `share-generics` is off. 80 ( 0.00%) pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option { . // If we are not in share generics mode, we don't link to upstream . // monomorphizations but always instantiate our own internal versions . // instead. 30 ( 0.00%) if !tcx.sess.opts.share_generics() { . return None; . } . . // If this is an item that is defined in the local crate, no upstream . // crate can know about it/provide a monomorphization. 10 ( 0.00%) if self.def_id().is_local() { . return None; . } . . // If this a non-generic instance, it cannot be a shared monomorphization. 10 ( 0.00%) self.substs.non_erasable_generics().next()?; . 50 ( 0.00%) match self.def { 6 ( 0.00%) InstanceDef::Item(def) => tcx . .upstream_monomorphizations_for(def.did) . .and_then(|monos| monos.get(&self.substs).cloned()), . InstanceDef::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.substs), . _ => None, . } 90 ( 0.00%) } . } . . impl<'tcx> InstanceDef<'tcx> { . #[inline] . pub fn def_id(self) -> DefId { . match self { . InstanceDef::Item(def) => def.did, . InstanceDef::VtableShim(def_id) -- line 145 ---------------------------------------- -- line 150 ---------------------------------------- . | InstanceDef::ClosureOnceShim { call_once: def_id, track_caller: _ } . | InstanceDef::DropGlue(def_id, _) . | InstanceDef::CloneShim(def_id, _) => def_id, . } . } . . /// Returns the `DefId` of instances which might not require codegen locally. . pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option { 120 ( 0.00%) match self { . ty::InstanceDef::Item(def) => Some(def.did), . ty::InstanceDef::DropGlue(def_id, Some(_)) => Some(def_id), . InstanceDef::VtableShim(..) . | InstanceDef::ReifyShim(..) . | InstanceDef::FnPtrShim(..) . | InstanceDef::Virtual(..) . | InstanceDef::Intrinsic(..) . | InstanceDef::ClosureOnceShim { .. } . | InstanceDef::DropGlue(..) . | InstanceDef::CloneShim(..) => None, . } 16 ( 0.00%) } . . #[inline] . pub fn with_opt_param(self) -> ty::WithOptConstParam { 60,778 ( 0.00%) match self { . InstanceDef::Item(def) => def, . InstanceDef::VtableShim(def_id) . | InstanceDef::ReifyShim(def_id) . | InstanceDef::FnPtrShim(def_id, _) . | InstanceDef::Virtual(def_id, _) . | InstanceDef::Intrinsic(def_id) . | InstanceDef::ClosureOnceShim { call_once: def_id, track_caller: _ } . | InstanceDef::DropGlue(def_id, _) -- line 182 ---------------------------------------- -- line 189 ---------------------------------------- . tcx.get_attrs(self.def_id()) . } . . /// Returns `true` if the LLVM version of this instance is unconditionally . /// marked with `inline`. This implies that a copy of this instance is . /// generated in every codegen unit. . /// Note that this is only a hint. See the documentation for . /// `generates_cgu_internal_copy` for more information. 27 ( 0.00%) pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool { . use rustc_hir::definitions::DefPathData; 641 ( 0.00%) let def_id = match *self { 208 ( 0.00%) ty::InstanceDef::Item(def) => def.did, . ty::InstanceDef::DropGlue(_, Some(_)) => return false, . _ => return true, . }; 312 ( 0.00%) matches!( . tcx.def_key(def_id).disambiguated_data.data, . DefPathData::Ctor | DefPathData::ClosureExpr . ) 54 ( 0.00%) } . . /// Returns `true` if the machine code for this instance is instantiated in . /// each codegen unit that references it. . /// Note that this is only a hint! The compiler can globally decide to *not* . /// do this in order to speed up compilation. CGU-internal copies are . /// only exist to enable inlining. If inlining is not performed (e.g. at . /// `-Copt-level=0`) then the time for generating them is wasted and it's . /// better to create a single copy with external linkage. 765 ( 0.00%) pub fn generates_cgu_internal_copy(&self, tcx: TyCtxt<'tcx>) -> bool { 89 ( 0.00%) if self.requires_inline(tcx) { . return true; . } 162 ( 0.00%) if let ty::InstanceDef::DropGlue(.., Some(ty)) = *self { . // Drop glue generally wants to be instantiated at every codegen . // unit, but without an #[inline] hint. We should make this . // available to normal end-users. . if tcx.sess.opts.incremental.is_none() { . return true; . } . // When compiling with incremental, we can generate a *lot* of . // codegen units. Including drop glue into all of them has a -- line 229 ---------------------------------------- -- line 234 ---------------------------------------- . // `#[inline]` on `Drop::drop` implementations. . return ty.ty_adt_def().map_or(true, |adt_def| { . adt_def.destructor(tcx).map_or_else( . || adt_def.is_enum(), . |dtor| tcx.codegen_fn_attrs(dtor.did).requests_inline(), . ) . }); . } 162 ( 0.00%) tcx.codegen_fn_attrs(self.def_id()).requests_inline() 765 ( 0.00%) } . 736 ( 0.00%) pub fn requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool { 468 ( 0.00%) match *self { . InstanceDef::Item(ty::WithOptConstParam { did: def_id, .. }) . | InstanceDef::Virtual(def_id, _) => { 264 ( 0.00%) tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::TRACK_CALLER) . } . InstanceDef::ClosureOnceShim { call_once: _, track_caller } => track_caller, . _ => false, . } 736 ( 0.00%) } . . /// Returns `true` when the MIR body associated with this instance should be monomorphized . /// by its users (e.g. codegen or miri) by substituting the `substs` from `Instance` (see . /// `Instance::substs_for_mir_body`). . /// . /// Otherwise, returns `false` only for some kinds of shims where the construction of the MIR . /// body should perform necessary substitutions. . pub fn has_polymorphic_mir_body(&self) -> bool { 357,206 ( 0.00%) match *self { . InstanceDef::CloneShim(..) . | InstanceDef::FnPtrShim(..) . | InstanceDef::DropGlue(_, Some(_)) => false, . InstanceDef::ClosureOnceShim { .. } . | InstanceDef::DropGlue(..) . | InstanceDef::Item(_) . | InstanceDef::Intrinsic(..) . | InstanceDef::ReifyShim(..) -- line 271 ---------------------------------------- -- line 295 ---------------------------------------- . InstanceDef::DropGlue(_, None) => write!(f, " - shim(None)"), . InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({}))", ty), . InstanceDef::CloneShim(_, ty) => write!(f, " - shim({})", ty), . } . } . } . . impl<'tcx> Instance<'tcx> { 81,928 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> Instance<'tcx> { . assert!( . !substs.has_escaping_bound_vars(), . "substs of instance {:?} not normalized for codegen: {:?}", . def_id, . substs . ); 29,685 ( 0.00%) Instance { def: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)), substs } 52,668 ( 0.00%) } . 1,105 ( 0.00%) pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> { 518 ( 0.00%) let substs = InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind { 8 ( 0.00%) ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), . ty::GenericParamDefKind::Type { .. } => { . bug!("Instance::mono: {:?} has type parameters", def_id) . } . ty::GenericParamDefKind::Const { .. } => { . bug!("Instance::mono: {:?} has const parameters", def_id) . } . }); . 510 ( 0.00%) Instance::new(def_id, substs) 765 ( 0.00%) } . . #[inline] . pub fn def_id(&self) -> DefId { 534 ( 0.00%) self.def.def_id() . } . . /// Resolves a `(def_id, substs)` pair to an (optional) instance -- most commonly, . /// this is used to find the precise code that will run for a trait method invocation, . /// if known. . /// . /// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance. . /// For example, in a context like this, -- line 337 ---------------------------------------- -- line 347 ---------------------------------------- . /// Presuming that coherence and type-check have succeeded, if this method is invoked . /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return . /// `Ok(Some(instance))`. . /// . /// Returns `Err(ErrorReported)` when the `Instance` resolution process . /// couldn't complete due to errors elsewhere - this is distinct . /// from `Ok(None)` to avoid misleading diagnostics when an error . /// has already been/will be emitted, for the original cause 26,660 ( 0.00%) pub fn resolve( . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . def_id: DefId, . substs: SubstsRef<'tcx>, . ) -> Result>, ErrorReported> { 26,905 ( 0.00%) Instance::resolve_opt_const_arg( . tcx, . param_env, . ty::WithOptConstParam::unknown(def_id), . substs, . ) 39,990 ( 0.00%) } . . // This should be kept up to date with `resolve`. 80,333,760 ( 0.07%) #[instrument(level = "debug", skip(tcx))] 130,542,360 ( 0.11%) pub fn resolve_opt_const_arg( . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . def: ty::WithOptConstParam, . substs: SubstsRef<'tcx>, . ) -> Result>, ErrorReported> { . // All regions in the result of this query are erased, so it's . // fine to erase all of the input regions. . . // HACK(eddyb) erase regions in `substs` first, so that `param_env.and(...)` . // below is more likely to ignore the bounds in scope (e.g. if the only . // generic parameters mentioned by `substs` were lifetime ones). . let substs = tcx.erase_regions(substs); . . // FIXME(eddyb) should this always use `param_env.with_reveal_all()`? 20,056,328 ( 0.02%) if let Some((did, param_did)) = def.as_const_arg() { . tcx.resolve_instance_of_const_arg( 130,366,132 ( 0.11%) tcx.erase_regions(param_env.and((did, param_did, substs))), . ) . } else { 122,004 ( 0.00%) tcx.resolve_instance(tcx.erase_regions(param_env.and((def.did, substs)))) . } . } . 645 ( 0.00%) pub fn resolve_for_fn_ptr( . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . def_id: DefId, . substs: SubstsRef<'tcx>, . ) -> Option> { . debug!("resolve(def_id={:?}, substs={:?})", def_id, substs); . // Use either `resolve_closure` or `resolve_for_vtable` 43 ( 0.00%) assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {:?}", def_id); . Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| { 172 ( 0.00%) match resolved.def { 172 ( 0.00%) InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => { . debug!(" => fn pointer created for function with #[track_caller]"); . resolved.def = InstanceDef::ReifyShim(def.did); . } . InstanceDef::Virtual(def_id, _) => { . debug!(" => fn pointer created for virtual call"); . resolved.def = InstanceDef::ReifyShim(def_id); . } . _ => {} . } . 516 ( 0.00%) resolved . }) 387 ( 0.00%) } . 20 ( 0.00%) pub fn resolve_for_vtable( . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . def_id: DefId, . substs: SubstsRef<'tcx>, . ) -> Option> { . debug!("resolve_for_vtable(def_id={:?}, substs={:?})", def_id, substs); . let fn_sig = tcx.fn_sig(def_id); 4 ( 0.00%) let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty() . && fn_sig.input(0).skip_binder().is_param(0) . && tcx.generics_of(def_id).has_self; . if is_vtable_shim { . debug!(" => associated item with unsizeable self: Self"); . Some(Instance { def: InstanceDef::VtableShim(def_id), substs }) . } else { . Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| { 8 ( 0.00%) match resolved.def { 6 ( 0.00%) InstanceDef::Item(def) => { . // We need to generate a shim when we cannot guarantee that . // the caller of a trait object method will be aware of . // `#[track_caller]` - this ensures that the caller . // and callee ABI will always match. . // . // The shim is generated when all of these conditions are met: . // . // 1) The underlying method expects a caller location parameter . // in the ABI 8 ( 0.00%) if resolved.def.requires_caller_location(tcx) . // 2) The caller location parameter comes from having `#[track_caller]` . // on the implementation, and *not* on the trait method. . && !tcx.should_inherit_track_caller(def.did) . // If the method implementation comes from the trait definition itself . // (e.g. `trait Foo { #[track_caller] my_fn() { /* impl */ } }`), . // then we don't need to generate a shim. This check is needed because . // `should_inherit_track_caller` returns `false` if our method . // implementation comes from the trait block, and not an impl block -- line 456 ---------------------------------------- -- line 480 ---------------------------------------- . } . InstanceDef::Virtual(def_id, _) => { . debug!(" => vtable fn pointer created for virtual call"); . resolved.def = InstanceDef::ReifyShim(def_id); . } . _ => {} . } . 34 ( 0.00%) resolved . }) . } 16 ( 0.00%) } . . pub fn resolve_closure( . tcx: TyCtxt<'tcx>, . def_id: DefId, . substs: ty::SubstsRef<'tcx>, . requested_kind: ty::ClosureKind, . ) -> Instance<'tcx> { . let actual_kind = substs.as_closure().kind(); . . match needs_fn_once_adapter_shim(actual_kind, requested_kind) { . Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs), . _ => Instance::new(def_id, substs), . } . } . 32 ( 0.00%) pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> { . let def_id = tcx.require_lang_item(LangItem::DropInPlace, None); 12 ( 0.00%) let substs = tcx.intern_substs(&[ty.into()]); . Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap().unwrap() 28 ( 0.00%) } . . pub fn fn_once_adapter_instance( . tcx: TyCtxt<'tcx>, . closure_did: DefId, . substs: ty::SubstsRef<'tcx>, . ) -> Instance<'tcx> { . debug!("fn_once_adapter_shim({:?}, {:?})", closure_did, substs); . let fn_once = tcx.require_lang_item(LangItem::FnOnce, None); -- line 519 ---------------------------------------- -- line 544 ---------------------------------------- . /// In the former case, we want to substitute those generic types and replace them with the . /// values from the substs when monomorphizing the function body. But in the latter case, we . /// don't want to do that substitution, since it has already been done effectively. . /// . /// This function returns `Some(substs)` in the former case and `None` otherwise -- i.e., if . /// this function returns `None`, then the MIR body does not require substitution during . /// codegen. . fn substs_for_mir_body(&self) -> Option> { 142,876 ( 0.00%) if self.def.has_polymorphic_mir_body() { Some(self.substs) } else { None } 71,438 ( 0.00%) } . . pub fn subst_mir(&self, tcx: TyCtxt<'tcx>, v: &T) -> T . where . T: TypeFoldable<'tcx> + Copy, . { . if let Some(substs) = self.substs_for_mir_body() { v.subst(tcx, substs) } else { *v } . } . -- line 561 ---------------------------------------- -- line 564 ---------------------------------------- . &self, . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . v: T, . ) -> T . where . T: TypeFoldable<'tcx> + Clone, . { 1,076 ( 0.00%) if let Some(substs) = self.substs_for_mir_body() { 514 ( 0.00%) tcx.subst_and_normalize_erasing_regions(substs, param_env, v) . } else { . tcx.normalize_erasing_regions(param_env, v) . } . } . . #[inline(always)] . pub fn try_subst_mir_and_normalize_erasing_regions( . &self, . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . v: T, . ) -> Result> . where . T: TypeFoldable<'tcx> + Clone, . { 213,381 ( 0.00%) if let Some(substs) = self.substs_for_mir_body() { 216,612 ( 0.00%) tcx.try_subst_and_normalize_erasing_regions(substs, param_env, v) . } else { . tcx.try_normalize_erasing_regions(param_env, v) . } . } . . /// Returns a new `Instance` where generic parameters in `instance.substs` are replaced by . /// identity parameters if they are determined to be unused in `instance.def`. 155 ( 0.00%) pub fn polymorphize(self, tcx: TyCtxt<'tcx>) -> Self { . debug!("polymorphize: running polymorphization analysis"); 99 ( 0.00%) if !tcx.sess.opts.debugging_opts.polymorphize { 132 ( 0.00%) return self; . } . . let polymorphized_substs = polymorphize(tcx, self.def, self.substs); . debug!("polymorphize: self={:?} polymorphized_substs={:?}", self, polymorphized_substs); . Self { def: self.def, substs: polymorphized_substs } 155 ( 0.00%) } . } . . fn polymorphize<'tcx>( . tcx: TyCtxt<'tcx>, . instance: ty::InstanceDef<'tcx>, . substs: SubstsRef<'tcx>, . ) -> SubstsRef<'tcx> { . debug!("polymorphize({:?}, {:?})", instance, substs); -- line 615 ---------------------------------------- -- line 632 ---------------------------------------- . debug!("polymorphize: upvars_ty={:?} has_upvars={:?}", upvars_ty, has_upvars); . . struct PolymorphizationFolder<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl<'tcx> ty::TypeFolder<'tcx> for PolymorphizationFolder<'tcx> { . fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { 15,739,331 ( 0.01%) self.tcx 15,739,331 ( 0.01%) } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { . debug!("fold_ty: ty={:?}", ty); . match ty.kind { . ty::Closure(def_id, substs) => { . let polymorphized_substs = polymorphize( . self.tcx, . ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)), -- line 649 ---------------------------------------- 151,360,825 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_query_system/src/query/caches.rs -------------------------------------------------------------------------------- Ir -- line 94 ---------------------------------------- . &self, . state: &'s QueryCacheStore, . key: &K, . on_hit: OnHit, . ) -> Result . where . OnHit: FnOnce(&V, DepNodeIndex) -> R, . { 64,211,748 ( 0.06%) let (lookup, lock) = state.get_lookup(key); . let result = lock.raw_entry().from_key_hashed_nocheck(lookup.key_hash, key); . 293,102,279 ( 0.25%) if let Some((_, value)) = result { 168,377,440 ( 0.14%) let hit_result = on_hit(&value.0, value.1); 95,315,185 ( 0.08%) Ok(hit_result) . } else { 721,568 ( 0.00%) Err(lookup) . } . } . . #[inline] . fn complete( . &self, . lock_sharded_storage: &mut Self::Sharded, . key: K, . value: V, . index: DepNodeIndex, . ) -> Self::Stored { 795,802 ( 0.00%) lock_sharded_storage.insert(key, (value.clone(), index)); 44,122 ( 0.00%) value . } . . fn iter( . &self, . shards: &Sharded, . f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex), . ) { . let shards = shards.lock_shards(); -- line 130 ---------------------------------------- -- line 178 ---------------------------------------- . &self, . state: &'s QueryCacheStore, . key: &K, . on_hit: OnHit, . ) -> Result . where . OnHit: FnOnce(&&'tcx V, DepNodeIndex) -> R, . { 478,550 ( 0.00%) let (lookup, lock) = state.get_lookup(key); . let result = lock.raw_entry().from_key_hashed_nocheck(lookup.key_hash, key); . 41,809,148 ( 0.04%) if let Some((_, value)) = result { 44,090,356 ( 0.04%) let hit_result = on_hit(&&value.0, value.1); 913,364 ( 0.00%) Ok(hit_result) . } else { 59,553 ( 0.00%) Err(lookup) . } . } . . #[inline] . fn complete( . &self, . lock_sharded_storage: &mut Self::Sharded, . key: K, . value: V, . index: DepNodeIndex, . ) -> Self::Stored { 587,257 ( 0.00%) let value = self.arena.alloc((value, index)); . let value = unsafe { &*(value as *const _) }; . lock_sharded_storage.insert(key, value); . &value.0 . } . . fn iter( . &self, . shards: &Sharded, -- line 213 ---------------------------------------- 201,512,043 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/query.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . TyCtxtEnsure { tcx: self } . } . . /// Returns a transparent wrapper for `TyCtxt` which uses . /// `span` as the location of queries performed through it. . #[inline(always)] . pub fn at(self, span: Span) -> TyCtxtAt<'tcx> { . TyCtxtAt { tcx: self, span } 11 ( 0.00%) } . . pub fn try_mark_green(self, dep_node: &dep_graph::DepNode) -> bool { . self.queries.try_mark_green(self, dep_node) . } . } . . /// Helper for `TyCtxtEnsure` to avoid a closure. . #[inline(always)] -- line 107 ---------------------------------------- -- line 198 ---------------------------------------- . } . #[allow(nonstandard_style, unused_lifetimes)] . pub mod query_stored { . use super::*; . . $(pub type $name<$tcx> = as QueryStorage>::Stored;)* . } . 530 ( 0.00%) #[derive(Default)] . pub struct QueryCaches<$tcx> { . $($(#[$attr])* pub $name: QueryCacheStore>,)* . } . . impl<$tcx> TyCtxtEnsure<$tcx> { . $($(#[$attr])* . #[inline(always)] . pub fn $name(self, key: query_helper_param_ty!($($K)*)) { 157,853 ( 0.00%) let key = key.into_query_param(); . opt_remap_env_constness!([$($modifiers)*][key]); . 110,335 ( 0.00%) let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, noop); . 44,134 ( 0.00%) let lookup = match cached { . Ok(()) => return, 38,773 ( 0.00%) Err(lookup) => lookup, . }; . 1,040,323 ( 0.00%) self.tcx.queries.$name(self.tcx, DUMMY_SP, key, lookup, QueryMode::Ensure); . })* . } . . impl<$tcx> TyCtxt<$tcx> { . $($(#[$attr])* . #[inline(always)] . #[must_use] . pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx> . { 10,041,720 ( 0.01%) self.at(DUMMY_SP).$name(key) . })* . } . . impl<$tcx> TyCtxtAt<$tcx> { . $($(#[$attr])* . #[inline(always)] . pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<$tcx> . { 322,008,537 ( 0.28%) let key = key.into_query_param(); 731,530 ( 0.00%) opt_remap_env_constness!([$($modifiers)*][key]); . 33,512,518 ( 0.03%) let cached = try_get_cached(self.tcx, &self.tcx.query_caches.$name, &key, Clone::clone); . 30,953,891 ( 0.03%) let lookup = match cached { 15,508,815 ( 0.01%) Ok(value) => return value, 242,840 ( 0.00%) Err(lookup) => lookup, . }; . 9,215,177 ( 0.01%) self.tcx.queries.$name(self.tcx, self.span, key, lookup, QueryMode::Get).unwrap() 28,015,015 ( 0.02%) })* . } . . pub struct Providers { . $(pub $name: for<'tcx> fn( . TyCtxt<'tcx>, . query_keys::$name<'tcx>, . ) -> query_values::$name<'tcx>,)* . } . . pub struct ExternProviders { . $(pub $name: separate_provide_extern_decl!([$($modifiers)*][$name]),)* . } . . impl Default for Providers { 1 ( 0.00%) fn default() -> Self { 524 ( 0.00%) Providers { . $($name: |_, key| bug!( . "`tcx.{}({:?})` unsupported by its crate; \ . perhaps the `{}` query was never assigned a provider function", . stringify!($name), . key, . stringify!($name), . ),)* . } 1 ( 0.00%) } . } . . impl Default for ExternProviders { 1 ( 0.00%) fn default() -> Self { 158 ( 0.00%) ExternProviders { . $($name: separate_provide_extern_default!([$($modifiers)*][$name]),)* . } 1 ( 0.00%) } . } . . impl Copy for Providers {} . impl Clone for Providers { . fn clone(&self) -> Self { *self } . } . . impl Copy for ExternProviders {} -- line 296 ---------------------------------------- -- line 354 ---------------------------------------- . self.to_def_id() . } . } . } . . use sealed::IntoQueryParam; . . impl<'tcx> TyCtxt<'tcx> { 6,343,883 ( 0.01%) pub fn def_kind(self, def_id: impl IntoQueryParam) -> DefKind { 1,812,538 ( 0.00%) let def_id = def_id.into_query_param(); . self.opt_def_kind(def_id) . .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id)) 7,250,152 ( 0.01%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { 3,864 ( 0.00%) pub fn def_kind(self, def_id: impl IntoQueryParam) -> DefKind { 1,104 ( 0.00%) let def_id = def_id.into_query_param(); . self.opt_def_kind(def_id) . .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", def_id)) 4,416 ( 0.00%) } . } 148,477,636 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . fn default() -> FxHasher { . FxHasher { hash: 0 } . } . } . . impl FxHasher { . #[inline] . fn add_to_hash(&mut self, i: usize) { 152,016,987 ( 0.13%) self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K); . } . } . . impl Hasher for FxHasher { . #[inline] 10,152,158 ( 0.01%) fn write(&mut self, mut bytes: &[u8]) { . #[cfg(target_pointer_width = "32")] . let read_usize = |bytes: &[u8]| u32::from_ne_bytes(bytes[..4].try_into().unwrap()); . #[cfg(target_pointer_width = "64")] . let read_usize = |bytes: &[u8]| u64::from_ne_bytes(bytes[..8].try_into().unwrap()); . 10,418,329 ( 0.01%) let mut hash = FxHasher { hash: self.hash }; . assert!(size_of::() <= 8); 225,813,959 ( 0.19%) while bytes.len() >= size_of::() { . hash.add_to_hash(read_usize(bytes) as usize); . bytes = &bytes[size_of::()..]; . } 20,850,516 ( 0.02%) if (size_of::() > 4) && (bytes.len() >= 4) { . hash.add_to_hash(u32::from_ne_bytes(bytes[..4].try_into().unwrap()) as usize); . bytes = &bytes[4..]; . } 20,850,516 ( 0.02%) if (size_of::() > 2) && bytes.len() >= 2 { . hash.add_to_hash(u16::from_ne_bytes(bytes[..2].try_into().unwrap()) as usize); . bytes = &bytes[2..]; . } 20,912,011 ( 0.02%) if (size_of::() > 1) && bytes.len() >= 1 { 141,578 ( 0.00%) hash.add_to_hash(bytes[0] as usize); . } 10,157,485 ( 0.01%) self.hash = hash.hash; 10,152,158 ( 0.01%) } . . #[inline] . fn write_u8(&mut self, i: u8) { 11,057 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u16(&mut self, i: u16) { 16,753 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u32(&mut self, i: u32) { 29,838,918 ( 0.03%) self.add_to_hash(i as usize); . } . . #[cfg(target_pointer_width = "32")] . #[inline] . fn write_u64(&mut self, i: u64) { . self.add_to_hash(i as usize); . self.add_to_hash((i >> 32) as usize); . } -- line 131 ---------------------------------------- 349 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . PushRegionObligation, . } . . macro_rules! impl_from { . ($($ctor: ident ($ty: ty),)*) => { . $( . impl<'tcx> From<$ty> for UndoLog<'tcx> { . fn from(x: $ty) -> Self { 105,701 ( 0.00%) UndoLog::$ctor(x.into()) . } . } . )* . } . } . . // Upcast from a single kind of "undoable action" to the general enum . impl_from! { -- line 44 ---------------------------------------- -- line 57 ---------------------------------------- . ConstUnificationTable(sv::UndoLog>>), . . RegionUnificationTable(sv::UndoLog>>), . ProjectionCache(traits::UndoLog<'tcx>), . } . . /// The Rollback trait defines how to rollback a particular action. . impl<'tcx> Rollback> for InferCtxtInner<'tcx> { 32,900,526 ( 0.03%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 54,834,210 ( 0.05%) match undo { 29,391,340 ( 0.03%) UndoLog::TypeVariables(undo) => self.type_variable_storage.reverse(undo), 13,182,842 ( 0.01%) UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo), 3,108 ( 0.00%) UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo), 584 ( 0.00%) UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo), . UndoLog::RegionConstraintCollector(undo) => { 5,156,011 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().reverse(undo) . } . UndoLog::RegionUnificationTable(undo) => { 1,293,022 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().unification_table.reverse(undo) . } . UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo), . UndoLog::PushRegionObligation => { . self.region_obligations.pop(); . } . } 43,867,368 ( 0.04%) } . } . . /// The combined undo log for all the various unification tables. For each change to the storage . /// for any kind of inference variable, we record an UndoLog entry in the vector here. . pub(crate) struct InferCtxtUndoLogs<'tcx> { . logs: Vec>, . num_open_snapshots: usize, . } . . impl Default for InferCtxtUndoLogs<'_> { . fn default() -> Self { 544,390 ( 0.00%) Self { logs: Default::default(), num_open_snapshots: Default::default() } . } . } . . /// The UndoLogs trait defines how we undo a particular kind of action (of type T). We can undo any . /// action that is convertable into an UndoLog (per the From impls above). . impl<'tcx, T> UndoLogs for InferCtxtUndoLogs<'tcx> . where . UndoLog<'tcx>: From, -- line 102 ---------------------------------------- -- line 103 ---------------------------------------- . { . #[inline] . fn num_open_snapshots(&self) -> usize { . self.num_open_snapshots . } . . #[inline] . fn push(&mut self, undo: T) { 1,851,729 ( 0.00%) if self.in_snapshot() { 845,608 ( 0.00%) self.logs.push(undo.into()) . } . } . . fn clear(&mut self) { . self.logs.clear(); . self.num_open_snapshots = 0; . } . -- line 120 ---------------------------------------- -- line 125 ---------------------------------------- . { . if self.in_snapshot() { . self.logs.extend(undos.into_iter().map(UndoLog::from)) . } . } . } . . impl<'tcx> InferCtxtInner<'tcx> { 92,166,588 ( 0.08%) pub fn rollback_to(&mut self, snapshot: Snapshot<'tcx>) { . debug!("rollback_to({})", snapshot.undo_len); . self.undo_log.assert_open_snapshot(&snapshot); . 63,622,722 ( 0.05%) while self.undo_log.logs.len() > snapshot.undo_len { . let undo = self.undo_log.logs.pop().unwrap(); 131,602,104 ( 0.11%) self.reverse(undo); . } . 37,746,013 ( 0.03%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 1,177,552 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 46,672,070 ( 0.04%) self.undo_log.num_open_snapshots -= 1; 107,527,686 ( 0.09%) } . . pub fn commit(&mut self, snapshot: Snapshot<'tcx>) { . debug!("commit({})", snapshot.undo_len); . 34,367,805 ( 0.03%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 1,057,210 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 34,896,410 ( 0.03%) self.undo_log.num_open_snapshots -= 1; . } . } . . impl<'tcx> InferCtxtUndoLogs<'tcx> { . pub fn start_snapshot(&mut self) -> Snapshot<'tcx> { 107,268,132 ( 0.09%) self.num_open_snapshots += 1; . Snapshot { undo_len: self.logs.len(), _marker: PhantomData } . } . . pub(crate) fn region_constraints_in_snapshot( . &self, . s: &Snapshot<'tcx>, . ) -> impl Iterator> + Clone { 10,677,902 ( 0.01%) self.logs[s.undo_len..].iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . pub(crate) fn region_constraints( . &self, . ) -> impl Iterator> + Clone { 135 ( 0.00%) self.logs.iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) { . // Failures here may indicate a failure to follow a stack discipline. 46,083,294 ( 0.04%) assert!(self.logs.len() >= snapshot.undo_len); 46,083,294 ( 0.04%) assert!(self.num_open_snapshots > 0); . } . } . . impl<'tcx> std::ops::Index for InferCtxtUndoLogs<'tcx> { . type Output = UndoLog<'tcx>; . . fn index(&self, key: usize) -> &Self::Output { . &self.logs[key] -- line 204 ---------------------------------------- 73,302,558 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs -------------------------------------------------------------------------------- Ir -- line 193 ---------------------------------------- . /// assert_eq!(a.iter().count(), 5); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn count(self) -> usize . where . Self: Sized, . { 24,097 ( 0.00%) self.fold( . 0, . #[rustc_inherit_overflow_checks] 115,380 ( 0.00%) |count, _| count + 1, . ) . } . . /// Consumes the iterator, returning the last element. . /// . /// This method will evaluate the iterator until it returns [`None`]. While . /// doing so, it keeps track of the current element. After [`None`] is . /// returned, `last()` will then return the last element it saw. -- line 212 ---------------------------------------- -- line 267 ---------------------------------------- . /// assert_eq!(iter.next(), Some(&3)); . /// assert_eq!(iter.advance_by(0), Ok(())); . /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped . /// ``` . #[inline] . #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . for i in 0..n { 12,997 ( 0.00%) self.next().ok_or(i)?; . } . Ok(()) . } . . /// Returns the `n`th element of the iterator. . /// . /// Like most indexing operations, the count starts from zero, so `nth(0)` . /// returns the first value, `nth(1)` the second, and so on. -- line 283 ---------------------------------------- -- line 313 ---------------------------------------- . /// Returning `None` if there are less than `n + 1` elements: . /// . /// ``` . /// let a = [1, 2, 3]; . /// assert_eq!(a.iter().nth(10), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 664 ( 0.00%) fn nth(&mut self, n: usize) -> Option { . self.advance_by(n).ok()?; 23,013 ( 0.00%) self.next() . } . . /// Creates an iterator starting at the same point, but stepping by . /// the given amount at each iteration. . /// . /// Note 1: The first element of the iterator will always be returned, . /// regardless of the step given. . /// -- line 331 ---------------------------------------- -- line 441 ---------------------------------------- . /// [`OsStr`]: ../../std/ffi/struct.OsStr.html . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn chain(self, other: U) -> Chain . where . Self: Sized, . U: IntoIterator, . { 209,972 ( 0.00%) Chain::new(self, other.into_iter()) . } . . /// 'Zips up' two iterators into a single iterator of pairs. . /// . /// `zip()` returns a new iterator that will iterate over two other . /// iterators, returning a tuple where the first element comes from the . /// first iterator, and the second element comes from the second iterator. . /// -- line 457 ---------------------------------------- -- line 555 ---------------------------------------- . /// [`zip`]: crate::iter::zip . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn zip(self, other: U) -> Zip . where . Self: Sized, . U: IntoIterator, . { 819 ( 0.00%) Zip::new(self, other.into_iter()) . } . . /// Creates a new iterator which places a copy of `separator` between adjacent . /// items of the original iterator. . /// . /// In case `separator` does not implement [`Clone`] or needs to be . /// computed every time, use [`intersperse_with`]. . /// -- line 571 ---------------------------------------- -- line 714 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn map(self, f: F) -> Map . where . Self: Sized, . F: FnMut(Self::Item) -> B, . { 1,605,982 ( 0.00%) Map::new(self, f) . } . . /// Calls a closure on each element of an iterator. . /// . /// This is equivalent to using a [`for`] loop on the iterator, although . /// `break` and `continue` are not possible from a closure. It's generally . /// more idiomatic to use a `for` loop, but `for_each` may be more legible . /// when processing items at the end of longer iterator chains. In some -- line 730 ---------------------------------------- -- line 761 ---------------------------------------- . #[stable(feature = "iterator_for_each", since = "1.21.0")] . fn for_each(self, f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . #[inline] . fn call(mut f: impl FnMut(T)) -> impl FnMut((), T) { 10,035 ( 0.00%) move |(), item| f(item) . } . 19,585,523 ( 0.02%) self.fold((), call(f)); . } . . /// Creates an iterator which uses a closure to determine if an element . /// should be yielded. . /// . /// Given an element the closure must return `true` or `false`. The returned . /// iterator will yield only the elements for which the closure returns . /// true. -- line 780 ---------------------------------------- -- line 834 ---------------------------------------- . /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn filter

(self, predicate: P) -> Filter . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 3,759,219 ( 0.00%) Filter::new(self, predicate) . } . . /// Creates an iterator that both filters and maps. . /// . /// The returned iterator yields only the `value`s for which the supplied . /// closure returns `Some(value)`. . /// . /// `filter_map` can be used to make chains of [`filter`] and [`map`] more -- line 850 ---------------------------------------- -- line 879 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn filter_map(self, f: F) -> FilterMap . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 86,143 ( 0.00%) FilterMap::new(self, f) . } . . /// Creates an iterator which gives the current iteration count as well as . /// the next value. . /// . /// The iterator returned yields pairs `(i, val)`, where `i` is the . /// current index of iteration and `val` is the value returned by the . /// iterator. -- line 895 ---------------------------------------- -- line 995 ---------------------------------------- . /// [`peek_mut`]: Peekable::peek_mut . /// [`next`]: Iterator::next . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn peekable(self) -> Peekable . where . Self: Sized, . { 13 ( 0.00%) Peekable::new(self) . } . . /// Creates an iterator that [`skip`]s elements based on a predicate. . /// . /// [`skip`]: Iterator::skip . /// . /// `skip_while()` takes a closure as an argument. It will call this . /// closure on each element of the iterator, and ignore elements -- line 1011 ---------------------------------------- -- line 1537 ---------------------------------------- . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn fuse(self) -> Fuse . where . Self: Sized, . { 70,384 ( 0.00%) Fuse::new(self) . } . . /// Does something with each element of an iterator, passing the value on. . /// . /// When using iterators, you'll often chain several of them together. . /// While working on such code, you might want to check out what's . /// happening at various parts in the pipeline. To do that, insert . /// a call to `inspect()`. -- line 1553 ---------------------------------------- -- line 1769 ---------------------------------------- . /// [`char`]: type@char . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] . fn collect>(self) -> B . where . Self: Sized, . { 184,927 ( 0.00%) FromIterator::from_iter(self) . } . . /// Consumes an iterator, creating two collections from it. . /// . /// The predicate passed to `partition()` can return `true`, or `false`. . /// `partition()` returns a pair, all of the elements for which it returned . /// `true`, and all of the elements for which it returned `false`. . /// -- line 1785 ---------------------------------------- -- line 1798 ---------------------------------------- . /// let (even, odd): (Vec, Vec) = a . /// .iter() . /// .partition(|&n| n % 2 == 0); . /// . /// assert_eq!(even, vec![2]); . /// assert_eq!(odd, vec![1, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 6,376 ( 0.00%) fn partition(self, f: F) -> (B, B) . where . Self: Sized, . B: Default + Extend, . F: FnMut(&Self::Item) -> bool, . { . #[inline] . fn extend<'a, T, B: Extend>( . mut f: impl FnMut(&T) -> bool + 'a, . left: &'a mut B, . right: &'a mut B, . ) -> impl FnMut((), T) + 'a { . move |(), x| { 480 ( 0.00%) if f(&x) { . left.extend_one(x); . } else { . right.extend_one(x); . } . } . } . . let mut left: B = Default::default(); . let mut right: B = Default::default(); . 4 ( 0.00%) self.fold((), extend(f, &mut left, &mut right)); . 9,560 ( 0.00%) (left, right) 7,173 ( 0.00%) } . . /// Reorders the elements of this iterator *in-place* according to the given predicate, . /// such that all those that return `true` precede all those that return `false`. . /// Returns the number of `true` elements found. . /// . /// The relative order of partitioned items is not maintained. . /// . /// # Current implementation -- line 1841 ---------------------------------------- -- line 2011 ---------------------------------------- . /// } else { . /// ControlFlow::Break(prev) . /// } . /// }); . /// assert_eq!(triangular, ControlFlow::Continue(435)); . /// ``` . #[inline] . #[stable(feature = "iterator_try_fold", since = "1.27.0")] 449,675 ( 0.00%) fn try_fold(&mut self, init: B, mut f: F) -> R . where . Self: Sized, . F: FnMut(B, Self::Item) -> R, . R: Try, . { 158,196 ( 0.00%) let mut accum = init; 575,261,032 ( 0.49%) while let Some(x) = self.next() { 1,138,852,218 ( 0.98%) accum = f(accum, x)?; . } 306,061 ( 0.00%) try { accum } 500,392 ( 0.00%) } . . /// An iterator method that applies a fallible function to each item in the . /// iterator, stopping at the first error and returning that error. . /// . /// This can also be thought of as the fallible form of [`for_each()`] . /// or as the stateless version of [`try_fold()`]. . /// . /// [`for_each()`]: Iterator::for_each -- line 2038 ---------------------------------------- -- line 2077 ---------------------------------------- . fn try_for_each(&mut self, f: F) -> R . where . Self: Sized, . F: FnMut(Self::Item) -> R, . R: Try, . { . #[inline] . fn call(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R { 15,072 ( 0.00%) move |(), x| f(x) . } . 4,768 ( 0.00%) self.try_fold((), call(f)) . } . . /// Folds every element into an accumulator by applying an operation, . /// returning the final result. . /// . /// `fold()` takes two arguments: an initial value, and a closure with two . /// arguments: an 'accumulator', and an element. The closure returns the value that . /// the accumulator should have for the next iteration. -- line 2096 ---------------------------------------- -- line 2188 ---------------------------------------- . /// // they're the same . /// assert_eq!(result, result2); . /// ``` . /// . /// [`reduce()`]: Iterator::reduce . #[doc(alias = "inject", alias = "foldl")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 1,946 ( 0.00%) fn fold(mut self, init: B, mut f: F) -> B . where . Self: Sized, . F: FnMut(B, Self::Item) -> B, . { 21,430 ( 0.00%) let mut accum = init; 7,872,298 ( 0.01%) while let Some(x) = self.next() { 4,384,412 ( 0.00%) accum = f(accum, x); . } . accum 2,520 ( 0.00%) } . . /// Reduces the elements to a single one, by repeatedly applying a reducing . /// operation. . /// . /// If the iterator is empty, returns [`None`]; otherwise, returns the . /// result of the reduction. . /// . /// The reducing function is a closure with two arguments: an 'accumulator', and an element. -- line 2214 ---------------------------------------- -- line 2240 ---------------------------------------- . #[inline] . #[stable(feature = "iterator_fold_self", since = "1.51.0")] . fn reduce(mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item, Self::Item) -> Self::Item, . { . let first = self.next()?; 88,111 ( 0.00%) Some(self.fold(first, f)) . } . . /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the . /// closure returns a failure, the failure is propagated back to the caller immediately. . /// . /// The return type of this method depends on the return type of the closure. If the closure . /// returns `Result`, then this function will return `Result, . /// E>`. If the closure returns `Option`, then this function will return -- line 2256 ---------------------------------------- -- line 2370 ---------------------------------------- . fn all(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 93,896 ( 0.00%) if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK } . } . } 83,931 ( 0.00%) self.try_fold((), check(f)) == ControlFlow::CONTINUE . } . . /// Tests if any element of the iterator matches a predicate. . /// . /// `any()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, and if any of them return . /// `true`, then so does `any()`. If they all return `false`, it . /// returns `false`. -- line 2389 ---------------------------------------- -- line 2423 ---------------------------------------- . fn any(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 18 ( 0.00%) if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE } . } . } . . self.try_fold((), check(f)) == ControlFlow::BREAK . } . . /// Searches for an element of an iterator that satisfies a predicate. . /// -- line 2439 ---------------------------------------- -- line 2483 ---------------------------------------- . fn find

(&mut self, predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { . #[inline] . fn check(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow { . move |(), x| { 6,898,587 ( 0.01%) if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE } 135,216 ( 0.00%) } . } . 5,799,639 ( 0.00%) self.try_fold((), check(predicate)).break_value() . } . . /// Applies function to the elements of iterator and returns . /// the first non-none result. . /// . /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`. . /// . /// # Examples -- line 2503 ---------------------------------------- -- line 2513 ---------------------------------------- . #[stable(feature = "iterator_find_map", since = "1.30.0")] . fn find_map(&mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { . #[inline] . fn check(mut f: impl FnMut(T) -> Option) -> impl FnMut((), T) -> ControlFlow { 19,255,604 ( 0.02%) move |(), x| match f(x) { 288,374 ( 0.00%) Some(x) => ControlFlow::Break(x), . None => ControlFlow::CONTINUE, . } . } . 64,739 ( 0.00%) self.try_fold((), check(f)).break_value() . } . . /// Applies function to the elements of iterator and returns . /// the first true result or the first error. . /// . /// The return type of this method depends on the return type of the closure. . /// If you return `Result` from the closure, you'll get a `Result; E>`. . /// If you return `Option` from the closure, you'll get an `Option>`. -- line 2535 ---------------------------------------- -- line 2655 ---------------------------------------- . P: FnMut(Self::Item) -> bool, . { . #[inline] . fn check( . mut predicate: impl FnMut(T) -> bool, . ) -> impl FnMut(usize, T) -> ControlFlow { . #[rustc_inherit_overflow_checks] . move |i, x| { 31,591 ( 0.00%) if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) } . } . } . . self.try_fold(0, check(predicate)).break_value() . } . . /// Searches for an element in an iterator from the right, returning its . /// index. -- line 2671 ---------------------------------------- -- line 2812 ---------------------------------------- . /// # Examples . /// . /// ``` . /// let a = [-3_i32, 0, 1, 5, -10]; . /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10); . /// ``` . #[inline] . #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] 1,736 ( 0.00%) fn max_by_key(self, f: F) -> Option . where . Self: Sized, . F: FnMut(&Self::Item) -> B, . { . #[inline] . fn key(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { 2,508 ( 0.00%) move |x| (f(&x), x) . } . . #[inline] . fn compare((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { . x_p.cmp(y_p) . } . 4,008 ( 0.00%) let (_, x) = self.map(key(f)).max_by(compare)?; . Some(x) 1,984 ( 0.00%) } . . /// Returns the element that gives the maximum value with respect to the . /// specified comparison function. . /// . /// If several elements are equally maximum, the last element is . /// returned. If the iterator is empty, [`None`] is returned. . /// . /// # Examples -- line 2845 ---------------------------------------- -- line 2852 ---------------------------------------- . #[stable(feature = "iter_max_by", since = "1.15.0")] . fn max_by(self, compare: F) -> Option . where . Self: Sized, . F: FnMut(&Self::Item, &Self::Item) -> Ordering, . { . #[inline] . fn fold(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { 1,113 ( 0.00%) move |x, y| cmp::max_by(x, y, &mut compare) . } . 84,906 ( 0.00%) self.reduce(fold(compare)) . } . . /// Returns the element that gives the minimum value from the . /// specified function. . /// . /// If several elements are equally minimum, the first element is . /// returned. If the iterator is empty, [`None`] is returned. . /// -- line 2871 ---------------------------------------- -- line 2946 ---------------------------------------- . /// ``` . #[inline] . #[doc(alias = "reverse")] . #[stable(feature = "rust1", since = "1.0.0")] . fn rev(self) -> Rev . where . Self: Sized + DoubleEndedIterator, . { 13 ( 0.00%) Rev::new(self) . } . . /// Converts an iterator of pairs into a pair of containers. . /// . /// `unzip()` consumes an entire iterator of pairs, producing two . /// collections: one from the left elements of the pairs, and one . /// from the right elements. . /// -- line 2962 ---------------------------------------- -- line 2987 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . fn unzip(self) -> (FromA, FromB) . where . FromA: Default + Extend, . FromB: Default + Extend, . Self: Sized + Iterator, . { . let mut unzipped: (FromA, FromB) = Default::default(); 6,903 ( 0.00%) unzipped.extend(self); . unzipped . } . . /// Creates an iterator which copies all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// -- line 3003 ---------------------------------------- -- line 3017 ---------------------------------------- . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "iter_copied", since = "1.36.0")] . fn copied<'a, T: 'a>(self) -> Copied . where . Self: Sized + Iterator, . T: Copy, . { 2,897,020 ( 0.00%) Copied::new(self) . } . . /// Creates an iterator which [`clone`]s all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// . /// [`clone`]: Clone::clone -- line 3033 ---------------------------------------- -- line 3048 ---------------------------------------- . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . fn cloned<'a, T: 'a>(self) -> Cloned . where . Self: Sized + Iterator, . T: Clone, . { 947,730 ( 0.00%) Cloned::new(self) . } . . /// Repeats an iterator endlessly. . /// . /// Instead of stopping at [`None`], the iterator will instead start again, . /// from the beginning. After iterating again, it will start at the . /// beginning again. And again. And again. Forever. Note that in case the . /// original iterator is empty, the resulting iterator will also be empty. -- line 3064 ---------------------------------------- -- line 3313 ---------------------------------------- . /// . /// # Examples . /// . /// ``` . /// assert_eq!([1].iter().eq([1].iter()), true); . /// assert_eq!([1].iter().eq([1, 2].iter()), false); . /// ``` . #[stable(feature = "iter_order", since = "1.5.0")] 966 ( 0.00%) fn eq(self, other: I) -> bool . where . I: IntoIterator, . Self::Item: PartialEq, . Self: Sized, . { 1,104 ( 0.00%) self.eq_by(other, |x, y| x == y) 1,104 ( 0.00%) } . . /// Determines if the elements of this [`Iterator`] are equal to those of . /// another with respect to the specified equality function. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 3336 ---------------------------------------- -- line 3344 ---------------------------------------- . /// ``` . #[unstable(feature = "iter_order_by", issue = "64295")] . fn eq_by(mut self, other: I, mut eq: F) -> bool . where . Self: Sized, . I: IntoIterator, . F: FnMut(Self::Item, I::Item) -> bool, . { 1,380 ( 0.00%) let mut other = other.into_iter(); . . loop { 417 ( 0.00%) let x = match self.next() { . None => return other.next().is_none(), 1,529 ( 0.00%) Some(val) => val, . }; . 417 ( 0.00%) let y = match other.next() { . None => return false, . Some(val) => val, . }; . 21 ( 0.00%) if !eq(x, y) { . return false; . } . } . } . . /// Determines if the elements of this [`Iterator`] are unequal to those of . /// another. . /// -- line 3373 ---------------------------------------- -- line 3589 ---------------------------------------- . unreachable!("Always specialized"); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for &mut I { . type Item = I::Item; . #[inline] 1,392 ( 0.00%) fn next(&mut self) -> Option { 1,139,755 ( 0.00%) (**self).next() 2,088 ( 0.00%) } . fn size_hint(&self) -> (usize, Option) { 186 ( 0.00%) (**self).size_hint() . } . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . (**self).advance_by(n) . } . fn nth(&mut self, n: usize) -> Option { . (**self).nth(n) . } . } -- line 3609 ---------------------------------------- 30,936,116 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/project.rs -------------------------------------------------------------------------------- Ir -- line 47 ---------------------------------------- . pub enum ProjectionTyError<'tcx> { . /// ...we found multiple sources of information and couldn't resolve the ambiguity. . TooManyCandidates, . . /// ...an error occurred matching `T : TraitRef` . TraitSelectionError(SelectionError<'tcx>), . } . 4,404 ( 0.00%) #[derive(PartialEq, Eq, Debug)] . enum ProjectionTyCandidate<'tcx> { . /// From a where-clause in the env or object type 15,160 ( 0.00%) ParamEnv(ty::PolyProjectionPredicate<'tcx>), . . /// From the definition of `Trait` when you have something like <::B as Trait2>::C 591 ( 0.00%) TraitDef(ty::PolyProjectionPredicate<'tcx>), . . /// Bounds specified on an object type . Object(ty::PolyProjectionPredicate<'tcx>), . . /// From an "impl" (or a "pseudo-impl" returned by select) . Select(Selection<'tcx>), . } . -- line 69 ---------------------------------------- -- line 71 ---------------------------------------- . None, . Single(ProjectionTyCandidate<'tcx>), . Ambiguous, . Error(SelectionError<'tcx>), . } . . impl<'tcx> ProjectionTyCandidateSet<'tcx> { . fn mark_ambiguous(&mut self) { 186,225 ( 0.00%) *self = ProjectionTyCandidateSet::Ambiguous; . } . . fn mark_error(&mut self, err: SelectionError<'tcx>) { 8,036 ( 0.00%) *self = ProjectionTyCandidateSet::Error(err); . } . . // Returns true if the push was successful, or false if the candidate . // was discarded -- this could be because of ambiguity, or because . // a higher-priority candidate is already there. 425,022 ( 0.00%) fn push_candidate(&mut self, candidate: ProjectionTyCandidate<'tcx>) -> bool { . use self::ProjectionTyCandidate::*; . use self::ProjectionTyCandidateSet::*; . . // This wacky variable is just used to try and . // make code readable and avoid confusing paths. . // It is assigned a "value" of `()` only on those . // paths in which we wish to convert `*self` to . // ambiguous (and return false, because the candidate . // was not used). On other paths, it is not assigned, . // and hence if those paths *could* reach the code that . // comes after the match, this fn would not compile. . let convert_to_ambiguous; . 425,022 ( 0.00%) match self { . None => { 901,797 ( 0.00%) *self = Single(candidate); . return true; . } . . Single(current) => { . // Duplicates can happen inside ParamEnv. In the case, we . // perform a lazy deduplication. 435 ( 0.00%) if current == &candidate { . return false; . } . . // Prefer where-clauses. As in select, if there are multiple . // candidates, we prefer where-clause candidates over impls. This . // may seem a bit surprising, since impls are the source of . // "truth" in some sense, but in fact some of the impls that SEEM . // applicable are not, because of nested obligations. Where . // clauses are the safer choice. See the comment on . // `select::SelectionCandidate` and #21974 for more details. 20,608 ( 0.00%) match (current, candidate) { . (ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (), . (ParamEnv(..), _) => return false, . (_, ParamEnv(..)) => unreachable!(), . (_, _) => convert_to_ambiguous = (), . } . } . . Ambiguous | Error(..) => { . return false; . } . } . . // We only ever get here when we moved from a single candidate . // to ambiguous. . let () = convert_to_ambiguous; 25 ( 0.00%) *self = Ambiguous; . false 495,859 ( 0.00%) } . } . . /// Evaluates constraints of the form: . /// . /// for<...> ::U == V . /// . /// If successful, this may result in additional obligations. Also returns . /// the projection cache key used to track these additional obligations. -- line 149 ---------------------------------------- -- line 164 ---------------------------------------- . pub(super) fn poly_project_and_unify_type<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &PolyProjectionObligation<'tcx>, . ) -> Result< . Result>>, InProgress>, . MismatchedProjectionTypes<'tcx>, . > { . let infcx = selcx.infcx(); 207,155 ( 0.00%) infcx.commit_if_ok(|_snapshot| { . let placeholder_predicate = 198,972 ( 0.00%) infcx.replace_bound_vars_with_placeholders(obligation.predicate); . . let placeholder_obligation = obligation.with(placeholder_predicate); 66,324 ( 0.00%) let result = project_and_unify_type(selcx, &placeholder_obligation)?; 33,048 ( 0.00%) Ok(result) . }) . } . . /// Evaluates constraints of the form: . /// . /// ::U == V . /// . /// If successful, this may result in additional obligations. . /// . /// See [poly_project_and_unify_type] for an explanation of the return value. 331,620 ( 0.00%) fn project_and_unify_type<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionObligation<'tcx>, . ) -> Result< . Result>>, InProgress>, . MismatchedProjectionTypes<'tcx>, . > { . debug!(?obligation, "project_and_unify_type"); . . let mut obligations = vec![]; 265,296 ( 0.00%) let normalized_ty = match opt_normalize_projection_type( . selcx, 33,162 ( 0.00%) obligation.param_env, 66,324 ( 0.00%) obligation.predicate.projection_ty, . obligation.cause.clone(), 66,324 ( 0.00%) obligation.recursion_depth, . &mut obligations, . ) { . Ok(Some(n)) => n, 49,720 ( 0.00%) Ok(None) => return Ok(Ok(None)), . Err(InProgress) => return Ok(Err(InProgress)), . }; . . debug!(?normalized_ty, ?obligations, "project_and_unify_type result"); . . let infcx = selcx.infcx(); . // FIXME(associated_const_equality): Handle consts here as well as types. 41,464 ( 0.00%) let obligation_pred_ty = obligation.predicate.term.ty().unwrap(); 62,196 ( 0.00%) match infcx.at(&obligation.cause, obligation.param_env).eq(normalized_ty, obligation_pred_ty) { . Ok(InferOk { obligations: inferred_obligations, value: () }) => { . obligations.extend(inferred_obligations); 144,326 ( 0.00%) Ok(Ok(Some(obligations))) . } . Err(err) => { . debug!("project_and_unify_type: equating types encountered error {:?}", err); 684 ( 0.00%) Err(MismatchedProjectionTypes { err }) . } . } 298,458 ( 0.00%) } . . /// Normalizes any associated type projections in `value`, replacing . /// them with a fully resolved type where possible. The return value . /// combines the normalized result and any additional obligations that . /// were incurred as result. 3,685,540 ( 0.00%) pub fn normalize<'a, 'b, 'tcx, T>( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . value: T, . ) -> Normalized<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . let mut obligations = Vec::new(); . let value = normalize_to(selcx, param_env, cause, value, &mut obligations); 2,982,610 ( 0.00%) Normalized { value, obligations } 3,316,986 ( 0.00%) } . . pub fn normalize_to<'a, 'b, 'tcx, T>( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . value: T, . obligations: &mut Vec>, . ) -> T . where . T: TypeFoldable<'tcx>, . { 3,363,894 ( 0.00%) normalize_with_depth_to(selcx, param_env, cause, 0, value, obligations) . } . . /// As `normalize`, but with a custom depth. 12,650 ( 0.00%) pub fn normalize_with_depth<'a, 'b, 'tcx, T>( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . depth: usize, . value: T, . ) -> Normalized<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . let mut obligations = Vec::new(); 112,799,221 ( 0.10%) let value = normalize_with_depth_to(selcx, param_env, cause, depth, value, &mut obligations); 61,531,022 ( 0.05%) Normalized { value, obligations } 10,945 ( 0.00%) } . 112,684,142 ( 0.10%) #[instrument(level = "info", skip(selcx, param_env, cause, obligations))] 147,944,641 ( 0.13%) pub fn normalize_with_depth_to<'a, 'b, 'tcx, T>( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . depth: usize, . value: T, . obligations: &mut Vec>, . ) -> T . where . T: TypeFoldable<'tcx>, . { . debug!(obligations.len = obligations.len()); 60,847,987 ( 0.05%) let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth, obligations); 58,272,389 ( 0.05%) let result = ensure_sufficient_stack(|| normalizer.fold(value)); . debug!(?result, obligations.len = normalizer.obligations.len()); . debug!(?normalizer.obligations,); 1,595,602 ( 0.00%) result 23,500,352 ( 0.02%) } . . pub(crate) fn needs_normalization<'tcx, T: TypeFoldable<'tcx>>(value: &T, reveal: Reveal) -> bool { . match reveal { . Reveal::UserFacing => value . .has_type_flags(ty::TypeFlags::HAS_TY_PROJECTION | ty::TypeFlags::HAS_CT_PROJECTION), . Reveal::All => value.has_type_flags( . ty::TypeFlags::HAS_TY_PROJECTION . | ty::TypeFlags::HAS_TY_OPAQUE -- line 302 ---------------------------------------- -- line 310 ---------------------------------------- . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . obligations: &'a mut Vec>, . depth: usize, . universes: Vec>, . } . . impl<'a, 'b, 'tcx> AssocTypeNormalizer<'a, 'b, 'tcx> { 219,817 ( 0.00%) fn new( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . depth: usize, . obligations: &'a mut Vec>, . ) -> AssocTypeNormalizer<'a, 'b, 'tcx> { 60,141,977 ( 0.05%) AssocTypeNormalizer { selcx, param_env, cause, obligations, depth, universes: vec![] } 219,817 ( 0.00%) } . 110,900,694 ( 0.10%) fn fold>(&mut self, value: T) -> T { 46,849,598 ( 0.04%) let value = self.selcx.infcx().resolve_vars_if_possible(value); . debug!(?value); . 2,324,285 ( 0.00%) assert!( . !value.has_escaping_bound_vars(), . "Normalizing {:?} without wrapping in a `Binder`", . value . ); . 14,078,106 ( 0.01%) if !needs_normalization(&value, self.param_env.reveal()) { 753,215 ( 0.00%) value . } else { 786,607 ( 0.00%) value.fold_with(self) . } 100,454,458 ( 0.09%) } . } . . impl<'a, 'b, 'tcx> TypeFolder<'tcx> for AssocTypeNormalizer<'a, 'b, 'tcx> { . fn tcx<'c>(&'c self) -> TyCtxt<'tcx> { 30,896,835 ( 0.03%) self.selcx.tcx() 81,698 ( 0.00%) } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { . self.universes.push(None); 441,554 ( 0.00%) let t = t.super_fold_with(self); . self.universes.pop(); . t . } . 183,380,480 ( 0.16%) fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 45,845,120 ( 0.04%) if !needs_normalization(&ty, self.param_env.reveal()) { . return ty; . } . . // We try to be a little clever here as a performance optimization in . // cases where there are nested projections under binders. . // For example: . // ``` . // for<'a> fn(::One<'a, Box::Two<'a>>>>) -- line 370 ---------------------------------------- -- line 381 ---------------------------------------- . // . // This is possible because the inner `'a` will already be a placeholder . // when we need to normalize the inner projection . // . // On the other hand, this does add a bit of complexity, since we only . // replace bound vars if the current type is a `Projection` and we need . // to make sure we don't forget to fold the substs regardless. . 52,883,311 ( 0.05%) match *ty.kind() { . // This is really important. While we *can* handle this, this has . // severe performance implications for large opaque types with . // late-bound regions. See `issue-88862` benchmark. . ty::Opaque(def_id, substs) if !substs.has_escaping_bound_vars() => { . // Only normalize `impl Trait` after type-checking, usually in codegen. . match self.param_env.reveal() { . Reveal::UserFacing => ty.super_fold_with(self), . -- line 397 ---------------------------------------- -- line 421 ---------------------------------------- . ty::Projection(data) if !data.has_escaping_bound_vars() => { . // This branch is *mostly* just an optimization: when we don't . // have escaping bound vars, we don't need to replace them with . // placeholders (see branch below). *Also*, we know that we can . // register an obligation to *later* project, since we know . // there won't be bound vars there. . . let data = data.super_fold_with(self); 3,782,712 ( 0.00%) let normalized_ty = normalize_projection_type( 630,452 ( 0.00%) self.selcx, 630,452 ( 0.00%) self.param_env, . data, . self.cause.clone(), 630,452 ( 0.00%) self.depth, 630,452 ( 0.00%) &mut self.obligations, . ); . debug!( . ?self.depth, . ?ty, . ?normalized_ty, . obligations.len = ?self.obligations.len(), . "AssocTypeNormalizer: normalized type" . ); -- line 443 ---------------------------------------- -- line 490 ---------------------------------------- . obligations.len = ?self.obligations.len(), . "AssocTypeNormalizer: normalized type" . ); . normalized_ty . } . . _ => ty.super_fold_with(self), . } 206,303,040 ( 0.18%) } . 90,438,462 ( 0.08%) fn fold_const(&mut self, constant: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 20,097,436 ( 0.02%) if self.selcx.tcx().lazy_normalization() { . constant . } else { 40,194,872 ( 0.03%) let constant = constant.super_fold_with(self); . constant.eval(self.selcx.tcx(), self.param_env) . } 90,438,462 ( 0.08%) } . } . . pub struct BoundVarReplacer<'me, 'tcx> { . infcx: &'me InferCtxt<'me, 'tcx>, . // These three maps track the bound variable that were replaced by placeholders. It might be . // nice to remove these since we already have the `kind` in the placeholder; we really just need . // the `var` (but we *could* bring that into scope if we were to track them as we pass them). . mapped_regions: BTreeMap, -- line 515 ---------------------------------------- -- line 781 ---------------------------------------- . } . . /// The guts of `normalize`: normalize a specific projection like `::Item`. The result is always a type (and possibly . /// additional obligations). If ambiguity arises, which implies that . /// there are unresolved type variables in the projection, we will . /// substitute a fresh type variable `$X` and generate a new . /// obligation `::Item == $X` for later. 6,389,600 ( 0.01%) pub fn normalize_projection_type<'a, 'b, 'tcx>( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . projection_ty: ty::ProjectionTy<'tcx>, . cause: ObligationCause<'tcx>, . depth: usize, . obligations: &mut Vec>, . ) -> Ty<'tcx> { 5,111,680 ( 0.00%) opt_normalize_projection_type( . selcx, . param_env, . projection_ty, . cause.clone(), . depth, . obligations, . ) . .ok() . .flatten() . .unwrap_or_else(move || { . // if we bottom out in ambiguity, create a type variable . // and a deferred predicate to resolve this when more type . // information is available. . 1,211,462 ( 0.00%) selcx.infcx().infer_projection(param_env, projection_ty, cause, depth + 1, obligations) . }) 5,750,640 ( 0.00%) } . . /// The guts of `normalize`: normalize a specific projection like `::Item`. The result is always a type (and possibly . /// additional obligations). Returns `None` in the case of ambiguity, . /// which indicates that there are unbound type variables. . /// . /// This function used to return `Option>`, which contains a . /// `Ty<'tcx>` and an obligations vector. But that obligation vector was very . /// often immediately appended to another obligations vector. So now this . /// function takes an obligations vector and appends to it directly, which is . /// slightly uglier but avoids the need for an extra short-lived allocation. 16,659,790 ( 0.01%) #[instrument(level = "debug", skip(selcx, param_env, cause, obligations))] . fn opt_normalize_projection_type<'a, 'b, 'tcx>( . selcx: &'a mut SelectionContext<'b, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . projection_ty: ty::ProjectionTy<'tcx>, . cause: ObligationCause<'tcx>, . depth: usize, . obligations: &mut Vec>, . ) -> Result>, InProgress> { . let infcx = selcx.infcx(); . // Don't use the projection cache in intercrate mode - . // the `infcx` may be re-used between intercrate in non-intercrate . // mode, which could lead to using incorrect cache results. . let use_cache = !selcx.is_intercrate(); . . let projection_ty = infcx.resolve_vars_if_possible(projection_ty); 2,016,366 ( 0.00%) let cache_key = ProjectionCacheKey::new(projection_ty); . . // FIXME(#20304) For now, I am caching here, which is good, but it . // means we don't capture the type variables that are created in . // the case of ambiguity. Which means we may create a large stream . // of such variables. OTOH, if we move the caching up a level, we . // would not benefit from caching when proving `T: Trait` . // bounds. It might be the case that we want two distinct caches, . // or else another kind of cache entry. . 672,122 ( 0.00%) let cache_result = if use_cache { 3,417,246 ( 0.00%) infcx.inner.borrow_mut().projection_cache().try_start(cache_key) . } else { 102,581 ( 0.00%) Ok(()) . }; 3,417,246 ( 0.00%) match cache_result { . Ok(()) => debug!("no cache"), . Err(ProjectionCacheEntry::Ambiguous) => { . // If we found ambiguity the last time, that means we will continue . // to do so until some type in the key changes (and we know it . // hasn't, because we just fully resolved it). . debug!("found cache entry: ambiguous"); . return Ok(None); . } -- line 865 ---------------------------------------- -- line 882 ---------------------------------------- . infcx.inner.borrow_mut().projection_cache().recur(cache_key); . } . return Err(InProgress); . } . Err(ProjectionCacheEntry::Recur) => { . debug!("recur cache"); . return Err(InProgress); . } 911,180 ( 0.00%) Err(ProjectionCacheEntry::NormalizedTy { ty, complete: _ }) => { . // This is the hottest path in this function. . // . // If we find the value in the cache, then return it along . // with the obligations that went along with it. Note . // that, when using a fulfillment context, these . // obligations could in principle be ignored: they have . // already been registered when the cache entry was . // created (and hence the new ones will quickly be -- line 898 ---------------------------------------- -- line 900 ---------------------------------------- . // evaluation this is not the case, and dropping the trait . // evaluations can causes ICEs (e.g., #43132). . debug!(?ty, "found normalized ty"); . obligations.extend(ty.obligations); . return Ok(Some(ty.value)); . } . Err(ProjectionCacheEntry::Error) => { . debug!("opt_normalize_projection_type: found error"); 8,988 ( 0.00%) let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth); . obligations.extend(result.obligations); 642 ( 0.00%) return Ok(Some(result.value)); . } . } . . let obligation = Obligation::with_depth(cause.clone(), depth, param_env, projection_ty); . 1,801,476 ( 0.00%) match project_type(selcx, &obligation) { . Ok(ProjectedTy::Progress(Progress { . ty: projected_ty, 276,320 ( 0.00%) obligations: mut projected_obligations, . })) => { . // if projection succeeded, then what we get out of this . // is also non-normalized (consider: it was derived from . // an impl, where-clause etc) and hence we must . // re-normalize it . . let projected_ty = selcx.infcx().resolve_vars_if_possible(projected_ty); . debug!(?projected_ty, ?depth, ?projected_obligations); . 69,080 ( 0.00%) let mut result = if projected_ty.has_projections() { . let mut normalizer = AssocTypeNormalizer::new( . selcx, . param_env, 70,856 ( 0.00%) cause, 35,428 ( 0.00%) depth + 1, . &mut projected_obligations, . ); 35,428 ( 0.00%) let normalized_ty = normalizer.fold(projected_ty); . . debug!(?normalized_ty, ?depth); . 88,570 ( 0.00%) Normalized { value: normalized_ty, obligations: projected_obligations } . } else { 308,196 ( 0.00%) Normalized { value: projected_ty, obligations: projected_obligations } . }; . . let mut deduped: SsoHashSet<_> = Default::default(); 69,080 ( 0.00%) result.obligations.drain_filter(|projected_obligation| { . if !deduped.insert(projected_obligation.clone()) { . return true; . } . false . }); . 69,080 ( 0.00%) if use_cache { 107,496 ( 0.00%) infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, result.clone()); . } . obligations.extend(result.obligations); 69,080 ( 0.00%) Ok(Some(result.value)) . } . Ok(ProjectedTy::NoProgress(projected_ty)) => { . debug!(?projected_ty, "opt_normalize_projection_type: no progress"); 94,546 ( 0.00%) let result = Normalized { value: projected_ty, obligations: vec![] }; 47,273 ( 0.00%) if use_cache { 141,819 ( 0.00%) infcx.inner.borrow_mut().projection_cache().insert_ty(cache_key, result.clone()); . } . // No need to extend `obligations`. 47,273 ( 0.00%) Ok(Some(result.value)) . } . Err(ProjectionTyError::TooManyCandidates) => { . debug!("opt_normalize_projection_type: too many candidates"); 83,237 ( 0.00%) if use_cache { 83,424 ( 0.00%) infcx.inner.borrow_mut().projection_cache().ambiguous(cache_key); . } . Ok(None) . } . Err(ProjectionTyError::TraitSelectionError(_)) => { . debug!("opt_normalize_projection_type: ERROR"); . // if we got an error processing the `T as Trait` part, . // just return `ty::err` but add the obligation `T : . // Trait`, which when processed will cause the error to be . // reported later . 574 ( 0.00%) if use_cache { 3,444 ( 0.00%) infcx.inner.borrow_mut().projection_cache().error(cache_key); . } 8,036 ( 0.00%) let result = normalize_to_error(selcx, param_env, projection_ty, cause, depth); . obligations.extend(result.obligations); 1,722 ( 0.00%) Ok(Some(result.value)) . } . } . } . . /// If we are projecting `::Item`, but `T: Trait` does not . /// hold. In various error cases, we cannot generate a valid . /// normalized projection. Therefore, we create an inference variable . /// return an associated obligation that, when fulfilled, will lead to -- line 996 ---------------------------------------- -- line 1004 ---------------------------------------- . /// paths you want to take. To make things worse, it was possible for . /// cycles to arise, where you basically had a setup like ` . /// as Trait>::Foo == $0`. Here, normalizing ` as . /// Trait>::Foo> to `[type error]` would lead to an obligation of . /// ` as Trait>::Foo`. We are supposed to report . /// an error for this obligation, but we legitimately should not, . /// because it contains `[type error]`. Yuck! (See issue #29857 for . /// one case where this arose.) 14,592 ( 0.00%) fn normalize_to_error<'a, 'tcx>( . selcx: &mut SelectionContext<'a, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . projection_ty: ty::ProjectionTy<'tcx>, . cause: ObligationCause<'tcx>, . depth: usize, . ) -> NormalizedTy<'tcx> { 1,216 ( 0.00%) let trait_ref = ty::Binder::dummy(projection_ty.trait_ref(selcx.tcx())); 9,728 ( 0.00%) let trait_obligation = Obligation { 4,864 ( 0.00%) cause, . recursion_depth: depth, . param_env, 1,216 ( 0.00%) predicate: trait_ref.without_const().to_predicate(selcx.tcx()), . }; 1,216 ( 0.00%) let tcx = selcx.infcx().tcx; . let def_id = projection_ty.item_def_id; 6,080 ( 0.00%) let new_value = selcx.infcx().next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::NormalizeProjectionType, . span: tcx.def_span(def_id), . }); 13,376 ( 0.00%) Normalized { value: new_value, obligations: vec![trait_obligation] } 9,728 ( 0.00%) } . . enum ProjectedTy<'tcx> { . Progress(Progress<'tcx>), . NoProgress(Ty<'tcx>), . } . . struct Progress<'tcx> { . ty: Ty<'tcx>, -- line 1041 ---------------------------------------- -- line 1042 ---------------------------------------- . obligations: Vec>, . } . . impl<'tcx> Progress<'tcx> { . fn error(tcx: TyCtxt<'tcx>) -> Self { . Progress { ty: tcx.ty_error(), obligations: vec![] } . } . 8,800 ( 0.00%) fn with_addl_obligations(mut self, mut obligations: Vec>) -> Self { . debug!( . self.obligations.len = ?self.obligations.len(), . obligations.len = obligations.len(), . "with_addl_obligations" . ); . . debug!(?self.obligations, ?obligations, "with_addl_obligations"); . 880 ( 0.00%) self.obligations.append(&mut obligations); 5,280 ( 0.00%) self 3,752 ( 0.00%) } . } . . /// Computes the result of a projection type (if we can). . /// . /// IMPORTANT: . /// - `obligation` must be fully normalized 3,602,952 ( 0.00%) #[tracing::instrument(level = "info", skip(selcx))] . fn project_type<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . ) -> Result, ProjectionTyError<'tcx>> { 600,492 ( 0.00%) if !selcx.tcx().recursion_limit().value_within_limit(obligation.recursion_depth) { . debug!("project: overflow!"); . // This should really be an immediate error, but some existing code . // relies on being able to recover from this. . return Err(ProjectionTyError::TraitSelectionError(SelectionError::Overflow)); . } . . if obligation.predicate.references_error() { . return Ok(ProjectedTy::Progress(Progress::error(selcx.tcx()))); . } . 200,164 ( 0.00%) let mut candidates = ProjectionTyCandidateSet::None; . . // Make sure that the following procedures are kept in order. ParamEnv . // needs to be first because it has highest priority, and Select checks . // the return value of push_candidate which assumes it's ran at last. 400,328 ( 0.00%) assemble_candidates_from_param_env(selcx, obligation, &mut candidates); . 194,922 ( 0.00%) assemble_candidates_from_trait_def(selcx, obligation, &mut candidates); . 400,328 ( 0.00%) assemble_candidates_from_object_ty(selcx, obligation, &mut candidates); . 327,964 ( 0.00%) if let ProjectionTyCandidateSet::Single(ProjectionTyCandidate::Object(_)) = candidates { . // Avoid normalization cycle from selection (see . // `assemble_candidates_from_object_ty`). . // FIXME(lazy_normalization): Lazy normalization should save us from . // having to special case this. . } else { 400,328 ( 0.00%) assemble_candidates_from_impls(selcx, obligation, &mut candidates); . }; . 1,000,820 ( 0.00%) match candidates { . ProjectionTyCandidateSet::Single(candidate) => { 1,519,760 ( 0.00%) Ok(ProjectedTy::Progress(confirm_candidate(selcx, obligation, candidate))) . } 236,365 ( 0.00%) ProjectionTyCandidateSet::None => Ok(ProjectedTy::NoProgress( . selcx . .tcx() 94,546 ( 0.00%) .mk_projection(obligation.predicate.item_def_id, obligation.predicate.substs), . )), . // Error occurred while trying to processing impls. 9,184 ( 0.00%) ProjectionTyCandidateSet::Error(e) => Err(ProjectionTyError::TraitSelectionError(e)), . // Inherent ambiguity that prevents us from even enumerating the . // candidates. 332,948 ( 0.00%) ProjectionTyCandidateSet::Ambiguous => Err(ProjectionTyError::TooManyCandidates), . } 531,412 ( 0.00%) } . . /// The first thing we have to do is scan through the parameter . /// environment to see whether there are any projection predicates . /// there that can answer this question. . fn assemble_candidates_from_param_env<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . candidate_set: &mut ProjectionTyCandidateSet<'tcx>, . ) { . debug!("assemble_candidates_from_param_env(..)"); . assemble_candidates_from_predicates( . selcx, . obligation, . candidate_set, . ProjectionTyCandidate::ParamEnv, 200,164 ( 0.00%) obligation.param_env.caller_bounds().iter(), . false, . ); . } . . /// In the case of a nested projection like <::FooT as Bar>::BarT, we may find . /// that the definition of `Foo` has some clues: . /// . /// ``` -- line 1143 ---------------------------------------- -- line 1152 ---------------------------------------- . obligation: &ProjectionTyObligation<'tcx>, . candidate_set: &mut ProjectionTyCandidateSet<'tcx>, . ) { . debug!("assemble_candidates_from_trait_def(..)"); . . let tcx = selcx.tcx(); . // Check whether the self-type is itself a projection. . // If so, extract what we know from the trait and try to come up with a good answer. 2,298,898 ( 0.00%) let bounds = match *obligation.predicate.self_ty().kind() { 15,288 ( 0.00%) ty::Projection(ref data) => tcx.item_bounds(data.item_def_id).subst(tcx, data.substs), . ty::Opaque(def_id, substs) => tcx.item_bounds(def_id).subst(tcx, substs), . ty::Infer(ty::TyVar(_)) => { . // If the self-type is an inference variable, then it MAY wind up . // being a projected type, so induce an ambiguity. . candidate_set.mark_ambiguous(); . return; . } . _ => return, -- line 1169 ---------------------------------------- -- line 1192 ---------------------------------------- . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . candidate_set: &mut ProjectionTyCandidateSet<'tcx>, . ) { . debug!("assemble_candidates_from_object_ty(..)"); . . let tcx = selcx.tcx(); . 400,328 ( 0.00%) let self_ty = obligation.predicate.self_ty(); . let object_ty = selcx.infcx().shallow_resolve(self_ty); 1,000,820 ( 0.00%) let data = match object_ty.kind() { . ty::Dynamic(data, ..) => data, . ty::Infer(ty::TyVar(_)) => { . // If the self-type is an inference variable, then it MAY wind up . // being an object type, so induce an ambiguity. . candidate_set.mark_ambiguous(); . return; . } . _ => return, -- line 1210 ---------------------------------------- -- line 1232 ---------------------------------------- . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . candidate_set: &mut ProjectionTyCandidateSet<'tcx>, . ctor: fn(ty::PolyProjectionPredicate<'tcx>) -> ProjectionTyCandidate<'tcx>, . env_predicates: impl Iterator>, . potentially_unnormalized_candidates: bool, . ) { . let infcx = selcx.infcx(); 37,927 ( 0.00%) for predicate in env_predicates { . debug!(?predicate); . let bound_predicate = predicate.kind(); 12,275,131 ( 0.01%) if let ty::PredicateKind::Projection(data) = predicate.kind().skip_binder() { 3,007,540 ( 0.00%) let data = bound_predicate.rebind(data); 1,503,770 ( 0.00%) let same_def_id = data.projection_def_id() == obligation.predicate.item_def_id; . 818,287 ( 0.00%) let is_match = same_def_id . && infcx.probe(|_| { 99,603 ( 0.00%) selcx.match_projection_projections( . obligation, 298,809 ( 0.00%) data, . potentially_unnormalized_candidates, . ) . }); . . debug!(?data, ?is_match, ?same_def_id); . 66,402 ( 0.00%) if is_match { 172,670 ( 0.00%) candidate_set.push_candidate(ctor(data)); . . if potentially_unnormalized_candidates . && !obligation.predicate.has_infer_types_or_consts() . { . // HACK: Pick the first trait def candidate for a fully . // inferred predicate. This is to allow duplicates that . // differ only in normalization. . return; -- line 1267 ---------------------------------------- -- line 1274 ---------------------------------------- . #[tracing::instrument(level = "debug", skip(selcx, obligation, candidate_set))] . fn assemble_candidates_from_impls<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . candidate_set: &mut ProjectionTyCandidateSet<'tcx>, . ) { . // If we are resolving `>::Item == Type`, . // start out by selecting the predicate `T as TraitRef<...>`: 600,492 ( 0.00%) let poly_trait_ref = ty::Binder::dummy(obligation.predicate.trait_ref(selcx.tcx())); 400,328 ( 0.00%) let trait_obligation = obligation.with(poly_trait_ref.to_poly_trait_predicate()); 1,801,476 ( 0.00%) let _ = selcx.infcx().commit_if_ok(|_| { 1,199,836 ( 0.00%) let impl_source = match selcx.select(&trait_obligation) { 1,163,530 ( 0.00%) Ok(Some(impl_source)) => impl_source, . Ok(None) => { . candidate_set.mark_ambiguous(); . return Err(()); . } . Err(e) => { . debug!(error = ?e, "selection error"); . candidate_set.mark_error(e); . return Err(()); . } . }; . 581,765 ( 0.00%) let eligible = match &impl_source { . super::ImplSource::Closure(_) . | super::ImplSource::Generator(_) . | super::ImplSource::FnPointer(_) . | super::ImplSource::TraitAlias(_) => { . debug!(?impl_source); . true . } . super::ImplSource::UserDefined(impl_data) => { -- line 1306 ---------------------------------------- -- line 1322 ---------------------------------------- . // . // In either case, we handle this by not adding a . // candidate for an impl if it contains a `default` . // type. . // . // NOTE: This should be kept in sync with the similar code in . // `rustc_ty_utils::instance::resolve_associated_item()`. . let node_item = 491,814 ( 0.00%) assoc_ty_def(selcx, impl_data.impl_def_id, obligation.predicate.item_def_id) . .map_err(|ErrorReported| ())?; . 163,938 ( 0.00%) if node_item.is_final() { . // Non-specializable items are always projectable. . true . } else { . // Only reveal a specializable default if we're past type-checking . // and the obligation is monomorphic, otherwise passes such as . // transmute checking and polymorphic MIR optimizations could . // get a result which isn't correct for all monomorphizations. . if obligation.param_env.reveal() == Reveal::All { -- line 1341 ---------------------------------------- -- line 1495 ---------------------------------------- . obligation.cause.span, . &format!("Cannot project an associated type from `{:?}`", impl_source), . ); . return Err(()); . } . }; . . if eligible { 771,204 ( 0.00%) if candidate_set.push_candidate(ProjectionTyCandidate::Select(impl_source)) { . Ok(()) . } else { . Err(()) . } . } else { . Err(()) . } 122,534 ( 0.00%) }); . } . . fn confirm_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . candidate: ProjectionTyCandidate<'tcx>, . ) -> Progress<'tcx> { . debug!(?obligation, ?candidate, "confirm_candidate"); 345,400 ( 0.00%) let mut progress = match candidate { . ProjectionTyCandidate::ParamEnv(poly_projection) . | ProjectionTyCandidate::Object(poly_projection) => { 205,324 ( 0.00%) confirm_param_env_candidate(selcx, obligation, poly_projection, false) . } . . ProjectionTyCandidate::TraitDef(poly_projection) => { 7,566 ( 0.00%) confirm_param_env_candidate(selcx, obligation, poly_projection, true) . } . . ProjectionTyCandidate::Select(impl_source) => { 538,320 ( 0.00%) confirm_select_candidate(selcx, obligation, impl_source) . } . }; . // When checking for cycle during evaluation, we compare predicates with . // "syntactic" equality. Since normalization generally introduces a type . // with new region variables, we need to resolve them to existing variables . // when possible for this to work. See `auto-trait-projection-recursion.rs` . // for a case where this matters. 84,315 ( 0.00%) if progress.ty.has_infer_regions() { 6,792 ( 0.00%) progress.ty = OpportunisticRegionResolver::new(selcx.infcx()).fold_ty(progress.ty); . } . progress . } . . fn confirm_select_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . impl_source: Selection<'tcx>, . ) -> Progress<'tcx> { 269,160 ( 0.00%) match impl_source { 266,960 ( 0.00%) super::ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data), . super::ImplSource::Generator(data) => confirm_generator_candidate(selcx, obligation, data), 2,466 ( 0.00%) super::ImplSource::Closure(data) => confirm_closure_candidate(selcx, obligation, data), 145 ( 0.00%) super::ImplSource::FnPointer(data) => confirm_fn_pointer_candidate(selcx, obligation, data), . super::ImplSource::DiscriminantKind(data) => { . confirm_discriminant_kind_candidate(selcx, obligation, data) . } . super::ImplSource::Pointee(data) => confirm_pointee_candidate(selcx, obligation, data), . super::ImplSource::Object(_) . | super::ImplSource::AutoImpl(..) . | super::ImplSource::Param(..) . | super::ImplSource::Builtin(..) -- line 1562 ---------------------------------------- -- line 1680 ---------------------------------------- . .with_addl_obligations(obligations) . } . . fn confirm_fn_pointer_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . fn_pointer_impl_source: ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, . ) -> Progress<'tcx> { 29 ( 0.00%) let fn_type = selcx.infcx().shallow_resolve(fn_pointer_impl_source.fn_ty); 58 ( 0.00%) let sig = fn_type.fn_sig(selcx.tcx()); 290 ( 0.00%) let Normalized { value: sig, obligations } = normalize_with_depth( . selcx, 29 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 87 ( 0.00%) obligation.recursion_depth + 1, 232 ( 0.00%) sig, . ); . 87 ( 0.00%) confirm_callable_candidate(selcx, obligation, sig, util::TupleArgumentsFlag::Yes) 203 ( 0.00%) .with_addl_obligations(fn_pointer_impl_source.nested) 203 ( 0.00%) .with_addl_obligations(obligations) . } . . fn confirm_closure_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . impl_source: ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, . ) -> Progress<'tcx> { 1,644 ( 0.00%) let closure_sig = impl_source.substs.as_closure().sig(); 4,110 ( 0.00%) let Normalized { value: closure_sig, obligations } = normalize_with_depth( . selcx, 411 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 1,233 ( 0.00%) obligation.recursion_depth + 1, 3,288 ( 0.00%) closure_sig, . ); . . debug!(?obligation, ?closure_sig, ?obligations, "confirm_closure_candidate"); . 1,233 ( 0.00%) confirm_callable_candidate(selcx, obligation, closure_sig, util::TupleArgumentsFlag::No) 2,877 ( 0.00%) .with_addl_obligations(impl_source.nested) 2,877 ( 0.00%) .with_addl_obligations(obligations) . } . . fn confirm_callable_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . fn_sig: ty::PolyFnSig<'tcx>, . flag: util::TupleArgumentsFlag, . ) -> Progress<'tcx> { . let tcx = selcx.tcx(); . . debug!(?obligation, ?fn_sig, "confirm_callable_candidate"); . 2,200 ( 0.00%) let fn_once_def_id = tcx.require_lang_item(LangItem::FnOnce, None); 2,200 ( 0.00%) let fn_once_output_def_id = tcx.require_lang_item(LangItem::FnOnceOutput, None); . 4,400 ( 0.00%) let predicate = super::util::closure_trait_ref_and_return_type( . tcx, . fn_once_def_id, 880 ( 0.00%) obligation.predicate.self_ty(), 1,760 ( 0.00%) fn_sig, . flag, . ) . .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate { . projection_ty: ty::ProjectionTy { . substs: trait_ref.substs, . item_def_id: fn_once_output_def_id, . }, . term: ret_type.into(), . }); . 5,280 ( 0.00%) confirm_param_env_candidate(selcx, obligation, predicate, true) . } . 188,256 ( 0.00%) fn confirm_param_env_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . poly_cache_entry: ty::PolyProjectionPredicate<'tcx>, . potentially_unnormalized_candidate: bool, . ) -> Progress<'tcx> { . let infcx = selcx.infcx(); . let cause = &obligation.cause; 31,376 ( 0.00%) let param_env = obligation.param_env; . 62,752 ( 0.00%) let (cache_entry, _) = infcx.replace_bound_vars_with_fresh_vars( 47,064 ( 0.00%) cause.span, . LateBoundRegionConversionTime::HigherRankedType, . poly_cache_entry, . ); . 31,376 ( 0.00%) let cache_projection = cache_entry.projection_ty; . let mut nested_obligations = Vec::new(); 47,064 ( 0.00%) let obligation_projection = obligation.predicate; 125,504 ( 0.00%) let obligation_projection = ensure_sufficient_stack(|| { 62,752 ( 0.00%) normalize_with_depth_to( . selcx, 15,688 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 47,064 ( 0.00%) obligation.recursion_depth + 1, 31,376 ( 0.00%) obligation_projection, . &mut nested_obligations, . ) . }); 31,376 ( 0.00%) let cache_projection = if potentially_unnormalized_candidate { 7,154 ( 0.00%) ensure_sufficient_stack(|| { 4,088 ( 0.00%) normalize_with_depth_to( . selcx, 1,022 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 3,066 ( 0.00%) obligation.recursion_depth + 1, 2,044 ( 0.00%) cache_projection, . &mut nested_obligations, . ) . }) . } else { 29,332 ( 0.00%) cache_projection . }; . . debug!(?cache_projection, ?obligation_projection); . 31,376 ( 0.00%) match infcx.at(cause, param_env).eq(cache_projection, obligation_projection) { . Ok(InferOk { value: _, obligations }) => { . nested_obligations.extend(obligations); 31,376 ( 0.00%) assoc_ty_own_obligations(selcx, obligation, &mut nested_obligations); . // FIXME(associated_const_equality): Handle consts here as well? Maybe this progress type should just take . // a term instead. 125,504 ( 0.00%) Progress { ty: cache_entry.term.ty().unwrap(), obligations: nested_obligations } . } . Err(e) => { . let msg = format!( . "Failed to unify obligation `{:?}` with poly_projection `{:?}`: {:?}", . obligation, poly_cache_entry, e, . ); . debug!("confirm_param_env_candidate: {}", msg); . let err = infcx.tcx.ty_error_with_message(obligation.cause.span, &msg); . Progress { ty: err, obligations: vec![] } . } . } 125,504 ( 0.00%) } . . fn confirm_impl_candidate<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>, . ) -> Progress<'tcx> { . let tcx = selcx.tcx(); . 213,568 ( 0.00%) let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source; 160,176 ( 0.00%) let assoc_item_id = obligation.predicate.item_def_id; 213,568 ( 0.00%) let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap(); . 213,568 ( 0.00%) let param_env = obligation.param_env; 373,744 ( 0.00%) let assoc_ty = match assoc_ty_def(selcx, impl_def_id, assoc_item_id) { 533,920 ( 0.00%) Ok(assoc_ty) => assoc_ty, . Err(ErrorReported) => return Progress { ty: tcx.ty_error(), obligations: nested }, . }; . 213,568 ( 0.00%) if !assoc_ty.item.defaultness.has_value() { . // This means that the impl is missing a definition for the . // associated type. This error will be reported by the type . // checker method `check_impl_items_against_trait`, so here we . // just return Error. . debug!( . "confirm_impl_candidate: no associated type {:?} for {:?}", . assoc_ty.item.name, obligation.predicate . ); -- line 1846 ---------------------------------------- -- line 1847 ---------------------------------------- . return Progress { ty: tcx.ty_error(), obligations: nested }; . } . // If we're trying to normalize ` as X>::A` using . //`impl X for Vec { type A = Box; }`, then: . // . // * `obligation.predicate.substs` is `[Vec, S]` . // * `substs` is `[u32]` . // * `substs` ends up as `[u32, S]` 320,352 ( 0.00%) let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs); . let substs = 587,312 ( 0.00%) translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.defining_node); 53,392 ( 0.00%) let ty = tcx.type_of(assoc_ty.item.def_id); 160,176 ( 0.00%) if substs.len() != tcx.generics_of(assoc_ty.item.def_id).count() { . let err = tcx.ty_error_with_message( . obligation.cause.span, . "impl item and trait item have different parameter counts", . ); . Progress { ty: err, obligations: nested } . } else { 106,784 ( 0.00%) assoc_ty_own_obligations(selcx, obligation, &mut nested); . Progress { ty: ty.subst(tcx, substs), obligations: nested } . } . } . . // Get obligations corresponding to the predicates from the where-clause of the . // associated type itself. . // Note: `feature(generic_associated_types)` is required to write such . // predicates, even for non-generic associcated types. 621,720 ( 0.00%) fn assoc_ty_own_obligations<'cx, 'tcx>( . selcx: &mut SelectionContext<'cx, 'tcx>, . obligation: &ProjectionTyObligation<'tcx>, . nested: &mut Vec>, . ) { . let tcx = selcx.tcx(); 621,720 ( 0.00%) for predicate in tcx 138,160 ( 0.00%) .predicates_of(obligation.predicate.item_def_id) 207,240 ( 0.00%) .instantiate_own(tcx, obligation.predicate.substs) . .predicates . { . let normalized = normalize_with_depth_to( . selcx, . obligation.param_env, . obligation.cause.clone(), . obligation.recursion_depth + 1, . predicate, -- line 1891 ---------------------------------------- -- line 1893 ---------------------------------------- . ); . nested.push(Obligation::with_depth( . obligation.cause.clone(), . obligation.recursion_depth + 1, . obligation.param_env, . normalized, . )); . } 552,640 ( 0.00%) } . . /// Locate the definition of an associated type in the specialization hierarchy, . /// starting from the given impl. . /// . /// Based on the "projection mode", this lookup may in fact only examine the . /// topmost impl. See the comments for `Reveal` for more details. 972,342 ( 0.00%) fn assoc_ty_def( . selcx: &SelectionContext<'_, '_>, . impl_def_id: DefId, . assoc_ty_def_id: DefId, . ) -> Result { . let tcx = selcx.tcx(); 216,076 ( 0.00%) let trait_def_id = tcx.impl_trait_ref(impl_def_id).unwrap().def_id; . let trait_def = tcx.trait_def(trait_def_id); . . // This function may be called while we are still building the . // specialization graph that is queried below (via TraitDef::ancestors()), . // so, in order to avoid unnecessary infinite recursion, we manually look . // for the associated item at the given impl. . // If there is no such item in that impl, this function will fail with a . // cycle error if the specialization graph is currently being built. 216,076 ( 0.00%) if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_ty_def_id) { . let item = tcx.associated_item(impl_item_id); . let impl_node = specialization_graph::Node::Impl(impl_def_id); 1,296,456 ( 0.00%) return Ok(specialization_graph::LeafDef { 648,228 ( 0.00%) item: *item, . defining_node: impl_node, 540,190 ( 0.00%) finalizing_node: if item.defaultness.is_default() { None } else { Some(impl_node) }, . }); . } . . let ancestors = trait_def.ancestors(tcx, impl_def_id)?; . if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_ty_def_id) { . Ok(assoc_item) . } else { . // This is saying that neither the trait nor -- line 1937 ---------------------------------------- -- line 1941 ---------------------------------------- . // if the user wrote a bad item name, it . // should have failed in astconv. . bug!( . "No associated type `{}` for {}", . tcx.item_name(assoc_ty_def_id), . tcx.def_path_str(impl_def_id) . ) . } 972,342 ( 0.00%) } . . crate trait ProjectionCacheKeyExt<'cx, 'tcx>: Sized { . fn from_poly_projection_predicate( . selcx: &mut SelectionContext<'cx, 'tcx>, . predicate: ty::PolyProjectionPredicate<'tcx>, . ) -> Option; . } . . impl<'cx, 'tcx> ProjectionCacheKeyExt<'cx, 'tcx> for ProjectionCacheKey<'tcx> { 29,792 ( 0.00%) fn from_poly_projection_predicate( . selcx: &mut SelectionContext<'cx, 'tcx>, . predicate: ty::PolyProjectionPredicate<'tcx>, . ) -> Option { . let infcx = selcx.infcx(); . // We don't do cross-snapshot caching of obligations with escaping regions, . // so there's no cache key to use 25,536 ( 0.00%) predicate.no_bound_vars().map(|predicate| { 8,508 ( 0.00%) ProjectionCacheKey::new( . // We don't attempt to match up with a specific type-variable state . // from a specific call to `opt_normalize_projection_type` - if . // there's no precise match, the original cache entry is "stranded" . // anyway. . infcx.resolve_vars_if_possible(predicate.projection_ty), . ) . }) 34,048 ( 0.00%) } . } 157,105,203 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/combine.rs -------------------------------------------------------------------------------- Ir -- line 56 ---------------------------------------- . #[derive(Copy, Clone, Debug)] . pub enum RelationDir { . SubtypeOf, . SupertypeOf, . EqTo, . } . . impl<'infcx, 'tcx> InferCtxt<'infcx, 'tcx> { 99,801,711 ( 0.09%) pub fn super_combine_tys( . &self, . relation: &mut R, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> . where . R: TypeRelation<'tcx>, . { . let a_is_expected = relation.a_is_expected(); . 77,989,650 ( 0.07%) match (a.kind(), b.kind()) { . // Relate integral variables to other types 34 ( 0.00%) (&ty::Infer(ty::IntVar(a_id)), &ty::Infer(ty::IntVar(b_id))) => { 187 ( 0.00%) self.inner . .borrow_mut() . .int_unification_table() . .unify_var_var(a_id, b_id) . .map_err(|e| int_unification_error(a_is_expected, e))?; . Ok(a) . } 508 ( 0.00%) (&ty::Infer(ty::IntVar(v_id)), &ty::Int(v)) => { 1,016 ( 0.00%) self.unify_integral_variable(a_is_expected, v_id, IntType(v)) . } . (&ty::Int(v), &ty::Infer(ty::IntVar(v_id))) => { . self.unify_integral_variable(!a_is_expected, v_id, IntType(v)) . } 2,901 ( 0.00%) (&ty::Infer(ty::IntVar(v_id)), &ty::Uint(v)) => { 5,802 ( 0.00%) self.unify_integral_variable(a_is_expected, v_id, UintType(v)) . } 437 ( 0.00%) (&ty::Uint(v), &ty::Infer(ty::IntVar(v_id))) => { 874 ( 0.00%) self.unify_integral_variable(!a_is_expected, v_id, UintType(v)) . } . . // Relate floating-point variables to other types 12 ( 0.00%) (&ty::Infer(ty::FloatVar(a_id)), &ty::Infer(ty::FloatVar(b_id))) => { 66 ( 0.00%) self.inner . .borrow_mut() . .float_unification_table() . .unify_var_var(a_id, b_id) . .map_err(|e| float_unification_error(relation.a_is_expected(), e))?; . Ok(a) . } 524 ( 0.00%) (&ty::Infer(ty::FloatVar(v_id)), &ty::Float(v)) => { 524 ( 0.00%) self.unify_float_variable(a_is_expected, v_id, v) . } 256 ( 0.00%) (&ty::Float(v), &ty::Infer(ty::FloatVar(v_id))) => { 256 ( 0.00%) self.unify_float_variable(!a_is_expected, v_id, v) . } . . // All other cases of inference are errors . (&ty::Infer(_), _) | (_, &ty::Infer(_)) => { 93,630 ( 0.00%) Err(TypeError::Sorts(ty::relate::expected_found(relation, a, b))) . } . 66,845,742 ( 0.06%) _ => ty::relate::super_relate_tys(relation, a, b), . } 99,801,711 ( 0.09%) } . 119,064,216 ( 0.10%) pub fn super_combine_consts( . &self, . relation: &mut R, . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> . where . R: ConstEquateRelation<'tcx>, . { . debug!("{}.consts({:?}, {:?})", relation.tag(), a, b); 49,623,085 ( 0.04%) if a == b { . return Ok(a); . } . 29,723,604 ( 0.03%) let a = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), a); 29,723,604 ( 0.03%) let b = replace_if_possible(&mut self.inner.borrow_mut().const_unification_table(), b); . . let a_is_expected = relation.a_is_expected(); . 119,227,018 ( 0.10%) match (a.val, b.val) { . ( . ty::ConstKind::Infer(InferConst::Var(a_vid)), . ty::ConstKind::Infer(InferConst::Var(b_vid)), . ) => { 117,564 ( 0.00%) self.inner . .borrow_mut() . .const_unification_table() . .unify_var_var(a_vid, b_vid) . .map_err(|e| const_unification_error(a_is_expected, e))?; . return Ok(a); . } . . // All other cases of inference with other variables are errors. . (ty::ConstKind::Infer(InferConst::Var(_)), ty::ConstKind::Infer(_)) . | (ty::ConstKind::Infer(_), ty::ConstKind::Infer(InferConst::Var(_))) => { . bug!("tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var)") . } . . (ty::ConstKind::Infer(InferConst::Var(vid)), _) => { 44,817,388 ( 0.04%) return self.unify_const_variable(relation.param_env(), vid, b, a_is_expected); . } . . (_, ty::ConstKind::Infer(InferConst::Var(vid))) => { 321,085 ( 0.00%) return self.unify_const_variable(relation.param_env(), vid, a, !a_is_expected); . } 572 ( 0.00%) (ty::ConstKind::Unevaluated(..), _) if self.tcx.lazy_normalization() => { . // FIXME(#59490): Need to remove the leak check to accommodate . // escaping bound variables here. . if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() { . relation.const_equate_obligation(a, b); . } . return Ok(b); . } . (_, ty::ConstKind::Unevaluated(..)) if self.tcx.lazy_normalization() => { -- line 176 ---------------------------------------- -- line 179 ---------------------------------------- . if !a.has_escaping_bound_vars() && !b.has_escaping_bound_vars() { . relation.const_equate_obligation(a, b); . } . return Ok(a); . } . _ => {} . } . 17,108,255 ( 0.01%) ty::relate::super_relate_consts(relation, a, b) 89,298,162 ( 0.08%) } . . /// Unifies the const variable `target_vid` with the given constant. . /// . /// This also tests if the given const `ct` contains an inference variable which was previously . /// unioned with `target_vid`. If this is the case, inferring `target_vid` to `ct` . /// would result in an infinite type as we continuously replace an inference variable . /// in `ct` with `ct` itself. . /// -- line 196 ---------------------------------------- -- line 216 ---------------------------------------- . /// of `fn bind` (meaning that its substs contain `N`). . /// . /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`. . /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`. . /// . /// As `3 + 4` contains `N` in its substs, this must not succeed. . /// . /// See `src/test/ui/const-generics/occurs-check/` for more examples where this is relevant. 122,865,837 ( 0.11%) #[instrument(level = "debug", skip(self))] . fn unify_const_variable( . &self, . param_env: ty::ParamEnv<'tcx>, . target_vid: ty::ConstVid<'tcx>, . ct: &'tcx ty::Const<'tcx>, . vid_is_expected: bool, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { . let (for_universe, span) = { . let mut inner = self.inner.borrow_mut(); 25,866,492 ( 0.02%) let variable_table = &mut inner.const_unification_table(); 12,933,246 ( 0.01%) let var_value = variable_table.probe_value(target_vid); 12,933,246 ( 0.01%) match var_value.val { . ConstVariableValue::Known { value } => { . bug!("instantiating {:?} which has a known value {:?}", target_vid, value) . } . ConstVariableValue::Unknown { universe } => (universe, var_value.origin.span), . } . }; 51,732,984 ( 0.04%) let value = ConstInferUnifier { infcx: self, span, param_env, for_universe, target_vid } . .relate(ct, ct)?; . 25,866,492 ( 0.02%) self.inner . .borrow_mut() . .const_unification_table() . .unify_var_value( . target_vid, 38,799,738 ( 0.03%) ConstVarValue { . origin: ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstInference, . span: DUMMY_SP, . }, . val: ConstVariableValue::Known { value }, . }, . ) . .map(|()| value) . .map_err(|e| const_unification_error(vid_is_expected, e)) . } . 23,076 ( 0.00%) fn unify_integral_variable( . &self, . vid_is_expected: bool, . vid: ty::IntVid, . val: ty::IntVarValue, . ) -> RelateResult<'tcx, Ty<'tcx>> { 30,768 ( 0.00%) self.inner . .borrow_mut() . .int_unification_table() . .unify_var_value(vid, Some(val)) . .map_err(|e| int_unification_error(vid_is_expected, e))?; 7,692 ( 0.00%) match val { 508 ( 0.00%) IntType(v) => Ok(self.tcx.mk_mach_int(v)), 10,522 ( 0.00%) UintType(v) => Ok(self.tcx.mk_mach_uint(v)), . } 30,768 ( 0.00%) } . 1,950 ( 0.00%) fn unify_float_variable( . &self, . vid_is_expected: bool, . vid: ty::FloatVid, . val: ty::FloatTy, . ) -> RelateResult<'tcx, Ty<'tcx>> { 2,730 ( 0.00%) self.inner . .borrow_mut() . .float_unification_table() . .unify_var_value(vid, Some(ty::FloatVarValue(val))) . .map_err(|e| float_unification_error(vid_is_expected, e))?; 2,328 ( 0.00%) Ok(self.tcx.mk_mach_float(val)) 2,730 ( 0.00%) } . } . . impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { . pub fn tcx(&self) -> TyCtxt<'tcx> { 58,124,199 ( 0.05%) self.infcx.tcx . } . . pub fn equate<'a>(&'a mut self, a_is_expected: bool) -> Equate<'a, 'infcx, 'tcx> { . Equate::new(self, a_is_expected) . } . 2,614,876 ( 0.00%) pub fn sub<'a>(&'a mut self, a_is_expected: bool) -> Sub<'a, 'infcx, 'tcx> { . Sub::new(self, a_is_expected) 1,307,438 ( 0.00%) } . . pub fn lub<'a>(&'a mut self, a_is_expected: bool) -> Lub<'a, 'infcx, 'tcx> { . Lub::new(self, a_is_expected) . } . 22,566,292 ( 0.02%) pub fn glb<'a>(&'a mut self, a_is_expected: bool) -> Glb<'a, 'infcx, 'tcx> { . Glb::new(self, a_is_expected) 11,283,146 ( 0.01%) } . . /// Here, `dir` is either `EqTo`, `SubtypeOf`, or `SupertypeOf`. . /// The idea is that we should ensure that the type `a_ty` is equal . /// to, a subtype of, or a supertype of (respectively) the type . /// to which `b_vid` is bound. . /// . /// Since `b_vid` has not yet been instantiated with a type, we . /// will first instantiate `b_vid` with a *generalized* version . /// of `a_ty`. Generalization introduces other inference . /// variables wherever subtyping could occur. 4,766,124 ( 0.00%) pub fn instantiate( . &mut self, . a_ty: Ty<'tcx>, . dir: RelationDir, . b_vid: ty::TyVid, . a_is_expected: bool, . ) -> RelateResult<'tcx, ()> { . use self::RelationDir::*; . -- line 333 ---------------------------------------- -- line 342 ---------------------------------------- . // - `a_ty == &'x ?1`, where `'x` is some free region and `?1` is an . // inference variable, . // - and `dir` == `SubtypeOf`. . // . // Then the generalized form `b_ty` would be `&'?2 ?3`, where . // `'?2` and `?3` are fresh region/type inference . // variables. (Down below, we will relate `a_ty <: b_ty`, . // adding constraints like `'x: '?2` and `?1 <: ?3`.) 433,205 ( 0.00%) let Generalization { ty: b_ty, needs_wf } = self.generalize(a_ty, b_vid, dir)?; . debug!( . "instantiate(a_ty={:?}, dir={:?}, b_vid={:?}, generalized b_ty={:?})", . a_ty, dir, b_vid, b_ty . ); 3,032,435 ( 0.00%) self.infcx.inner.borrow_mut().type_variables().instantiate(b_vid, b_ty); . 433,205 ( 0.00%) if needs_wf { . self.obligations.push(Obligation::new( . self.trace.cause.clone(), . self.param_env, . ty::Binder::dummy(ty::PredicateKind::WellFormed(b_ty.into())) . .to_predicate(self.infcx.tcx), . )); . } . . // Finally, relate `b_ty` to `a_ty`, as described in previous comment. . // . // FIXME(#16847): This code is non-ideal because all these subtype . // relations wind up attributed to the same spans. We need . // to associate causes/spans with each of the relations in . // the stack to get this right. 1,640,062 ( 0.00%) match dir { 1,739,045 ( 0.00%) EqTo => self.equate(a_is_expected).relate(a_ty, b_ty), 231,895 ( 0.00%) SubtypeOf => self.sub(a_is_expected).relate(a_ty, b_ty), 78,034 ( 0.00%) SupertypeOf => self.sub(a_is_expected).relate_with_variance( . ty::Contravariant, . ty::VarianceDiagInfo::default(), . a_ty, . b_ty, . ), . }?; . 433,205 ( 0.00%) Ok(()) 3,466,272 ( 0.00%) } . . /// Attempts to generalize `ty` for the type variable `for_vid`. . /// This checks for cycle -- that is, whether the type `ty` . /// references `for_vid`. The `dir` is the "direction" for which we . /// a performing the generalization (i.e., are we producing a type . /// that can be used as a supertype etc). . /// . /// Preconditions: -- line 392 ---------------------------------------- -- line 401 ---------------------------------------- . debug!("generalize(ty={:?}, for_vid={:?}, dir={:?}", ty, for_vid, dir); . // Determine the ambient variance within which `ty` appears. . // The surrounding equation is: . // . // ty [op] ty2 . // . // where `op` is either `==`, `<:`, or `:>`. This maps quite . // naturally. 1,733,136 ( 0.00%) let ambient_variance = match dir { . RelationDir::EqTo => ty::Invariant, . RelationDir::SubtypeOf => ty::Covariant, . RelationDir::SupertypeOf => ty::Contravariant, . }; . . debug!("generalize: ambient_variance = {:?}", ambient_variance); . 4,332,840 ( 0.00%) let for_universe = match self.infcx.inner.borrow_mut().type_variables().probe(for_vid) { . v @ TypeVariableValue::Known { .. } => { . bug!("instantiating {:?} which has a known value {:?}", for_vid, v,) . } . TypeVariableValue::Unknown { universe } => universe, . }; . . debug!("generalize: for_universe = {:?}", for_universe); . debug!("generalize: trace = {:?}", self.trace); . 4,332,840 ( 0.00%) let mut generalize = Generalizer { . infcx: self.infcx, . cause: &self.trace.cause, . for_vid_sub_root: self.infcx.inner.borrow_mut().type_variables().sub_root_var(for_vid), . for_universe, . ambient_variance, . needs_wf: false, . root_ty: ty, 433,284 ( 0.00%) param_env: self.param_env, . cache: SsoHashMap::new(), . }; . 866,568 ( 0.00%) let ty = match generalize.relate(ty, ty) { 433,205 ( 0.00%) Ok(ty) => ty, . Err(e) => { . debug!("generalize: failure {:?}", e); 474 ( 0.00%) return Err(e); . } . }; 433,205 ( 0.00%) let needs_wf = generalize.needs_wf; . debug!("generalize: success {{ {:?}, {:?} }}", ty, needs_wf); . Ok(Generalization { ty, needs_wf }) . } . . pub fn add_const_equate_obligation( . &mut self, . a_is_expected: bool, . a: &'tcx ty::Const<'tcx>, -- line 454 ---------------------------------------- -- line 528 ---------------------------------------- . /// will force the calling code to check that `WF(Foo)` . /// holds, which in turn implies that `?C::Item == ?D`. So once . /// `?C` is constrained, that should suffice to restrict `?D`. . needs_wf: bool, . } . . impl<'tcx> TypeRelation<'tcx> for Generalizer<'_, 'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 1,122,062 ( 0.00%) self.infcx.tcx . } . fn param_env(&self) -> ty::ParamEnv<'tcx> { 109,875 ( 0.00%) self.param_env . } . . fn tag(&self) -> &'static str { . "Generalizer" . } . . fn a_is_expected(&self) -> bool { . true . } . 10,823 ( 0.00%) fn binders( . &mut self, . a: ty::Binder<'tcx, T>, . b: ty::Binder<'tcx, T>, . ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> . where . T: Relate<'tcx>, . { 15,687 ( 0.00%) Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?)) 10,823 ( 0.00%) } . 2,633,015 ( 0.00%) fn relate_item_substs( . &mut self, . item_def_id: DefId, . a_subst: SubstsRef<'tcx>, . b_subst: SubstsRef<'tcx>, . ) -> RelateResult<'tcx, SubstsRef<'tcx>> { 239,365 ( 0.00%) if self.ambient_variance == ty::Variance::Invariant { . // Avoid fetching the variance if we are in an invariant . // context; no need, and it can induce dependency cycles . // (e.g., #41849). 191,975 ( 0.00%) relate::relate_substs(self, None, a_subst, b_subst) . } else { . let tcx = self.tcx(); . let opt_variances = tcx.variances_of(item_def_id); 236,950 ( 0.00%) relate::relate_substs(self, Some((item_def_id, &opt_variances)), a_subst, b_subst) . } 2,154,285 ( 0.00%) } . 231,093 ( 0.00%) fn relate_with_variance>( . &mut self, . variance: ty::Variance, . _info: ty::VarianceDiagInfo<'tcx>, . a: T, . b: T, . ) -> RelateResult<'tcx, T> { . let old_ambient_variance = self.ambient_variance; 3,145,518 ( 0.00%) self.ambient_variance = self.ambient_variance.xform(variance); . . let result = self.relate(a, b); 565,418 ( 0.00%) self.ambient_variance = old_ambient_variance; . result 179,739 ( 0.00%) } . 7,883,667 ( 0.01%) fn tys(&mut self, t: Ty<'tcx>, t2: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { 875,963 ( 0.00%) assert_eq!(t, t2); // we are abusing TypeRelation here; both LHS and RHS ought to be == . 5,255,778 ( 0.00%) if let Some(result) = self.cache.get(&t) { 355,796 ( 0.00%) return result.clone(); . } . debug!("generalize: t={:?}", t); . . // Check to see whether the type we are generalizing references . // any other type variable related to `vid` via . // subtyping. This is basically our "occurs check", preventing . // us from creating infinitely sized types. 2,558,744 ( 0.00%) let result = match *t.kind() { 31,223 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 31,223 ( 0.00%) let vid = self.infcx.inner.borrow_mut().type_variables().root_var(vid); 31,223 ( 0.00%) let sub_vid = self.infcx.inner.borrow_mut().type_variables().sub_root_var(vid); 31,223 ( 0.00%) if sub_vid == self.for_vid_sub_root { . // If sub-roots are equal, then `for_vid` and . // `vid` are related via subtyping. 395 ( 0.00%) Err(TypeError::CyclicTy(self.root_ty)) . } else { 186,864 ( 0.00%) let probe = self.infcx.inner.borrow_mut().type_variables().probe(vid); 62,288 ( 0.00%) match probe { . TypeVariableValue::Known { value: u } => { . debug!("generalize: known value {:?}", u); . self.relate(u, u) . } . TypeVariableValue::Unknown { universe } => { 113,085 ( 0.00%) match self.ambient_variance { . // Invariant: no need to make a fresh type variable. . ty::Invariant => { 89,205 ( 0.00%) if self.for_universe.can_name(universe) { 71,104 ( 0.00%) return Ok(t); . } . } . . // Bivariant: make a fresh var, but we . // may need a WF predicate. See . // comment on `needs_wf` field for . // more info. . ty::Bivariant => self.needs_wf = true, . . // Co/contravariant: this will be . // sufficiently constrained later on. . ty::Covariant | ty::Contravariant => (), . } . . let origin = 43,569 ( 0.00%) *self.infcx.inner.borrow_mut().type_variables().var_origin(vid); 33,887 ( 0.00%) let new_var_id = self . .infcx . .inner . .borrow_mut() . .type_variables() 33,887 ( 0.00%) .new_var(self.for_universe, origin); . let u = self.tcx().mk_ty_var(new_var_id); . . // Record that we replaced `vid` with `new_var_id` as part of a generalization . // operation. This is needed to detect cyclic types. To see why, see the . // docs in the `type_variables` module. 24,205 ( 0.00%) self.infcx.inner.borrow_mut().type_variables().sub(vid, new_var_id); . debug!("generalize: replacing original vid={:?} with new={:?}", vid, u); 9,682 ( 0.00%) Ok(u) . } . } . } . } . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => { . // No matter what mode we are in, . // integer/floating-point types must be equal to be . // relatable. 2,591 ( 0.00%) Ok(t) . } 2,259,600 ( 0.00%) _ => relate::super_relate_tys(self, t, t), . }; . 7,692,380 ( 0.01%) self.cache.insert(t, result.clone()); 4,615,428 ( 0.00%) return result; 7,883,667 ( 0.01%) } . 331,976 ( 0.00%) fn regions( . &mut self, . r: ty::Region<'tcx>, . r2: ty::Region<'tcx>, . ) -> RelateResult<'tcx, ty::Region<'tcx>> { 39,775 ( 0.00%) assert_eq!(r, r2); // we are abusing TypeRelation here; both LHS and RHS ought to be == . . debug!("generalize: regions r={:?}", r); . 79,550 ( 0.00%) match *r { . // Never make variables for regions bound within the type itself, . // nor for erased regions. . ty::ReLateBound(..) | ty::ReErased => { . return Ok(r); . } . . ty::RePlaceholder(..) . | ty::ReVar(..) -- line 691 ---------------------------------------- -- line 697 ---------------------------------------- . } . } . . // If we are in an invariant context, we can re-use the region . // as is, unless it happens to be in some universe that we . // can't name. (In the case of a region *variable*, we could . // use it if we promoted it into our universe, but we don't . // bother.) 80,454 ( 0.00%) if let ty::Invariant = self.ambient_variance { 79,818 ( 0.00%) let r_universe = self.infcx.universe_of_region(r); 186,236 ( 0.00%) if self.for_universe.can_name(r_universe) { . return Ok(r); . } . } . . // FIXME: This is non-ideal because we don't give a . // very descriptive origin for this region variable. 136,264 ( 0.00%) Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.cause.span), self.for_universe)) 331,976 ( 0.00%) } . 1,079,109 ( 0.00%) fn consts( . &mut self, . c: &'tcx ty::Const<'tcx>, . c2: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { 329,625 ( 0.00%) assert_eq!(c, c2); // we are abusing TypeRelation here; both LHS and RHS ought to be == . . match c.val { . ty::ConstKind::Infer(InferConst::Var(vid)) => { 10,026 ( 0.00%) let mut inner = self.infcx.inner.borrow_mut(); 40,104 ( 0.00%) let variable_table = &mut inner.const_unification_table(); 10,026 ( 0.00%) let var_value = variable_table.probe_value(vid); 20,052 ( 0.00%) match var_value.val { . ConstVariableValue::Known { value: u } => { . drop(inner); . self.relate(u, u) . } 6,458 ( 0.00%) ConstVariableValue::Unknown { universe } => { 32,290 ( 0.00%) if self.for_universe.can_name(universe) { . Ok(c) . } else { . let new_var_id = variable_table.new_key(ConstVarValue { . origin: var_value.origin, . val: ConstVariableValue::Unknown { universe: self.for_universe }, . }); . Ok(self.tcx().mk_const_var(new_var_id, c.ty)) . } -- line 743 ---------------------------------------- -- line 754 ---------------------------------------- . substs, . substs, . )?; . Ok(self.tcx().mk_const(ty::Const { . ty: c.ty, . val: ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }), . })) . } 549,375 ( 0.00%) _ => relate::super_relate_consts(self, c, c), . } 1,079,109 ( 0.00%) } . } . . pub trait ConstEquateRelation<'tcx>: TypeRelation<'tcx> { . /// Register an obligation that both constants must be equal to each other. . /// . /// If they aren't equal then the relation doesn't hold. . fn const_equate_obligation(&mut self, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>); . } -- line 772 ---------------------------------------- -- line 824 ---------------------------------------- . target_vid: ty::ConstVid<'tcx>, . } . . // We use `TypeRelation` here to propagate `RelateResult` upwards. . // . // Both inputs are expected to be the same. . impl<'tcx> TypeRelation<'tcx> for ConstInferUnifier<'_, 'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 25,845,191 ( 0.02%) self.infcx.tcx . } . . fn param_env(&self) -> ty::ParamEnv<'tcx> { 6,466,623 ( 0.01%) self.param_env . } . . fn tag(&self) -> &'static str { . "ConstInferUnifier" . } . . fn a_is_expected(&self) -> bool { . true -- line 844 ---------------------------------------- -- line 937 ---------------------------------------- . return Ok(r); . } else { . // FIXME: This is non-ideal because we don't give a . // very descriptive origin for this region variable. . Ok(self.infcx.next_region_var_in_universe(MiscVariable(self.span), self.for_universe)) . } . } . 122,865,837 ( 0.11%) #[tracing::instrument(level = "debug", skip(self))] . fn consts( . &mut self, . c: &'tcx ty::Const<'tcx>, . _c: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { . debug_assert_eq!(c, _c); . debug!("ConstInferUnifier: c={:?}", c); . 32,333,115 ( 0.03%) match c.val { . ty::ConstKind::Infer(InferConst::Var(vid)) => { . // Check if the current unification would end up . // unifying `target_vid` with a const which contains . // an inference variable which is unioned with `target_vid`. . // . // Not doing so can easily result in stack overflows. . if self . .infcx -- line 962 ---------------------------------------- -- line 1000 ---------------------------------------- . substs, . substs, . )?; . Ok(self.tcx().mk_const(ty::Const { . ty: c.ty, . val: ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }), . })) . } 32,333,115 ( 0.03%) _ => relate::super_relate_consts(self, c, c), . } . } . } 83,761,792 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/cmp.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32; . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<[B]> for [A] . where . A: PartialEq, . { 1,135,276 ( 0.00%) fn eq(&self, other: &[B]) -> bool { . SlicePartialEq::equal(self, other) 1,383,945 ( 0.00%) } . . fn ne(&self, other: &[B]) -> bool { . SlicePartialEq::not_equal(self, other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for [T] {} -- line 36 ---------------------------------------- -- line 62 ---------------------------------------- . } . . // Generic slice equality . impl SlicePartialEq for [A] . where . A: PartialEq, . { . default fn equal(&self, other: &[B]) -> bool { 93,298,444 ( 0.08%) if self.len() != other.len() { . return false; . } . 450,159 ( 0.00%) self.iter().zip(other.iter()).all(|(x, y)| x == y) . } . } . . // Use memcmp for bytewise equality when the types allow . impl SlicePartialEq for [A] . where . A: BytewiseEquality, . { . fn equal(&self, other: &[B]) -> bool { 462,867 ( 0.00%) if self.len() != other.len() { . return false; . } . . // SAFETY: `self` and `other` are references and are thus guaranteed to be valid. . // The two slices have been checked to have the same size above. . unsafe { . let size = mem::size_of_val(self); 1,655,759 ( 0.00%) memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0 . } . } . } . . #[doc(hidden)] . // intermediate trait for specialization of slice's PartialOrd . trait SlicePartialOrd: Sized { . fn partial_compare(left: &[Self], right: &[Self]) -> Option; -- line 100 ---------------------------------------- -- line 168 ---------------------------------------- . default fn compare(left: &[Self], right: &[Self]) -> Ordering { . let l = cmp::min(left.len(), right.len()); . . // Slice to the loop iteration range to enable bound check . // elimination in the compiler . let lhs = &left[..l]; . let rhs = &right[..l]; . 2 ( 0.00%) for i in 0..l { . match lhs[i].cmp(&rhs[i]) { . Ordering::Equal => (), . non_eq => return non_eq, . } . } . . left.len().cmp(&right.len()) . } -- line 184 ---------------------------------------- -- line 188 ---------------------------------------- . // this matches the order we want for [u8], but no others (not even [i8]). . impl SliceOrd for u8 { . #[inline] . fn compare(left: &[Self], right: &[Self]) -> Ordering { . let order = . // SAFETY: `left` and `right` are references and are thus guaranteed to be valid. . // We use the minimum of both lengths which guarantees that both regions are . // valid for reads in that interval. 11,915 ( 0.00%) unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) }; 23,479 ( 0.00%) if order == 0 { . left.len().cmp(&right.len()) 9,551 ( 0.00%) } else if order < 0 { . Less . } else { . Greater . } . } . } . . // Hack to allow specializing on `Eq` even though `Eq` has a method. -- line 207 ---------------------------------------- -- line 230 ---------------------------------------- . pub(super) trait SliceContains: Sized { . fn slice_contains(&self, x: &[Self]) -> bool; . } . . impl SliceContains for T . where . T: PartialEq, . { 2,652 ( 0.00%) default fn slice_contains(&self, x: &[Self]) -> bool { 383,901 ( 0.00%) x.iter().any(|y| *y == *self) 3,978 ( 0.00%) } . } . . impl SliceContains for u8 { . #[inline] . fn slice_contains(&self, x: &[Self]) -> bool { . memchr::memchr(*self, x).is_some() . } . } -- line 248 ---------------------------------------- 102,609,376 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/unify/mod.rs -------------------------------------------------------------------------------- Ir -- line 131 ---------------------------------------- . /// Otherwise, the error `(v1, v2)` is returned, where `v1` and `v2` . /// are the two unequal values. . pub trait EqUnifyValue: Eq + Clone + Debug {} . . impl UnifyValue for T { . type Error = (T, T); . . fn unify_values(value1: &Self, value2: &Self) -> Result { 24 ( 0.00%) if value1 == value2 { . Ok(value1.clone()) . } else { . Err((value1.clone(), value2.clone())) . } . } . } . . /// A struct which can never be instantiated. Used -- line 147 ---------------------------------------- -- line 154 ---------------------------------------- . /// Value of a unification key. We implement Tarjan's union-find . /// algorithm: when two keys are unified, one of them is converted . /// into a "redirect" pointing at the other. These redirects form a . /// DAG: the roots of the DAG (nodes that are not redirected) are each . /// associated with a value of type `V` and a rank. The rank is used . /// to keep the DAG relatively balanced, which helps keep the running . /// time of the algorithm under control. For more information, see . /// . 320,699 ( 0.00%) #[derive(PartialEq, Clone, Debug)] . pub struct VarValue { 7,009,518 ( 0.01%) parent: K, // if equal to self, this is a root 15,432 ( 0.00%) value: K::Value, // value assigned (only relevant to root) 7,001,814 ( 0.01%) rank: u32, // max depth (only relevant to root) . } . . /// Table of unification keys and their values. You must define a key type K . /// that implements the `UnifyKey` trait. Unification tables can be used in two-modes: . /// . /// - in-place (`UnificationTable>` or `InPlaceUnificationTable`): . /// - This is the standard mutable mode, where the array is modified . /// in place. . /// - To do backtracking, you can employ the `snapshot` and `rollback_to` . /// methods. . /// - persistent (`UnificationTable>` or `PersistentUnificationTable`): . /// - In this mode, we use a persistent vector to store the data, so that . /// cloning the table is an O(1) operation. . /// - This implies that ordinary operations are quite a bit slower though. . /// - Requires the `persistent` feature be selected in your Cargo.toml file. 1,360,975 ( 0.00%) #[derive(Clone, Debug, Default)] . pub struct UnificationTable { . /// Indicates the current value of each key. . values: S, . } . . pub type UnificationStorage = Vec>; . pub type UnificationTableStorage = UnificationTable, ()>>; . -- line 190 ---------------------------------------- -- line 215 ---------------------------------------- . } . . fn new(parent: K, value: K::Value, rank: u32) -> VarValue { . VarValue { . parent: parent, // this is a root . value: value, . rank: rank, . } 1,252,707 ( 0.00%) } . . fn redirect(&mut self, to: K) { 387,340 ( 0.00%) self.parent = to; . } . . fn root(&mut self, rank: u32, value: K::Value) { 316,273 ( 0.00%) self.rank = rank; 294,318 ( 0.00%) self.value = value; . } . . fn parent(&self, self_key: K) -> Option { 16,986,410 ( 0.01%) self.if_not_self(self.parent, self_key) . } . . fn if_not_self(&self, key: K, self_key: K) -> Option { . if key == self_key { . None . } else { . Some(key) . } -- line 243 ---------------------------------------- -- line 253 ---------------------------------------- . &'a mut self, . undo_log: L, . ) -> UnificationTable, L>> . where . L: UndoLogs>>, . { . UnificationTable { . values: InPlace { 10,026 ( 0.00%) values: self.values.values.with_log(undo_log), . }, . } . } . } . . // We can't use V:LatticeValue, much as I would like to, . // because frequently the pattern is that V=Option for some . // other type parameter U, and we have no way to say -- line 269 ---------------------------------------- -- line 311 ---------------------------------------- . pub fn len(&self) -> usize { . self.values.len() . } . } . . impl UnificationTable { . /// Starts a new snapshot. Each snapshot must be either . /// Creates a fresh key with the given value. 6,359,970 ( 0.01%) pub fn new_key(&mut self, value: S::Value) -> S::Key { . let len = self.values.len(); 5,967,404 ( 0.01%) let key: S::Key = UnifyKey::from_index(len as u32); . self.values.push(VarValue::new_var(key, value)); 2,608,070 ( 0.00%) debug!("{}: created new key: {:?}", S::tag(), key); . key 9,142,860 ( 0.01%) } . . /// Reserve memory for `num_new_keys` to be created. Does not . /// actually create the new keys; you must then invoke `new_key`. . pub fn reserve(&mut self, num_new_keys: usize) { . self.values.reserve(num_new_keys); . } . . /// Clears all unifications that have been performed, resetting to -- line 333 ---------------------------------------- -- line 339 ---------------------------------------- . let value = value(key); . VarValue::new_var(key, value) . }); . } . . /// Obtains the current value for a particular key. . /// Not for end-users; they can use `probe_value`. . fn value(&self, key: S::Key) -> &VarValue { 124,584,173 ( 0.11%) &self.values[key.index() as usize] . } . . /// Find the root node for `vid`. This uses the standard . /// union-find algorithm with path compression: . /// . . /// . /// NB. This is a building-block operation and you would probably . /// prefer to call `probe` below. . /// . /// This is an always-inlined version of this function for the hot . /// callsites. `uninlined_get_root_key` is the never-inlined version. . #[inline(always)] . fn inlined_get_root_key(&mut self, vid: S::Key) -> S::Key { . let redirect = { 109,897,415 ( 0.09%) match self.value(vid).parent(vid) { . None => return vid, . Some(redirect) => redirect, . } . }; . 67,286,682 ( 0.06%) let root_key: S::Key = self.uninlined_get_root_key(redirect); 232,921 ( 0.00%) if root_key != redirect { . // Path compression 416 ( 0.00%) self.update_value(vid, |value| value.parent = root_key); . } . 10 ( 0.00%) root_key . } . . // This is a never-inlined version of this function for cold callsites. . // 'inlined_get_root_key` is the always-inlined version. . #[inline(never)] 198,445,009 ( 0.17%) fn uninlined_get_root_key(&mut self, vid: S::Key) -> S::Key { . self.inlined_get_root_key(vid) 158,059,885 ( 0.14%) } . 1,106 ( 0.00%) fn update_value(&mut self, key: S::Key, op: OP) . where . OP: FnOnce(&mut VarValue), . { 21,124,538 ( 0.02%) self.values.update(key.index() as usize, op); 7,394,458 ( 0.01%) debug!("Updated variable {:?} to {:?}", key, self.value(key)); 700 ( 0.00%) } . . /// Either redirects `node_a` to `node_b` or vice versa, depending . /// on the relative rank. The value associated with the new root . /// will be `new_value`. . /// . /// NB: This is the "union" operation of "union-find". It is . /// really more of a building block. If the values associated with . /// your key are non-trivial, you would probably prefer to call . /// `unify_var_var` below. . fn unify_roots(&mut self, key_a: S::Key, key_b: S::Key, new_value: S::Value) { 202,469 ( 0.00%) debug!("unify(key_a={:?}, key_b={:?})", key_a, key_b); . 323,483 ( 0.00%) let rank_a = self.value(key_a).rank; 930,878 ( 0.00%) let rank_b = self.value(key_b).rank; . if let Some((new_root, redirected)) = S::Key::order_roots( 512,091 ( 0.00%) key_a, . &self.value(key_a).value, 512,091 ( 0.00%) key_b, . &self.value(key_b).value, . ) { . // compute the new rank for the new root that they chose; . // this may not be the optimal choice. . let new_rank = if new_root == key_a { . debug_assert!(redirected == key_b); . if rank_a > rank_b { . rank_a -- line 416 ---------------------------------------- -- line 422 ---------------------------------------- . debug_assert!(redirected == key_a); . if rank_b > rank_a { . rank_b . } else { . rank_a + 1 . } . }; . self.redirect_root(new_rank, redirected, new_root, new_value); 404,938 ( 0.00%) } else if rank_a > rank_b { . // a has greater rank, so a should become b's parent, . // i.e., b should redirect to a. 76,620 ( 0.00%) self.redirect_root(rank_a, key_b, key_a, new_value); 178,227 ( 0.00%) } else if rank_a < rank_b { . // b has greater rank, so a should redirect to b. 21,008 ( 0.00%) self.redirect_root(rank_b, key_a, key_b, new_value); . } else { . // If equal, redirect one to the other and increment the . // other's rank. 669,089 ( 0.00%) self.redirect_root(rank_a + 1, key_a, key_b, new_value); . } . } . . /// Internal method to redirect `old_root_key` (which is currently . /// a root) to a child of `new_root_key` (which will remain a . /// root). The rank and value of `new_root_key` will be updated to . /// `new_rank` and `new_value` respectively. 2,589,053 ( 0.00%) fn redirect_root( . &mut self, . new_rank: u32, . old_root_key: S::Key, . new_root_key: S::Key, . new_value: S::Value, . ) { . self.update_value(old_root_key, |old_root_value| { . old_root_value.redirect(new_root_key); . }); 30 ( 0.00%) self.update_value(new_root_key, |new_root_value| { 51,269 ( 0.00%) new_root_value.root(new_rank, new_value); . }); 1,411,647 ( 0.00%) } . } . . /// //////////////////////////////////////////////////////////////////////// . /// Public API . . impl UnificationTable . where . S: UnificationStoreMut, . K: UnifyKey, . V: UnifyValue, . { . /// Unions two keys without the possibility of failure; only . /// applicable when unify values use `NoError` as their error . /// type. 1,641,948 ( 0.00%) pub fn union(&mut self, a_id: K1, b_id: K2) . where . K1: Into, . K2: Into, . V: UnifyValue, . { . self.unify_var_var(a_id, b_id).unwrap(); 1,454,999 ( 0.00%) } . . /// Unions a key and a value without the possibility of failure; . /// only applicable when unify values use `NoError` as their error . /// type. 4,512,897 ( 0.00%) pub fn union_value(&mut self, id: K1, value: V) . where . K1: Into, . V: UnifyValue, . { . self.unify_var_value(id, value).unwrap(); 3,552,686 ( 0.00%) } . . /// Given two keys, indicates whether they have been unioned together. . pub fn unioned(&mut self, a_id: K1, b_id: K2) -> bool . where . K1: Into, . K2: Into, . { . self.find(a_id) == self.find(b_id) -- line 502 ---------------------------------------- -- line 503 ---------------------------------------- . } . . /// Given a key, returns the (current) root key. . pub fn find(&mut self, id: K1) -> K . where . K1: Into, . { . let id = id.into(); 1,895,496 ( 0.00%) self.uninlined_get_root_key(id) . } . . /// Unions together two variables, merging their values. If . /// merging the values fails, the error is propagated and this . /// method has no effect. 176,547 ( 0.00%) pub fn unify_var_var(&mut self, a_id: K1, b_id: K2) -> Result<(), V::Error> . where . K1: Into, . K2: Into, . { . let a_id = a_id.into(); . let b_id = b_id.into(); . 640,956 ( 0.00%) let root_a = self.uninlined_get_root_key(a_id); 619,738 ( 0.00%) let root_b = self.uninlined_get_root_key(b_id); . 40,616 ( 0.00%) if root_a == root_b { . return Ok(()); . } . 1,211,275 ( 0.00%) let combined = V::unify_values(&self.value(root_a).value, &self.value(root_b).value)?; . 77,988 ( 0.00%) Ok(self.unify_roots(root_a, root_b, combined)) 196,158 ( 0.00%) } . . /// Sets the value of the key `a_id` to `b`, attempting to merge . /// with the previous value. 58,241,187 ( 0.05%) pub fn unify_var_value(&mut self, a_id: K1, b: V) -> Result<(), V::Error> . where . K1: Into, . { . let a_id = a_id.into(); 26,774,288 ( 0.02%) let root_a = self.uninlined_get_root_key(a_id); 40,509,185 ( 0.03%) let value = V::unify_values(&self.value(root_a).value, &b)?; 39,852,888 ( 0.03%) self.update_value(root_a, |node| node.value = value); . Ok(()) 64,704,354 ( 0.06%) } . . /// Returns the current value for the given key. If the key has . /// been union'd, this will give the value from the current root. 149,313,017 ( 0.13%) pub fn probe_value(&mut self, id: K1) -> V . where . K1: Into, . { . self.inlined_probe_value(id) 108,687,962 ( 0.09%) } . . // An always-inlined version of `probe_value`, for hot callsites. . #[inline(always)] . pub fn inlined_probe_value(&mut self, id: K1) -> V . where . K1: Into, . { . let id = id.into(); . let id = self.inlined_get_root_key(id); 235,643 ( 0.00%) self.value(id).value.clone() . } . } . . /////////////////////////////////////////////////////////////////////////// . . impl UnifyValue for () { . type Error = NoError; . . fn unify_values(_: &(), _: &()) -> Result<(), NoError> { . Ok(()) 74,816 ( 0.00%) } . } . . impl UnifyValue for Option { . type Error = V::Error; . . fn unify_values(a: &Option, b: &Option) -> Result { 25,116 ( 0.00%) match (a, b) { . (&None, &None) => Ok(None), . (&Some(ref v), &None) | (&None, &Some(ref v)) => Ok(Some(v.clone())), . (&Some(ref a), &Some(ref b)) => match V::unify_values(a, b) { . Ok(v) => Ok(Some(v)), . Err(err) => Err(err), . }, . } . } -- line 593 ---------------------------------------- 50,322,126 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts.rs -------------------------------------------------------------------------------- Ir -- line 13 ---------------------------------------- . mod kind; . mod valtree; . . pub use int::*; . pub use kind::*; . pub use valtree::*; . . /// Typed constant value. 95,511,310 ( 0.08%) #[derive(Copy, Clone, Debug, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] . #[derive(HashStable)] . pub struct Const<'tcx> { 20,658,844 ( 0.02%) pub ty: Ty<'tcx>, . 20,658,972 ( 0.02%) pub val: ConstKind<'tcx>, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Const<'_>, 48); . . impl<'tcx> Const<'tcx> { . /// Literals and const generic parameters are eagerly converted to a constant, everything else . /// becomes `Unevaluated`. . pub fn from_anon_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx Self { 5,078 ( 0.00%) Self::from_opt_const_arg_anon_const(tcx, ty::WithOptConstParam::unknown(def_id)) . } . 113,152 ( 0.00%) #[instrument(skip(tcx), level = "debug")] 113,152 ( 0.00%) pub fn from_opt_const_arg_anon_const( . tcx: TyCtxt<'tcx>, . def: ty::WithOptConstParam, . ) -> &'tcx Self { . debug!("Const::from_anon_const(def={:?})", def); . 56,576 ( 0.00%) let body_id = match tcx.hir().get_by_def_id(def.did) { 28,288 ( 0.00%) hir::Node::AnonConst(ac) => ac.body, . _ => span_bug!( . tcx.def_span(def.did.to_def_id()), . "from_anon_const can only process anonymous constants" . ), . }; . 84,864 ( 0.00%) let expr = &tcx.hir().body(body_id).value; . debug!(?expr); . . let ty = tcx.type_of(def.def_id_for_type_of()); . 84,864 ( 0.00%) match Self::try_eval_lit_or_param(tcx, ty, expr) { . Some(v) => v, 6,894 ( 0.00%) None => tcx.mk_const(ty::Const { . val: ty::ConstKind::Unevaluated(ty::Unevaluated { . def: def.to_global(), 3,064 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def.did.to_def_id()), . promoted: None, . }), . ty, . }), . } . } . 254,592 ( 0.00%) #[instrument(skip(tcx), level = "debug")] . fn try_eval_lit_or_param( . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Option<&'tcx Self> { . // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments . // currently have to be wrapped in curly brackets, so it's necessary to special-case. 42,432 ( 0.00%) let expr = match &expr.kind { 1,532 ( 0.00%) hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => { . block.expr.as_ref().unwrap() . } . _ => expr, . }; . 47,748 ( 0.00%) let lit_input = match expr.kind { 9,594 ( 0.00%) hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }), . hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => match expr.kind { . hir::ExprKind::Lit(ref lit) => { . Some(LitToConstInput { lit: &lit.node, ty, neg: true }) . } . _ => None, . }, . _ => None, . }; . . if let Some(lit_input) = lit_input { . // If an error occurred, ignore that it's a literal and leave reporting the error up to . // mir. 14,408 ( 0.00%) match tcx.at(expr.span).lit_to_const(lit_input) { . Ok(c) => return Some(c), . Err(e) => { . tcx.sess.delay_span_bug( . expr.span, . &format!("Const::from_anon_const: couldn't lit_to_const {:?}", e), . ); . } . } . } . . use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath}; 80,293 ( 0.00%) match expr.kind { 34,324 ( 0.00%) ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => { . // Find the name and index of the const parameter by indexing the generics of . // the parent item and construct a `ParamConst`. . let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); 42,905 ( 0.00%) let item_id = tcx.hir().get_parent_node(hir_id); 34,324 ( 0.00%) let item_def_id = tcx.hir().local_def_id(item_id); . let generics = tcx.generics_of(item_def_id.to_def_id()); 17,162 ( 0.00%) let index = generics.param_def_id_to_index[&def_id]; 42,905 ( 0.00%) let name = tcx.hir().name(hir_id); 68,648 ( 0.00%) Some(tcx.mk_const(ty::Const { . val: ty::ConstKind::Param(ty::ParamConst::new(index, name)), . ty, . })) . } . _ => None, . } . } . -- line 131 ---------------------------------------- -- line 167 ---------------------------------------- . }; . debug_assert!(!ret.has_free_regions()); . ret . } . . /// Interns the given value as a constant. . #[inline] . pub fn from_value(tcx: TyCtxt<'tcx>, val: ConstValue<'tcx>, ty: Ty<'tcx>) -> &'tcx Self { 110,738,324 ( 0.10%) tcx.mk_const(Self { val: ConstKind::Value(val), ty }) . } . . #[inline] . /// Interns the given scalar as a constant. . pub fn from_scalar(tcx: TyCtxt<'tcx>, val: Scalar, ty: Ty<'tcx>) -> &'tcx Self { . Self::from_value(tcx, ConstValue::Scalar(val), ty) . } . . #[inline] . /// Creates a constant with the given integer value and interns it. 11,429 ( 0.00%) pub fn from_bits(tcx: TyCtxt<'tcx>, bits: u128, ty: ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx Self { 21,468 ( 0.00%) let size = tcx . .layout_of(ty) . .unwrap_or_else(|e| panic!("could not compute layout for {:?}: {:?}", ty, e)) . .size; . Self::from_scalar(tcx, Scalar::from_uint(bits, size), ty.value) 8,312 ( 0.00%) } . . #[inline] . /// Creates an interned zst constant. . pub fn zero_sized(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> &'tcx Self { . Self::from_scalar(tcx, Scalar::ZST, ty) . } . . #[inline] . /// Creates an interned bool constant. 145,104 ( 0.00%) pub fn from_bool(tcx: TyCtxt<'tcx>, v: bool) -> &'tcx Self { 115,905 ( 0.00%) Self::from_bits(tcx, v as u128, ParamEnv::empty().and(tcx.types.bool)) 145,104 ( 0.00%) } . . #[inline] . /// Creates an interned usize constant. . pub fn from_usize(tcx: TyCtxt<'tcx>, n: u64) -> &'tcx Self { 11,455 ( 0.00%) Self::from_bits(tcx, n as u128, ParamEnv::empty().and(tcx.types.usize)) . } . . #[inline] . /// Attempts to evaluate the given constant to bits. Can fail to evaluate in the presence of . /// generics (or erroneous code) or if the value can't be represented as bits (e.g. because it . /// contains const generic parameters or pointers). . pub fn try_eval_bits( . &self, . tcx: TyCtxt<'tcx>, . param_env: ParamEnv<'tcx>, . ty: Ty<'tcx>, . ) -> Option { 19 ( 0.00%) assert_eq!(self.ty, ty); 61 ( 0.00%) let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size; . // if `ty` does not depend on generic parameters, use an empty param_env 164 ( 0.00%) self.val.eval(tcx, param_env).try_to_bits(size) . } . . #[inline] . pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option { 5,181 ( 0.00%) self.val.eval(tcx, param_env).try_to_bool() . } . . #[inline] 16,528 ( 0.00%) pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Option { 16,125 ( 0.00%) self.val.eval(tcx, param_env).try_to_machine_usize(tcx) 14,224 ( 0.00%) } . . #[inline] . /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the . /// unevaluated constant. . pub fn eval(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> &Const<'tcx> { 433,520,049 ( 0.37%) if let Some(val) = self.val.try_eval(tcx, param_env) { . match val { 10,028,332 ( 0.01%) Ok(val) => Const::from_value(tcx, val, self.ty), . Err(ErrorReported) => tcx.const_error(self.ty), . } . } else { . self . } . } . . #[inline] -- line 252 ---------------------------------------- -- line 253 ---------------------------------------- . /// Panics if the value cannot be evaluated or doesn't contain a valid integer of the given type. . pub fn eval_bits(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> u128 { . self.try_eval_bits(tcx, param_env, ty) . .unwrap_or_else(|| bug!("expected bits of {:#?}, got {:#?}", ty, self)) . } . . #[inline] . /// Panics if the value cannot be evaluated or doesn't contain a valid `usize`. 36 ( 0.00%) pub fn eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> u64 { . self.try_eval_usize(tcx, param_env) . .unwrap_or_else(|| bug!("expected usize, got {:#?}", self)) 30 ( 0.00%) } . } . . pub fn const_param_default<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx Const<'tcx> { . let default_def_id = match tcx.hir().get_by_def_id(def_id.expect_local()) { . hir::Node::GenericParam(hir::GenericParam { . kind: hir::GenericParamKind::Const { ty: _, default: Some(ac) }, . .. . }) => tcx.hir().local_def_id(ac.hir_id), -- line 272 ---------------------------------------- 121,372,954 ( 0.10%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 27,199,785 ( 0.02%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 1,948,671 ( 0.00%) ctrl & 0x01 != 0 . } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize -- line 140 ---------------------------------------- -- line 143 ---------------------------------------- . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h2(hash: u64) -> u8 { . // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit . // value, some hash functions (such as FxHash) produce a usize result . // instead, which means that the top 32 bits are 0 on 32-bit platforms. . let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 3,105,086,819 ( 2.67%) let top7 = hash >> (hash_len * 8 - 7); . (top7 & 0x7f) as u8 // truncation . } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups -- line 159 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 5,565,182 ( 0.00%) self.stride += Group::WIDTH; 5,565,182 ( 0.00%) self.pos += self.stride; 5,049,893 ( 0.00%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 2,666,954 ( 0.00%) if cap < 8 { . // We don't bother with a table size of 2 buckets since that can only . // hold a single element. Instead we skip directly to a 4 bucket table . // which can hold 3 elements. 5,328,120 ( 0.00%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 1,607,118 ( 0.00%) let adjusted_cap = cap.checked_mul(8)? / 7; . . // Any overflows will have been caught by the checked_mul. Also, any . // rounding errors from the division above will be cleaned up by . // next_power_of_two (which can't overflow because of the previous division). . Some(adjusted_cap.next_power_of_two()) . } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] . fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 7,131,284 ( 0.01%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 1,797,263 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } . } . . /// Helper which allows the max calculation for ctrl_align to be statically computed for each T . /// while keeping the rest of `calculate_layout_for` independent of `T` . #[derive(Copy, Clone)] . struct TableLayout { . size: usize, -- line 233 ---------------------------------------- -- line 246 ---------------------------------------- . . #[inline] . fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . . let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 5,044,282 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 7,081,794 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 16,416 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 11,766 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 2,030 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 90,368 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 527 ---------------------------------------- . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); . Bucket::from_base_index(self.data_end(), index) . } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 573,982 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 573,982 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 1,147,964 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 172,438 ( 0.00%) self.erase_no_drop(&item); . item.drop(); . } . . /// Finds and erases an element from the table, dropping it in place. . /// Returns true if an element was found. . #[cfg(feature = "raw")] . #[cfg_attr(feature = "inline-more", inline)] . pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool { -- line 554 ---------------------------------------- -- line 563 ---------------------------------------- . } . } . . /// Removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { 975,526 ( 0.00%) self.erase_no_drop(&item); 1,984 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 10,936,136 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 35,240 ( 0.00%) match self.find(hash, eq) { 110,002 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 1,776,984 ( 0.00%) None => None, . } 13,636,882 ( 0.01%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 7 ( 0.00%) unsafe fn drop_elements(&mut self) { 348,326 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { . for item in self.iter() { . item.drop(); . } . } 8 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 642 ---------------------------------------- . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 5,991,385 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 4,783,199 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 10,813,233 ( 0.01%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { . self.table.reserve_rehash_inner( . additional, -- line 687 ---------------------------------------- -- line 690 ---------------------------------------- . TableLayout::new::(), . if mem::needs_drop::() { . Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 7,130,656 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 41,142,938 ( 0.04%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 118,330 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 26,562,214 ( 0.02%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 30,459,866 ( 0.03%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 5,037,352 ( 0.00%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 372 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 3,778,014 ( 0.00%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 26,401 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 5,241,413 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 282,564 ( 0.00%) let bucket = self.table.bucket(index); . . // If we are replacing a DELETED entry then we don't need to update . // the load counter. 11,188,791 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 8,881,033 ( 0.01%) self.table.items += 1; . bucket 52,780 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 813 ---------------------------------------- . true . } else { . false . } . } . . /// Searches for an element in the table. . #[inline] 34,137 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 127,180 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 303,490 ( 0.00%) eq(self.bucket(index).as_ref()) 47,976 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 16,171 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 34,200 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 381,440 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] 98 ( 0.00%) pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 413,767 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 112 ( 0.00%) } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. . /// . /// At most one mutable reference will be returned to any entry. `None` will be returned if any . /// of the hashes are duplicates. `None` will be returned if the hash is not found. . /// -- line 859 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 12,111,178 ( 0.01%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . -- line 936 ---------------------------------------- -- line 938 ---------------------------------------- . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { . let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 1,623,274 ( 0.00%) items: self.table.items, . } . } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. -- line 954 ---------------------------------------- -- line 995 ---------------------------------------- . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 114,612 ( 0.00%) let allocation = self.into_allocation(); 85,959 ( 0.00%) RawIntoIter { 143,265 ( 0.00%) iter, . allocation, . marker: PhantomData, . alloc, . } . } . . /// Converts the table into a raw allocation. The contents of the table . /// should be dropped using a `RawIter` before freeing the allocation. . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 47,531 ( 0.00%) let alloc = if self.table.is_empty_singleton() { . None . } else { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match calculate_layout::(self.table.buckets()) { . Some(lco) => lco, . None => unsafe { hint::unreachable_unchecked() }, . }; . Some(( 5,379 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1042 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 14,408,033 ( 0.01%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 9,304,964 ( 0.01%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 1,930,710 ( 0.00%) let ptr: NonNull = match do_alloc(&alloc, layout) { . Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . . let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 5,090,694 ( 0.00%) Ok(Self { . ctrl, 2,182,332 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 6,768,942 ( 0.01%) } . . #[inline] 231,780 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 64,704 ( 0.00%) if capacity == 0 { 59,124 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 4,224,157 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 112,359 ( 0.00%) Ok(result) . } . } 231,780 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element and sets the hash for that slot. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] 1,922,289 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 1,922,289 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 3,844,578 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 17,595,443 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 51,817,150 ( 0.04%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 23,892,664 ( 0.02%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 2,610,932 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 277,644,149 ( 0.24%) for bit in group.match_byte(h2_hash) { 762,625,291 ( 0.66%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 547,921,174 ( 0.47%) if likely(eq(index)) { . return Some(index); . } . } . 16,460,326 ( 0.01%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_rehash_in_place(&mut self) { . // Bulk convert all full control bytes to DELETED, and all DELETED . // control bytes to EMPTY. This effectively frees up all buckets . // containing a DELETED entry. 139 ( 0.00%) for i in (0..self.buckets()).step_by(Group::WIDTH) { . let group = Group::load_aligned(self.ctrl(i)); . let group = group.convert_special_to_empty_and_full_to_deleted(); . group.store_aligned(self.ctrl(i)); . } . . // Fix up the trailing control bytes. See the comments in set_ctrl . // for the handling of tables smaller than the group width. 129 ( 0.00%) if self.buckets() < Group::WIDTH { . self.ctrl(0) . .copy_to(self.ctrl(Group::WIDTH), self.buckets()); . } else { . self.ctrl(0) . .copy_to(self.ctrl(self.buckets()), Group::WIDTH); . } . } . -- line 1220 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 62,577,872 ( 0.05%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] . fn probe_seq(&self, hash: u64) -> ProbeSeq { . ProbeSeq { 1,184,860,210 ( 1.02%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } . } . . /// Returns the index of a bucket for which a value must be inserted if there is enough rooom . /// in the table, otherwise returns error . #[cfg(feature = "raw")] . #[inline] -- line 1257 ---------------------------------------- -- line 1263 ---------------------------------------- . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] . unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 33,193,408 ( 0.03%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 26,554,620 ( 0.02%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; 879 ( 0.00%) probe_index(i) == probe_index(new_i) . } . . /// Sets a control byte to the hash, and possibly also the replicated control byte at . /// the end of the array. . #[inline] . unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) { . self.set_ctrl(index, h2(hash)); . } . . #[inline] . unsafe fn replace_ctrl_h2(&self, index: usize, hash: u64) -> u8 { 4 ( 0.00%) let prev_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . prev_ctrl . } . . /// Sets a control byte, and possibly also the replicated control byte at . /// the end of the array. . #[inline] . unsafe fn set_ctrl(&self, index: usize, ctrl: u8) { -- line 1301 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 49,228,736 ( 0.04%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 16,409,564 ( 0.01%) *self.ctrl(index) = ctrl; 16,435,082 ( 0.01%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 5,545,179 ( 0.00%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 5,059,429 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 26,722,937 ( 0.02%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 22,521 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 2,952,766 ( 0.00%) new_table.growth_left -= self.items; . new_table.items = self.items; . . // The hash function may panic, in which case we simply free the new . // table without dropping any elements that may have been copied into . // it. . // . // This guard is also used to free the old table on success, see . // the comment at the bottom of this function. . Ok(guard(new_table, move |self_| { 1,322,249 ( 0.00%) if !self_.is_empty_singleton() { . self_.free_buckets(table_layout); . } . })) . } . . /// Reserves or rehashes to make room for `additional` more elements. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1383 ---------------------------------------- -- line 1388 ---------------------------------------- . &mut self, . additional: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . drop: Option, . ) -> Result<(), TryReserveError> { . // Avoid `Option::ok_or_else` because it bloats LLVM IR. 2,644,585 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 2,644,584 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 5,725,687 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); 86 ( 0.00%) Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 1,322,249 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } . } . . /// Allocates a new table of a different size and moves the contents of the -- line 1418 ---------------------------------------- -- line 1424 ---------------------------------------- . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 55,895 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 9,945,776 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 1,322,249 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1496 ---------------------------------------- . } . self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items; . }); . . // At this point, DELETED elements are elements that we haven't . // rehashed yet. Find them and re-insert them at their ideal . // position. . 'outer: for i in 0..guard.buckets() { 3,072 ( 0.00%) if *guard.ctrl(i) != DELETED { . continue; . } . . let i_p = guard.bucket_ptr(i, size_of); . . 'inner: loop { . // Hash the current item . let hash = hasher(*guard, i); -- line 1512 ---------------------------------------- -- line 1515 ---------------------------------------- . let new_i = guard.find_insert_slot(hash); . let new_i_p = guard.bucket_ptr(new_i, size_of); . . // Probing works by scanning through all of the control . // bytes in groups, which may not be aligned to the group . // size. If both the new and old position fall within the . // same unaligned group, then there is no benefit in moving . // it and we can just continue to the next item. 293 ( 0.00%) if likely(guard.is_in_same_group(i, new_i, hash)) { . guard.set_ctrl_h2(i, hash); . continue 'outer; . } . . // We are moving the current item to a new position. Write . // our H2 to the control byte of the new position. . let prev_ctrl = guard.replace_ctrl_h2(new_i, hash); 8 ( 0.00%) if prev_ctrl == EMPTY { . guard.set_ctrl(i, EMPTY); . // If the target slot is empty, simply move the current . // element into the new slot and clear the old control . // byte. . ptr::copy_nonoverlapping(i_p, new_i_p, size_of); . continue 'outer; . } else { . // If the target slot is occupied, swap the two elements -- line 1539 ---------------------------------------- -- line 1541 ---------------------------------------- . // swapped into the old slot. . debug_assert_eq!(prev_ctrl, DELETED); . ptr::swap_nonoverlapping(i_p, new_i_p, size_of); . continue 'inner; . } . } . } . 129 ( 0.00%) guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; . . mem::forget(guard); . } . . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 854,661 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); . } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 156,610 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 196,121 ( 0.00%) self.items = 0; 156,612 ( 0.00%) self.growth_left = bucket_mask_to_capacity(self.bucket_mask); . } . . #[inline] . unsafe fn erase(&mut self, index: usize) { . debug_assert!(is_full(*self.ctrl(index))); 1,598,258 ( 0.00%) let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask; . let empty_before = Group::load(self.ctrl(index_before)).match_empty(); . let empty_after = Group::load(self.ctrl(index)).match_empty(); . . // If we are inside a continuous block of Group::WIDTH full or deleted . // cells then a probe window may have seen a full block when trying to . // insert. We therefore need to keep that block non-empty so that . // lookups will continue searching to the next probe window. . // . // Note that in this context `leading_zeros` refers to the bytes at the . // end of a group, while `trailing_zeros` refers to the bytes at the . // beginning of a group. 6,393,032 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 7,707,240 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 6,393,032 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 31,392 ( 0.00%) fn clone(&self) -> Self { 4,363 ( 0.00%) if self.table.is_empty_singleton() { . Self::new_in(self.table.alloc.clone()) . } else { . unsafe { . let mut new_table = ManuallyDrop::new( . // Avoid `Result::ok_or_else` because it bloats LLVM IR. . match Self::new_uninitialized( . self.table.alloc.clone(), . self.table.buckets(), -- line 1615 ---------------------------------------- -- line 1624 ---------------------------------------- . // We need to free the memory allocated for the new table. . new_table.free_buckets(); . }); . . // Return the newly created table. . ManuallyDrop::into_inner(new_table) . } . } 35,316 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 812 ( 0.00%) self.table.growth_left = source.table.growth_left; . } . } . . impl RawTable { . /// Common code for clone and clone_from. Assumes `self.buckets() == source.buckets()`. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn clone_from_impl(&mut self, source: &Self, mut on_panic: impl FnMut(&mut Self)) { . // Copy the control bytes unchanged. We do this in a single pass -- line 1703 ---------------------------------------- -- line 1790 ---------------------------------------- . fn default() -> Self { . Self::new_in(Default::default()) . } . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] 11,774,275 ( 0.01%) fn drop(&mut self) { 11,469,313 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 12,177,320 ( 0.01%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 114,612 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 143,265 ( 0.00%) } . } . . /// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does . /// not track an item count. . pub(crate) struct RawIterRange { . // Mask of full buckets in the current group. Bits are cleared from this . // mask as each element is processed. . current_group: BitMask, -- line 1838 ---------------------------------------- -- line 1934 ---------------------------------------- . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option> { . unsafe { . loop { 4,182,629 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 490,200 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 739,988 ( 0.00%) return Some(self.data.next_n(index)); . } . 3,505,673 ( 0.00%) if self.next_ctrl >= self.end { . return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 106,640 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 63,702 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 246,316 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( -- line 1966 ---------------------------------------- -- line 2102 ---------------------------------------- . } . } else { . // We must have already iterated past the removed item. . } . } . } . . unsafe fn drop_elements(&mut self) { 14,874 ( 0.00%) if mem::needs_drop::() && self.len() != 0 { . for item in self { . item.drop(); . } . } . } . } . . impl Clone for RawIter { -- line 2118 ---------------------------------------- -- line 2124 ---------------------------------------- . } . } . } . . impl Iterator for RawIter { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 587,670 ( 0.00%) fn next(&mut self) -> Option> { 1,396,394 ( 0.00%) if let Some(b) = self.iter.next() { 5,166,706 ( 0.00%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); . None . } 1,175,340 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (self.items, Some(self.items)) . } . } . . impl ExactSizeIterator for RawIter {} -- line 2151 ---------------------------------------- -- line 2177 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] 28,312 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 227,361 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 1,296 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 11,034 ( 0.00%) fn next(&mut self) -> Option { 11,039 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 22,088 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 6 ( 0.00%) self.iter.size_hint() . } . } . . impl ExactSizeIterator for RawIntoIter {} . impl FusedIterator for RawIntoIter {} . . /// Iterator which consumes elements without freeing the table storage. . pub struct RawDrain<'a, T, A: Allocator + Clone = Global> { -- line 2231 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 11,072 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 1,384 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 11,072 ( 0.00%) } . } . . impl Iterator for RawDrain<'_, T, A> { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option { . unsafe { -- line 2289 ---------------------------------------- 640,934,214 ( 0.55%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 725,227,867 ( 0.62%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 366 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { 16,871 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 16,871 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 117 ( 0.00%) let z = read(x); . copy_nonoverlapping(y, x, 1); . write(y, z); . } . } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { -- line 464 ---------------------------------------- -- line 693 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 8,358,857 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 188,963,663 ( 0.16%) tmp.assume_init() . } . } . . /// Reads the value from `src` without moving it. This leaves the . /// memory in `src` unchanged. . /// . /// Unlike [`read`], `read_unaligned` works with unaligned pointers. . /// -- line 710 ---------------------------------------- -- line 884 ---------------------------------------- . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . . // SAFETY: the caller must guarantee that `dst` is valid for writes. . // `dst` cannot overlap `src` because the caller has mutable access . // to `dst` while `src` is owned by this function. . unsafe { 1,570,307,367 ( 1.35%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 195,135 ( 0.00%) return wrapping_sub( 437,220 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 412,639,999 ( 0.35%) a == b . } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// -- line 1364 ---------------------------------------- 184,256,996 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/snapshot_vec.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . . impl Rollback> for SnapshotVecStorage { . fn reverse(&mut self, undo: UndoLog) { . self.values.reverse(undo) . } . } . impl Rollback> for Vec { . fn reverse(&mut self, undo: UndoLog) { 35,221,602 ( 0.03%) match undo { . NewElem(i) => { . self.pop(); 5,286,358 ( 0.00%) assert!(Vec::len(self) == i); . } . . SetElem(i, v) => { 40,953,011 ( 0.04%) self[i] = v; . } . . Other(u) => { . D::reverse(self, u); . } . } . } . } -- line 65 ---------------------------------------- -- line 76 ---------------------------------------- . impl VecLike for Vec . where . D: SnapshotVecDelegate, . { . fn push(&mut self, item: D::Value) { . Vec::push(self, item) . } . fn len(&self) -> usize { 847,931 ( 0.00%) Vec::len(self) . } . fn reserve(&mut self, size: usize) { . Vec::reserve(self, size) . } . } . . impl VecLike for &'_ mut Vec . where . D: SnapshotVecDelegate, . { . fn push(&mut self, item: D::Value) { . Vec::push(self, item) . } . fn len(&self) -> usize { 15,311,299 ( 0.01%) Vec::len(self) . } . fn reserve(&mut self, size: usize) { . Vec::reserve(self, size) . } . } . . #[allow(type_alias_bounds)] . pub type SnapshotVecStorage = -- line 107 ---------------------------------------- -- line 191 ---------------------------------------- . } . . impl, D: SnapshotVecDelegate, U> SnapshotVec { . pub fn len(&self) -> usize { . self.values.len() . } . . pub fn get(&self, index: usize) -> &D::Value { 170,569,798 ( 0.15%) &self.values.as_ref()[index] . } . . /// Returns a mutable pointer into the vec; whatever changes you make here cannot be undone . /// automatically, so you should be sure call `record()` with some sort of suitable undo . /// action. . pub fn get_mut(&mut self, index: usize) -> &mut D::Value { 293,856 ( 0.00%) &mut self.values.as_mut()[index] . } . . /// Reserve space for new values, just like an ordinary vec. . pub fn reserve(&mut self, additional: usize) { . // This is not affected by snapshots or anything. . self.values.reserve(additional); . } . } -- line 214 ---------------------------------------- -- line 219 ---------------------------------------- . } . . pub fn record(&mut self, action: D::Undo) { . if self.in_snapshot() { . self.undo_log.push(Other(action)); . } . } . 28,098,085 ( 0.02%) pub fn push(&mut self, elem: D::Value) -> usize { . let len = self.values.len(); . self.values.push(elem); . 3,787,959 ( 0.00%) if self.in_snapshot() { . self.undo_log.push(NewElem(len)); . } . . len 26,368,785 ( 0.02%) } . . /// Updates the element at the given index. The old value will saved (and perhaps restored) if . /// a snapshot is active. . pub fn set(&mut self, index: usize, new_elem: D::Value) { . let old_elem = mem::replace(&mut self.values.as_mut()[index], new_elem); . if self.undo_log.in_snapshot() { . self.undo_log.push(SetElem(index, old_elem)); . } -- line 244 ---------------------------------------- -- line 253 ---------------------------------------- . } . } else { . for i in 0..self.values.len() { . self.set(i, new_elems(i)); . } . } . } . 65,958,998 ( 0.06%) pub fn update(&mut self, index: usize, op: OP) . where . OP: FnOnce(&mut D::Value), . D::Value: Clone, . { 7,394,458 ( 0.01%) if self.undo_log.in_snapshot() { 29,340,318 ( 0.03%) let old_elem = self.values.as_mut()[index].clone(); 39,030,438 ( 0.03%) self.undo_log.push(SetElem(index, old_elem)); . } 28,588,475 ( 0.02%) op(&mut self.values.as_mut()[index]); 59,155,664 ( 0.05%) } . } . . impl SnapshotVec . where . D: SnapshotVecDelegate, . V: VecLike + Rollback>, . L: Snapshots>, . { -- line 279 ---------------------------------------- 7,871,038 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs -------------------------------------------------------------------------------- Ir -- line 39 ---------------------------------------- . pub fn canonicalize_query( . &self, . value: V, . query_state: &mut OriginalQueryValues<'tcx>, . ) -> Canonicalized<'tcx, V> . where . V: TypeFoldable<'tcx>, . { 160,898 ( 0.00%) self.tcx.sess.perf_stats.queries_canonicalized.fetch_add(1, Ordering::Relaxed); . 791,675 ( 0.00%) Canonicalizer::canonicalize(value, self, self.tcx, &CanonicalizeAllFreeRegions, query_state) . } . . /// Canonicalizes a query *response* `V`. When we canonicalize a . /// query response, we only canonicalize unbound inference . /// variables, and we leave other free regions alone. So, . /// continuing with the example from `canonicalize_query`, if . /// there was an input query `T: Trait<'static>`, it would have . /// been canonicalized to -- line 57 ---------------------------------------- -- line 69 ---------------------------------------- . /// things) includes a mapping to `'?0 := 'static`. When . /// canonicalizing this query result R, we would leave this . /// reference to `'static` alone. . /// . /// To get a good understanding of what is happening here, check . /// out the [chapter in the rustc dev guide][c]. . /// . /// [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html#canonicalizing-the-query-result 1,737 ( 0.00%) pub fn canonicalize_response(&self, value: V) -> Canonicalized<'tcx, V> . where . V: TypeFoldable<'tcx>, . { 143,182 ( 0.00%) let mut query_state = OriginalQueryValues::default(); 501,137 ( 0.00%) Canonicalizer::canonicalize( 840,800 ( 0.00%) value, . self, 71,591 ( 0.00%) self.tcx, . &CanonicalizeQueryResponse, . &mut query_state, . ) 1,351 ( 0.00%) } . 66,636 ( 0.00%) pub fn canonicalize_user_type_annotation(&self, value: V) -> Canonicalized<'tcx, V> . where . V: TypeFoldable<'tcx>, . { 16,938 ( 0.00%) let mut query_state = OriginalQueryValues::default(); 59,283 ( 0.00%) Canonicalizer::canonicalize( 49,749 ( 0.00%) value, . self, 8,469 ( 0.00%) self.tcx, . &CanonicalizeUserTypeAnnotation, . &mut query_state, . ) 51,828 ( 0.00%) } . . /// A variant of `canonicalize_query` that does not . /// canonicalize `'static`. This is useful when . /// the query implementation can perform more efficient . /// handling of `'static` regions (e.g. trait evaluation). 178,180 ( 0.00%) pub fn canonicalize_query_keep_static( . &self, . value: V, . query_state: &mut OriginalQueryValues<'tcx>, . ) -> Canonicalized<'tcx, V> . where . V: TypeFoldable<'tcx>, . { 729,380 ( 0.00%) self.tcx.sess.perf_stats.queries_canonicalized.fetch_add(1, Ordering::Relaxed); . 3,244,385 ( 0.00%) Canonicalizer::canonicalize( 201,002 ( 0.00%) value, . self, 364,690 ( 0.00%) self.tcx, . &CanonicalizeFreeRegionsOtherThanStatic, . query_state, . ) 178,180 ( 0.00%) } . } . . /// Controls how we canonicalize "free regions" that are not inference . /// variables. This depends on what we are canonicalizing *for* -- . /// e.g., if we are canonicalizing to create a query, we want to . /// replace those with inference variables, since we want to make a . /// maximally general query. But if we are canonicalizing a *query . /// response*, then we don't typically replace free regions, as they -- line 134 ---------------------------------------- -- line 141 ---------------------------------------- . ) -> ty::Region<'tcx>; . . fn any(&self) -> bool; . } . . struct CanonicalizeQueryResponse; . . impl CanonicalizeRegionMode for CanonicalizeQueryResponse { 519,420 ( 0.00%) fn canonicalize_free_region<'tcx>( . &self, . canonicalizer: &mut Canonicalizer<'_, 'tcx>, . r: ty::Region<'tcx>, . ) -> ty::Region<'tcx> { 311,652 ( 0.00%) match r { . ty::ReFree(_) . | ty::ReErased . | ty::ReStatic . | ty::ReEmpty(ty::UniverseIndex::ROOT) . | ty::ReEarlyBound(..) => r, . . ty::RePlaceholder(placeholder) => canonicalizer.canonical_var_for_region( . CanonicalVarInfo { kind: CanonicalVarKind::PlaceholderRegion(*placeholder) }, . r, . ), . . ty::ReVar(vid) => { 102,011 ( 0.00%) let universe = canonicalizer.region_var_universe(*vid); . canonicalizer.canonical_var_for_region( . CanonicalVarInfo { kind: CanonicalVarKind::Region(universe) }, . r, . ) . } . . ty::ReEmpty(ui) => { . bug!("canonicalizing 'empty in universe {:?}", ui) // FIXME -- line 175 ---------------------------------------- -- line 188 ---------------------------------------- . tcx.sess.delay_span_bug( . rustc_span::DUMMY_SP, . &format!("unexpected region in query response: `{:?}`", r), . ); . }); . r . } . } 519,420 ( 0.00%) } . . fn any(&self) -> bool { . false . } . } . . struct CanonicalizeUserTypeAnnotation; . . impl CanonicalizeRegionMode for CanonicalizeUserTypeAnnotation { 11,064 ( 0.00%) fn canonicalize_free_region<'tcx>( . &self, . canonicalizer: &mut Canonicalizer<'_, 'tcx>, . r: ty::Region<'tcx>, . ) -> ty::Region<'tcx> { 11,064 ( 0.00%) match r { . ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReErased | ty::ReStatic => r, . ty::ReVar(_) => canonicalizer.canonical_var_for_region_in_root_universe(r), . _ => { . // We only expect region names that the user can type. . bug!("unexpected region in query response: `{:?}`", r) . } . } 11,064 ( 0.00%) } . . fn any(&self) -> bool { . false 160,120 ( 0.00%) } . } . . struct CanonicalizeAllFreeRegions; . . impl CanonicalizeRegionMode for CanonicalizeAllFreeRegions { 905,008 ( 0.00%) fn canonicalize_free_region<'tcx>( . &self, . canonicalizer: &mut Canonicalizer<'_, 'tcx>, . r: ty::Region<'tcx>, . ) -> ty::Region<'tcx> { . canonicalizer.canonical_var_for_region_in_root_universe(r) 678,756 ( 0.00%) } . . fn any(&self) -> bool { . true 890,278 ( 0.00%) } . } . . struct CanonicalizeFreeRegionsOtherThanStatic; . . impl CanonicalizeRegionMode for CanonicalizeFreeRegionsOtherThanStatic { 3,347,085 ( 0.00%) fn canonicalize_free_region<'tcx>( . &self, . canonicalizer: &mut Canonicalizer<'_, 'tcx>, . r: ty::Region<'tcx>, . ) -> ty::Region<'tcx> { 2,231,390 ( 0.00%) if let ty::ReStatic = r { . r . } else { . canonicalizer.canonical_var_for_region_in_root_universe(r) . } 3,347,085 ( 0.00%) } . . fn any(&self) -> bool { . true . } . } . . struct Canonicalizer<'cx, 'tcx> { . infcx: &'cx InferCtxt<'cx, 'tcx>, -- line 263 ---------------------------------------- -- line 270 ---------------------------------------- . canonicalize_region_mode: &'cx dyn CanonicalizeRegionMode, . needs_canonical_flags: TypeFlags, . . binder_index: ty::DebruijnIndex, . } . . impl<'cx, 'tcx> TypeFolder<'tcx> for Canonicalizer<'cx, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 22,641,215 ( 0.02%) self.tcx 22,043,689 ( 0.02%) } . . fn fold_binder(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { 65,981,466 ( 0.06%) self.binder_index.shift_in(1); 126,284,094 ( 0.11%) let t = t.super_fold_with(self); 65,724,598 ( 0.06%) self.binder_index.shift_out(1); . t . } . 5,798,692 ( 0.00%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 8,698,038 ( 0.01%) match *r { 154 ( 0.00%) ty::ReLateBound(index, ..) => { 154 ( 0.00%) if index >= self.binder_index { . bug!("escaping late-bound region during canonicalization"); . } else { . r . } . } . . ty::ReVar(vid) => { 217,860 ( 0.00%) let resolved_vid = self . .infcx . .inner . .borrow_mut() . .unwrap_region_constraints() . .opportunistic_resolve_var(vid); . debug!( . "canonical: region var found with vid {:?}, \ . opportunistically resolved to {:?}", . vid, r . ); 871,440 ( 0.00%) let r = self.tcx.reuse_or_mk_region(r, ty::ReVar(resolved_vid)); 1,307,160 ( 0.00%) self.canonicalize_region_mode.canonicalize_free_region(self, r) . } . . ty::ReStatic . | ty::ReEarlyBound(..) . | ty::ReFree(_) . | ty::ReEmpty(_) . | ty::RePlaceholder(..) 12,316,590 ( 0.01%) | ty::ReErased => self.canonicalize_region_mode.canonicalize_free_region(self, r), . } 1,308,084 ( 0.00%) } . 213,679,128 ( 0.18%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 178,308,147 ( 0.15%) match *t.kind() { 67,316 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { . debug!("canonical: type var found with vid {:?}", vid); 269,264 ( 0.00%) match self.infcx.probe_ty_var(vid) { . // `t` could be a float / int variable; canonicalize that instead. . Ok(t) => { . debug!("(resolved to {:?})", t); . self.fold_ty(t) . } . . // `TyVar(vid)` is unresolved, track its universe index in the canonicalized . // result. . Err(mut ui) => { . // FIXME: perf problem described in #55921. . ui = ty::UniverseIndex::ROOT; . self.canonicalize_ty_var( 59,404 ( 0.00%) CanonicalVarInfo { . kind: CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)), . }, . t, . ) . } . } . } . -- line 351 ---------------------------------------- -- line 395 ---------------------------------------- . | ty::FnPtr(_) . | ty::Dynamic(..) . | ty::Never . | ty::Tuple(..) . | ty::Projection(..) . | ty::Foreign(..) . | ty::Param(..) . | ty::Opaque(..) => { 71,107,306 ( 0.06%) if t.flags().intersects(self.needs_canonical_flags) { 967,442 ( 0.00%) t.super_fold_with(self) . } else { . t . } . } . } 212,849,892 ( 0.18%) } . 167,923 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 167,162 ( 0.00%) match ct.val { 2,651 ( 0.00%) ty::ConstKind::Infer(InferConst::Var(vid)) => { . debug!("canonical: const var found with vid {:?}", vid); 10,604 ( 0.00%) match self.infcx.probe_const_var(vid) { . Ok(c) => { . debug!("(resolved to {:?})", c); . return self.fold_const(c); . } . . // `ConstVar(vid)` is unresolved, track its universe index in the . // canonicalized result . Err(mut ui) => { . // FIXME: perf problem described in #55921. . ui = ty::UniverseIndex::ROOT; . return self.canonicalize_const_var( 7,143 ( 0.00%) CanonicalVarInfo { kind: CanonicalVarKind::Const(ui, ct.ty) }, . ct, . ); . } . } . } . ty::ConstKind::Infer(InferConst::Fresh(_)) => { . bug!("encountered a fresh const during canonicalization") . } -- line 436 ---------------------------------------- -- line 445 ---------------------------------------- . return self.canonicalize_const_var( . CanonicalVarInfo { kind: CanonicalVarKind::PlaceholderConst(placeholder) }, . ct, . ); . } . _ => {} . } . 43,216 ( 0.00%) let flags = FlagComputation::for_const(ct); 21,608 ( 0.00%) if flags.intersects(self.needs_canonical_flags) { ct.super_fold_with(self) } else { ct } 143,934 ( 0.00%) } . } . . impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { . /// The main `canonicalize` method, shared impl of . /// `canonicalize_query` and `canonicalize_response`. 7,180,706 ( 0.01%) fn canonicalize( . value: V, . infcx: &InferCtxt<'_, 'tcx>, . tcx: TyCtxt<'tcx>, . canonicalize_region_mode: &dyn CanonicalizeRegionMode, . query_state: &mut OriginalQueryValues<'tcx>, . ) -> Canonicalized<'tcx, V> . where . V: TypeFoldable<'tcx>, . { 3,194,968 ( 0.00%) let needs_canonical_flags = if canonicalize_region_mode.any() { . TypeFlags::NEEDS_INFER | . TypeFlags::HAS_FREE_REGIONS | // `HAS_RE_PLACEHOLDER` implies `HAS_FREE_REGIONS` . TypeFlags::HAS_TY_PLACEHOLDER | . TypeFlags::HAS_CT_PLACEHOLDER . } else { . TypeFlags::NEEDS_INFER . | TypeFlags::HAS_RE_PLACEHOLDER . | TypeFlags::HAS_TY_PLACEHOLDER . | TypeFlags::HAS_CT_PLACEHOLDER . }; . . // Fast path: nothing that needs to be canonicalized. 351,469 ( 0.00%) if !value.has_type_flags(needs_canonical_flags) { . let canon_value = Canonical { . max_universe: ty::UniverseIndex::ROOT, . variables: List::empty(), 389,980 ( 0.00%) value, . }; 302,911 ( 0.00%) return canon_value; . } . 4,982,216 ( 0.00%) let mut canonicalizer = Canonicalizer { . infcx, . tcx, . canonicalize_region_mode, . needs_canonical_flags, . variables: SmallVec::new(), . query_state, . indices: FxHashMap::default(), . binder_index: ty::INNERMOST, . }; 1,453,873 ( 0.00%) let out_value = value.fold_with(&mut canonicalizer); . . // Once we have canonicalized `out_value`, it should not . // contain anything that ties it to this inference context . // anymore, so it should live in the global arena. . debug_assert!(!out_value.needs_infer()); . 894,378 ( 0.00%) let canonical_variables = tcx.intern_canonical_var_infos(&canonicalizer.variables); . . let max_universe = canonical_variables . .iter() 909,938 ( 0.00%) .map(|cvar| cvar.universe()) . .max() . .unwrap_or(ty::UniverseIndex::ROOT); . 2,376,773 ( 0.00%) Canonical { max_universe, variables: canonical_variables, value: out_value } 4,756,545 ( 0.00%) } . . /// Creates a canonical variable replacing `kind` from the input, . /// or returns an existing variable if `kind` has already been . /// seen. `kind` is expected to be an unbound variable (or . /// potentially a free region). 5,100,940 ( 0.00%) fn canonical_var(&mut self, info: CanonicalVarInfo<'tcx>, kind: GenericArg<'tcx>) -> BoundVar { 1,020,188 ( 0.00%) let Canonicalizer { variables, query_state, indices, .. } = self; . 1,020,188 ( 0.00%) let var_values = &mut query_state.var_values; . . // This code is hot. `variables` and `var_values` are usually small . // (fewer than 8 elements ~95% of the time). They are SmallVec's to . // avoid allocations in those cases. We also don't use `indices` to . // determine if a kind has been seen before until the limit of 8 has . // been exceeded, to also avoid allocations for `indices`. 1,020,188 ( 0.00%) if !var_values.spilled() { . // `var_values` is stack-allocated. `indices` isn't used yet. Do a . // direct linear search of `var_values`. . if let Some(idx) = var_values.iter().position(|&k| k == kind) { . // `kind` is already present in `var_values`. . BoundVar::new(idx) . } else { . // `kind` isn't present in `var_values`. Append it. Likewise . // for `info` and `variables`. . variables.push(info); . var_values.push(kind); 1,496,360 ( 0.00%) assert_eq!(variables.len(), var_values.len()); . . // If `var_values` has become big enough to be heap-allocated, . // fill up `indices` to facilitate subsequent lookups. 299,272 ( 0.00%) if var_values.spilled() { 541 ( 0.00%) assert!(indices.is_empty()); 2,164 ( 0.00%) *indices = var_values . .iter() . .enumerate() . .map(|(i, &kind)| (kind, BoundVar::new(i))) . .collect(); . } . // The cv is the index of the appended element. 598,544 ( 0.00%) BoundVar::new(var_values.len() - 1) . } . } else { . // `var_values` is large. Do a hashmap search via `indices`. 2,142 ( 0.00%) *indices.entry(kind).or_insert_with(|| { . variables.push(info); . var_values.push(kind); 6,208 ( 0.00%) assert_eq!(variables.len(), var_values.len()); 3,104 ( 0.00%) BoundVar::new(variables.len() - 1) . }) . } 4,590,846 ( 0.00%) } . . /// Shorthand helper that creates a canonical region variable for . /// `r` (always in the root universe). The reason that we always . /// put these variables into the root universe is because this . /// method is used during **query construction:** in that case, we . /// are taking all the regions and just putting them into the most . /// generic context we can. This may generate solutions that don't . /// fit (e.g., that equate some region variable with a placeholder -- line 578 ---------------------------------------- -- line 599 ---------------------------------------- . . /// Creates a canonical variable (with the given `info`) . /// representing the region `r`; return a region referencing it. . fn canonical_var_for_region( . &mut self, . info: CanonicalVarInfo<'tcx>, . r: ty::Region<'tcx>, . ) -> ty::Region<'tcx> { 1,691,383 ( 0.00%) let var = self.canonical_var(info, r.into()); . let br = ty::BoundRegion { var, kind: ty::BrAnon(var.as_u32()) }; 345,510 ( 0.00%) let region = ty::ReLateBound(self.binder_index, br); 2,418,570 ( 0.00%) self.tcx().mk_region(region) . } . . /// Given a type variable `ty_var` of the given kind, first check . /// if `ty_var` is bound to anything; if so, canonicalize . /// *that*. Otherwise, create a new canonical variable for . /// `ty_var`. 476,280 ( 0.00%) fn canonicalize_ty_var(&mut self, info: CanonicalVarInfo<'tcx>, ty_var: Ty<'tcx>) -> Ty<'tcx> { 59,535 ( 0.00%) let infcx = self.infcx; . let bound_to = infcx.shallow_resolve(ty_var); 59,535 ( 0.00%) if bound_to != ty_var { 40 ( 0.00%) self.fold_ty(bound_to) . } else { 416,710 ( 0.00%) let var = self.canonical_var(info, ty_var.into()); 59,530 ( 0.00%) self.tcx().mk_ty(ty::Bound(self.binder_index, var.into())) . } 357,180 ( 0.00%) } . . /// Given a type variable `const_var` of the given kind, first check . /// if `const_var` is bound to anything; if so, canonicalize . /// *that*. Otherwise, create a new canonical variable for . /// `const_var`. 21,429 ( 0.00%) fn canonicalize_const_var( . &mut self, . info: CanonicalVarInfo<'tcx>, . const_var: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { 2,381 ( 0.00%) let infcx = self.infcx; . let bound_to = infcx.shallow_resolve(const_var); . if bound_to != const_var { . self.fold_const(bound_to) . } else { 19,048 ( 0.00%) let var = self.canonical_var(info, const_var.into()); 16,667 ( 0.00%) self.tcx().mk_const(ty::Const { 2,381 ( 0.00%) val: ty::ConstKind::Bound(self.binder_index, var), 7,143 ( 0.00%) ty: self.fold_ty(const_var.ty), . }) . } 16,667 ( 0.00%) } . } 6,092,316 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/mod.rs -------------------------------------------------------------------------------- Ir -- line 157 ---------------------------------------- . pub fn opt_fn_def_id(self) -> Option { . if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None } . } . } . . /// The "header" of an impl is everything outside the body: a Self type, a trait . /// ref (in the case of a trait impl), and a set of predicates (from the . /// bounds / where-clauses). 1,922,132 ( 0.00%) #[derive(Clone, Debug, TypeFoldable)] . pub struct ImplHeader<'tcx> { . pub impl_def_id: DefId, . pub self_ty: Ty<'tcx>, . pub trait_ref: Option>, . pub predicates: Vec>, . } . . #[derive( . Copy, . Clone, 10,532,355 ( 0.01%) PartialEq, . Eq, . Hash, . TyEncodable, 26,928 ( 0.00%) TyDecodable, . HashStable, . Debug, . TypeFoldable . )] . pub enum ImplPolarity { . /// `impl Trait for Type` . Positive, . /// `impl !Trait for Type` -- line 188 ---------------------------------------- -- line 210 ---------------------------------------- . match self { . Self::Positive => f.write_str("positive"), . Self::Negative => f.write_str("negative"), . Self::Reservation => f.write_str("reservation"), . } . } . } . 515,242 ( 0.00%) #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)] . pub enum Visibility { . /// Visible everywhere (including in other crates). . Public, . /// Visible only in the given crate-local module. . Restricted(DefId), . /// Not visible anywhere in the local crate. This is the visibility of private external items. . Invisible, . } . 44,512,997 ( 0.04%) #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)] . pub enum BoundConstness { . /// `T: Trait` . NotConst, . /// `T: ~const Trait` . /// . /// Requires resolving to const only when we are in a const context. . ConstIfConst, . } . . impl BoundConstness { . /// Reduce `self` and `constness` to two possible combined states instead of four. 422,770 ( 0.00%) pub fn and(&mut self, constness: hir::Constness) -> hir::Constness { 634,155 ( 0.00%) match (constness, self) { . (hir::Constness::Const, BoundConstness::ConstIfConst) => hir::Constness::Const, . (_, this) => { 1,143,541 ( 0.00%) *this = BoundConstness::NotConst; . hir::Constness::NotConst . } . } 211,385 ( 0.00%) } . } . . impl fmt::Display for BoundConstness { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . match self { . Self::NotConst => f.write_str("normal"), . Self::ConstIfConst => f.write_str("`~const`"), . } -- line 256 ---------------------------------------- -- line 275 ---------------------------------------- . /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields` . pub after_feature_tys: Ty<'tcx>, . } . . pub trait DefIdTree: Copy { . fn parent(self, id: DefId) -> Option; . . fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool { 288 ( 0.00%) if descendant.krate != ancestor.krate { . return false; . } . 59,155 ( 0.00%) while descendant != ancestor { 49,760 ( 0.00%) match self.parent(descendant) { . Some(parent) => descendant = parent, . None => return false, . } . } . true . } . } . . impl<'tcx> DefIdTree for TyCtxt<'tcx> { 50,710 ( 0.00%) fn parent(self, id: DefId) -> Option { . self.def_key(id).parent.map(|index| DefId { index, ..id }) 76,065 ( 0.00%) } . } . . impl Visibility { 3,648 ( 0.00%) pub fn from_hir(visibility: &hir::Visibility<'_>, id: hir::HirId, tcx: TyCtxt<'_>) -> Self { 10,944 ( 0.00%) match visibility.node { . hir::VisibilityKind::Public => Visibility::Public, . hir::VisibilityKind::Crate(_) => Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)), . hir::VisibilityKind::Restricted { ref path, .. } => match path.res { . // If there is no resolution, `resolve` will have already reported an error, so . // assume that the visibility is public to avoid reporting more privacy errors. . Res::Err => Visibility::Public, . def => Visibility::Restricted(def.def_id()), . }, . hir::VisibilityKind::Inherited => { 7,228 ( 0.00%) Visibility::Restricted(tcx.parent_module(id).to_def_id()) . } . } 3,648 ( 0.00%) } . . /// Returns `true` if an item with this visibility is accessible from the given block. 558,009 ( 0.00%) pub fn is_accessible_from(self, module: DefId, tree: T) -> bool { 3,074,046 ( 0.00%) let restriction = match self { . // Public items are visible everywhere. . Visibility::Public => return true, . // Private items from other crates are visible nowhere. . Visibility::Invisible => return false, . // Restricted items are visible in an arbitrary local module. 41,893 ( 0.00%) Visibility::Restricted(other) if other.krate != module.krate => return false, . Visibility::Restricted(module) => module, . }; . . tree.is_descendant_of(module, restriction) 558,009 ( 0.00%) } . . /// Returns `true` if this visibility is at least as accessible as the given visibility 51,147 ( 0.00%) pub fn is_at_least(self, vis: Visibility, tree: T) -> bool { 334,828 ( 0.00%) let vis_restriction = match vis { . Visibility::Public => return self == Visibility::Public, . Visibility::Invisible => return true, . Visibility::Restricted(module) => module, . }; . . self.is_accessible_from(vis_restriction, tree) 51,147 ( 0.00%) } . . // Returns `true` if this item is visible anywhere in the local crate. . pub fn is_visible_locally(self) -> bool { . match self { . Visibility::Public => true, . Visibility::Restricted(def_id) => def_id.is_local(), . Visibility::Invisible => false, . } . } . . pub fn is_public(self) -> bool { 83,086 ( 0.00%) matches!(self, Visibility::Public) 41,543 ( 0.00%) } . } . . /// The crate variances map is computed during typeck and contains the . /// variance of every item in the local crate. You should not use it . /// directly, because to do so will make your pass dependent on the . /// HIR of every item in the local crate. Instead, use . /// `tcx.variances_of()` to get the variance for a *particular* . /// item. -- line 365 ---------------------------------------- -- line 434 ---------------------------------------- . } . . // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(TyS<'_>, 40); . . impl<'tcx> Ord for TyS<'tcx> { . fn cmp(&self, other: &TyS<'tcx>) -> Ordering { 48 ( 0.00%) self.kind().cmp(other.kind()) . } . } . . impl<'tcx> PartialOrd for TyS<'tcx> { . fn partial_cmp(&self, other: &TyS<'tcx>) -> Option { . Some(self.kind().cmp(other.kind())) . } . } -- line 450 ---------------------------------------- -- line 474 ---------------------------------------- . . // The other fields just provide fast access to information that is . // also contained in `kind`, so no need to hash them. . flags: _, . . outer_exclusive_binder: _, . } = *self; . 730 ( 0.00%) kind.hash_stable(hcx, hasher); . } . } . . #[rustc_diagnostic_item = "Ty"] . #[cfg_attr(not(bootstrap), rustc_pass_by_value)] . pub type Ty<'tcx> = &'tcx TyS<'tcx>; . . impl ty::EarlyBoundRegion { -- line 490 ---------------------------------------- -- line 509 ---------------------------------------- . #[derive(Clone, Copy, Lift)] . pub struct Predicate<'tcx> { . inner: &'tcx PredicateInner<'tcx>, . } . . impl<'tcx> PartialEq for Predicate<'tcx> { . fn eq(&self, other: &Self) -> bool { . // `self.kind` is always interned. 69,957,546 ( 0.06%) ptr::eq(self.inner, other.inner) 47,164,202 ( 0.04%) } . } . . impl Hash for Predicate<'_> { . fn hash(&self, s: &mut H) { . (self.inner as *const PredicateInner<'_>).hash(s) . } . } . . impl<'tcx> Eq for Predicate<'tcx> {} . . impl<'tcx> Predicate<'tcx> { . /// Gets the inner `Binder<'tcx, PredicateKind<'tcx>>`. . #[inline] . pub fn kind(self) -> Binder<'tcx, PredicateKind<'tcx>> { 134,585,063 ( 0.12%) self.inner.kind . } . . /// Flips the polarity of a Predicate. . /// . /// Given `T: Trait` predicate it returns `T: !Trait` and given `T: !Trait` returns `T: Trait`. . pub fn flip_polarity(&self, tcx: TyCtxt<'tcx>) -> Option> { . let kind = self . .inner -- line 541 ---------------------------------------- -- line 567 ---------------------------------------- . flags: _, . outer_exclusive_binder: _, . } = self.inner; . . kind.hash_stable(hcx, hasher); . } . } . 473,623,744 ( 0.41%) #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 1,025,464,548 ( 0.88%) #[derive(HashStable, TypeFoldable)] . pub enum PredicateKind<'tcx> { . /// Corresponds to `where Foo: Bar`. `Foo` here would be . /// the `Self` type of the trait reference and `A`, `B`, and `C` . /// would be the type parameters. . Trait(TraitPredicate<'tcx>), . . /// `where 'a: 'b` . RegionOutlives(RegionOutlivesPredicate<'tcx>), -- line 584 ---------------------------------------- -- line 594 ---------------------------------------- . WellFormed(GenericArg<'tcx>), . . /// Trait must be object-safe. . ObjectSafe(DefId), . . /// No direct syntax. May be thought of as `where T: FnFoo<...>` . /// for some substitutions `...` and `T` being a closure type. . /// Satisfied (or refuted) once we know the closure's kind. 3,259 ( 0.00%) ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind), . . /// `T1 <: T2` . /// . /// This obligation is created most often when we have two . /// unresolved type variables and hence don't have enough . /// information to process the subtyping obligation yet. 15,882 ( 0.00%) Subtype(SubtypePredicate<'tcx>), . . /// `T1` coerced to `T2` . /// . /// Like a subtyping obligation, this is created most often . /// when we have two unresolved type variables and hence . /// don't have enough information to process the coercion . /// obligation yet. At the moment, we actually process coercions . /// very much like subtyping and don't handle the full coercion -- line 617 ---------------------------------------- -- line 645 ---------------------------------------- . } . . impl<'tcx> Predicate<'tcx> { . /// Performs a substitution suitable for going from a . /// poly-trait-ref to supertraits that must hold if that . /// poly-trait-ref holds. This is slightly different from a normal . /// substitution in terms of what happens with bound regions. See . /// lengthy comment below for details. 9,576,549 ( 0.01%) pub fn subst_supertrait( . self, . tcx: TyCtxt<'tcx>, . trait_ref: &ty::PolyTraitRef<'tcx>, . ) -> Predicate<'tcx> { . // The interaction between HRTB and supertraits is not entirely . // obvious. Let me walk you (and myself) through an example. . // . // Let's start with an easy case. Consider two traits: -- line 661 ---------------------------------------- -- line 731 ---------------------------------------- . // ['x, 'b] . let bound_pred = self.kind(); . let pred_bound_vars = bound_pred.bound_vars(); . let trait_bound_vars = trait_ref.bound_vars(); . // 1) Self: Bar1<'a, '^0.0> -> Self: Bar1<'a, '^0.1> . let shifted_pred = . tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder()); . // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1> 1,064,061 ( 0.00%) let new = shifted_pred.subst(tcx, trait_ref.skip_binder().substs); . // 3) ['x] + ['b] -> ['x, 'b] . let bound_vars = . tcx.mk_bound_variable_kinds(trait_bound_vars.iter().chain(pred_bound_vars)); 9,576,549 ( 0.01%) tcx.reuse_or_mk_predicate(self, ty::Binder::bind_with_vars(new, bound_vars)) 7,448,427 ( 0.01%) } . } . 1,339,450 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 88,547,115 ( 0.08%) #[derive(HashStable, TypeFoldable)] . pub struct TraitPredicate<'tcx> { . pub trait_ref: TraitRef<'tcx>, . 56,491,131 ( 0.05%) pub constness: BoundConstness, . 130,869,572 ( 0.11%) pub polarity: ImplPolarity, . } . . pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>; . . impl<'tcx> TraitPredicate<'tcx> { 7,490,232 ( 0.01%) pub fn remap_constness(&mut self, tcx: TyCtxt<'tcx>, param_env: &mut ParamEnv<'tcx>) { 6,562,149 ( 0.01%) if unlikely!(Some(self.trait_ref.def_id) == tcx.lang_items().drop_trait()) { . // remap without changing constness of this predicate. . // this is because `T: ~const Drop` has a different meaning to `T: Drop` 8,196 ( 0.00%) param_env.remap_constness_with(self.constness) . } else { 932,181 ( 0.00%) *param_env = param_env.with_constness(self.constness.and(param_env.constness())) . } 5,617,674 ( 0.00%) } . . /// Remap the constness of this predicate before emitting it for diagnostics. . pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) { . // this is different to `remap_constness` that callees want to print this predicate . // in case of selection errors. `T: ~const Drop` bounds cannot end up here when the . // param_env is not const because we it is always satisfied in non-const contexts. . if let hir::Constness::NotConst = param_env.constness() { . self.constness = ty::BoundConstness::NotConst; . } . } . . pub fn def_id(self) -> DefId { 2,494,144 ( 0.00%) self.trait_ref.def_id 1,247,072 ( 0.00%) } . 1,054,013 ( 0.00%) pub fn self_ty(self) -> Ty<'tcx> { 3,162,039 ( 0.00%) self.trait_ref.self_ty() 2,108,026 ( 0.00%) } . } . . impl<'tcx> PolyTraitPredicate<'tcx> { . pub fn def_id(self) -> DefId { . // Ok to skip binder since trait `DefId` does not care about regions. . self.skip_binder().def_id() 10,908,646 ( 0.01%) } . 796 ( 0.00%) pub fn self_ty(self) -> ty::Binder<'tcx, Ty<'tcx>> { 3,184 ( 0.00%) self.map_bound(|trait_ref| trait_ref.self_ty()) 1,592 ( 0.00%) } . . /// Remap the constness of this predicate before emitting it for diagnostics. . pub fn remap_constness_diag(&mut self, param_env: ParamEnv<'tcx>) { . *self = self.map_bound(|mut p| { . p.remap_constness_diag(param_env); . p . }); . } . } . 477 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 1,816,157 ( 0.00%) #[derive(HashStable, TypeFoldable)] 4,897,981 ( 0.00%) pub struct OutlivesPredicate(pub A, pub B); // `A: B` . pub type RegionOutlivesPredicate<'tcx> = OutlivesPredicate, ty::Region<'tcx>>; . pub type TypeOutlivesPredicate<'tcx> = OutlivesPredicate, ty::Region<'tcx>>; . pub type PolyRegionOutlivesPredicate<'tcx> = ty::Binder<'tcx, RegionOutlivesPredicate<'tcx>>; . pub type PolyTypeOutlivesPredicate<'tcx> = ty::Binder<'tcx, TypeOutlivesPredicate<'tcx>>; . . /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates . /// whether the `a` type is the type that we should label as "expected" when . /// presenting user diagnostics. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)] 37,361 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct SubtypePredicate<'tcx> { 86,580 ( 0.00%) pub a_is_expected: bool, . pub a: Ty<'tcx>, . pub b: Ty<'tcx>, . } . pub type PolySubtypePredicate<'tcx> = ty::Binder<'tcx, SubtypePredicate<'tcx>>; . . /// Encodes that we have to coerce *from* the `a` type to the `b` type. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)] 401 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct CoercePredicate<'tcx> { . pub a: Ty<'tcx>, . pub b: Ty<'tcx>, . } . pub type PolyCoercePredicate<'tcx> = ty::Binder<'tcx, CoercePredicate<'tcx>>; . 23,621,343 ( 0.02%) #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, TyEncodable, TyDecodable)] 17,178,326 ( 0.01%) #[derive(HashStable, TypeFoldable)] . pub enum Term<'tcx> { 372 ( 0.00%) Ty(Ty<'tcx>), . Const(&'tcx Const<'tcx>), . } . . impl<'tcx> From> for Term<'tcx> { . fn from(ty: Ty<'tcx>) -> Self { . Term::Ty(ty) 266,181 ( 0.00%) } . } . . impl<'tcx> From<&'tcx Const<'tcx>> for Term<'tcx> { . fn from(c: &'tcx Const<'tcx>) -> Self { . Term::Const(c) . } . } . . impl<'tcx> Term<'tcx> { . pub fn ty(&self) -> Option> { 110,018 ( 0.00%) if let Term::Ty(ty) = self { Some(ty) } else { None } 55,009 ( 0.00%) } . } . . /// This kind of predicate has no *direct* correspondent in the . /// syntax, but it roughly corresponds to the syntactic forms: . /// . /// 1. `T: TraitRef<..., Item = Type>` . /// 2. `>::Item == Type` (NYI) . /// . /// In particular, form #1 is "desugared" to the combination of a . /// normal trait predicate (`T: TraitRef<...>`) and one of these . /// predicates. Form #2 is a broader form in that it also permits . /// equality between arbitrary types. Processing an instance of . /// Form #2 eventually yields one of these `ProjectionPredicate` . /// instances to normalize the LHS. 616 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 2,765,575 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionPredicate<'tcx> { . pub projection_ty: ProjectionTy<'tcx>, 17,926,938 ( 0.02%) pub term: Term<'tcx>, . } . . pub type PolyProjectionPredicate<'tcx> = Binder<'tcx, ProjectionPredicate<'tcx>>; . . impl<'tcx> PolyProjectionPredicate<'tcx> { . /// Returns the `DefId` of the trait of the associated item being projected. . #[inline] . pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 752 ( 0.00%) self.skip_binder().projection_ty.trait_def_id(tcx) . } . . /// Get the [PolyTraitRef] required for this projection to be well formed. . /// Note that for generic associated types the predicates of the associated . /// type also need to be checked. . #[inline] . pub fn required_poly_trait_ref(&self, tcx: TyCtxt<'tcx>) -> PolyTraitRef<'tcx> { . // Note: unlike with `TraitRef::to_poly_trait_ref()`, . // `self.0.trait_ref` is permitted to have escaping regions. . // This is because here `self` has a `Binder` and so does our . // return value, so we are preserving the number of binding . // levels. 502 ( 0.00%) self.map_bound(|predicate| predicate.projection_ty.trait_ref(tcx)) . } . . pub fn term(&self) -> Binder<'tcx, Term<'tcx>> { . self.map_bound(|predicate| predicate.term) . } . . /// The `DefId` of the `TraitItem` for the associated type. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(projection_def_id()).container`. . pub fn projection_def_id(&self) -> DefId { . // Ok to skip binder since trait `DefId` does not care about regions. 1,503,770 ( 0.00%) self.skip_binder().projection_ty.item_def_id 751,885 ( 0.00%) } . } . . pub trait ToPolyTraitRef<'tcx> { . fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx>; . } . . impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> { 527,623 ( 0.00%) fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> { 527,623 ( 0.00%) self.map_bound_ref(|trait_pred| trait_pred.trait_ref) 527,623 ( 0.00%) } . } . . pub trait ToPredicate<'tcx> { . fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx>; . } . . impl<'tcx> ToPredicate<'tcx> for Binder<'tcx, PredicateKind<'tcx>> { . #[inline(always)] . fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { . tcx.mk_predicate(self) . } . } . . impl<'tcx> ToPredicate<'tcx> for PolyTraitPredicate<'tcx> { 214,119 ( 0.00%) fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { 1,070,595 ( 0.00%) self.map_bound(PredicateKind::Trait).to_predicate(tcx) 428,238 ( 0.00%) } . } . . impl<'tcx> ToPredicate<'tcx> for PolyRegionOutlivesPredicate<'tcx> { . fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { . self.map_bound(PredicateKind::RegionOutlives).to_predicate(tcx) . } . } . . impl<'tcx> ToPredicate<'tcx> for PolyTypeOutlivesPredicate<'tcx> { 587 ( 0.00%) fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { 1,174 ( 0.00%) self.map_bound(PredicateKind::TypeOutlives).to_predicate(tcx) 1,174 ( 0.00%) } . } . . impl<'tcx> ToPredicate<'tcx> for PolyProjectionPredicate<'tcx> { 88,007 ( 0.00%) fn to_predicate(self, tcx: TyCtxt<'tcx>) -> Predicate<'tcx> { 440,035 ( 0.00%) self.map_bound(PredicateKind::Projection).to_predicate(tcx) 176,014 ( 0.00%) } . } . . impl<'tcx> Predicate<'tcx> { 12,344,110 ( 0.01%) pub fn to_opt_poly_trait_pred(self) -> Option> { . let predicate = self.kind(); 37,032,330 ( 0.03%) match predicate.skip_binder() { 25,938,775 ( 0.02%) PredicateKind::Trait(t) => Some(predicate.rebind(t)), . PredicateKind::Projection(..) . | PredicateKind::Subtype(..) . | PredicateKind::Coerce(..) . | PredicateKind::RegionOutlives(..) . | PredicateKind::WellFormed(..) . | PredicateKind::ObjectSafe(..) . | PredicateKind::ClosureKind(..) . | PredicateKind::TypeOutlives(..) . | PredicateKind::ConstEvaluatable(..) . | PredicateKind::ConstEquate(..) 984,300 ( 0.00%) | PredicateKind::TypeWellFormedFromEnv(..) => None, . } 12,344,110 ( 0.01%) } . 7,720,784 ( 0.01%) pub fn to_opt_type_outlives(self) -> Option> { . let predicate = self.kind(); 15,441,568 ( 0.01%) match predicate.skip_binder() { 1,350,657 ( 0.00%) PredicateKind::TypeOutlives(data) => Some(predicate.rebind(data)), . PredicateKind::Trait(..) . | PredicateKind::Projection(..) . | PredicateKind::Subtype(..) . | PredicateKind::Coerce(..) . | PredicateKind::RegionOutlives(..) . | PredicateKind::WellFormed(..) . | PredicateKind::ObjectSafe(..) . | PredicateKind::ClosureKind(..) . | PredicateKind::ConstEvaluatable(..) . | PredicateKind::ConstEquate(..) 7,270,565 ( 0.01%) | PredicateKind::TypeWellFormedFromEnv(..) => None, . } 7,720,784 ( 0.01%) } . } . . /// Represents the bounds declared on a particular set of type . /// parameters. Should eventually be generalized into a flag list of . /// where-clauses. You can obtain an `InstantiatedPredicates` list from a . /// `GenericPredicates` by using the `instantiate` method. Note that this method . /// reflects an important semantic invariant of `InstantiatedPredicates`: while . /// the `GenericPredicates` are expressed in terms of the bound type -- line 1005 ---------------------------------------- -- line 1011 ---------------------------------------- . /// Example: . /// . /// struct Foo> { ... } . /// . /// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like . /// `[[], [U:Bar]]`. Now if there were some particular reference . /// like `Foo`, then the `InstantiatedPredicates` would be `[[], . /// [usize:Bar]]`. 934,720 ( 0.00%) #[derive(Clone, Debug, TypeFoldable)] . pub struct InstantiatedPredicates<'tcx> { . pub predicates: Vec>, . pub spans: Vec, . } . . impl<'tcx> InstantiatedPredicates<'tcx> { 1,863 ( 0.00%) pub fn empty() -> InstantiatedPredicates<'tcx> { 721,706 ( 0.00%) InstantiatedPredicates { predicates: vec![], spans: vec![] } 1,863 ( 0.00%) } . . pub fn is_empty(&self) -> bool { . self.predicates.is_empty() 1,190 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable, TypeFoldable)] . pub struct OpaqueTypeKey<'tcx> { . pub def_id: DefId, . pub substs: SubstsRef<'tcx>, . } . -- line 1040 ---------------------------------------- -- line 1091 ---------------------------------------- . /// ``` . /// for<'a> fn(&'a u32) . /// ``` . /// . /// Once we "enter" into this `for<'a>` quantifier, we are in a . /// new universe that extends `U` -- in this new universe, we can . /// name the region `'a`, but that region was not nameable from . /// `U` because it was not in scope there. 10,887,723 ( 0.01%) pub fn next_universe(self) -> UniverseIndex { . UniverseIndex::from_u32(self.private.checked_add(1).unwrap()) 32,663,169 ( 0.03%) } . . /// Returns `true` if `self` can name a name from `other` -- in other words, . /// if the set of names in `self` is a superset of those in . /// `other` (`self >= other`). . pub fn can_name(self, other: UniverseIndex) -> bool { 463,482 ( 0.00%) self.private >= other.private 231,741 ( 0.00%) } . . /// Returns `true` if `self` cannot name some names from `other` -- in other . /// words, if the set of names in `self` is a strict subset of . /// those in `other` (`self < other`). . pub fn cannot_name(self, other: UniverseIndex) -> bool { 1,084 ( 0.00%) self.private < other.private 542 ( 0.00%) } . } . . /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are . /// identified by both a universe, as well as a name residing within that universe. Distinct bound . /// regions/types/consts within the same universe simply have an unknown relationship to one . /// another. . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)] . pub struct Placeholder { 15,125 ( 0.00%) pub universe: UniverseIndex, 8,434 ( 0.00%) pub name: T, . } . . impl<'a, T> HashStable> for Placeholder . where . T: HashStable>, . { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . self.universe.hash_stable(hcx, hasher); -- line 1133 ---------------------------------------- -- line 1194 ---------------------------------------- . /// aren't allowed to call that query: it is equal to `type_of(const_param)` which is . /// trivial to compute. . /// . /// If we now want to use that constant in a place which potentionally needs its type . /// we also pass the type of its `const_param`. This is the point of `WithOptConstParam`, . /// except that instead of a `Ty` we bundle the `DefId` of the const parameter. . /// Meaning that we need to use `type_of(const_param_did)` if `const_param_did` is `Some` . /// to get the type of `did`. 101,964 ( 0.00%) #[derive(Copy, Clone, Debug, TypeFoldable, Lift, TyEncodable, TyDecodable)] . #[derive(PartialEq, Eq, PartialOrd, Ord)] . #[derive(Hash, HashStable)] . pub struct WithOptConstParam { 10,173,809 ( 0.01%) pub did: T, . /// The `DefId` of the corresponding generic parameter in case `did` is . /// a const argument. . /// . /// Note that even if `did` is a const argument, this may still be `None`. . /// All queries taking `WithOptConstParam` start by calling `tcx.opt_const_param_of(def.did)` . /// to potentially update `param_did` in the case it is `None`. 110,685,219 ( 0.10%) pub const_param_did: Option, . } . . impl WithOptConstParam { . /// Creates a new `WithOptConstParam` setting `const_param_did` to `None`. . #[inline(always)] . pub fn unknown(did: T) -> WithOptConstParam { . WithOptConstParam { did, const_param_did: None } 174,502 ( 0.00%) } . } . . impl WithOptConstParam { . /// Returns `Some((did, param_did))` if `def_id` is a const argument, . /// `None` otherwise. . #[inline(always)] . pub fn try_lookup(did: LocalDefId, tcx: TyCtxt<'_>) -> Option<(LocalDefId, DefId)> { . tcx.opt_const_param_of(did).map(|param_did| (did, param_did)) . } . . /// In case `self` is unknown but `self.did` is a const argument, this returns . /// a `WithOptConstParam` with the correct `const_param_did`. . #[inline(always)] . pub fn try_upgrade(self, tcx: TyCtxt<'_>) -> Option> { 41,150 ( 0.00%) if self.const_param_did.is_none() { 33,470 ( 0.00%) if let const_param_did @ Some(_) = tcx.opt_const_param_of(self.did) { . return Some(WithOptConstParam { did: self.did, const_param_did }); . } . } . . None 13,041 ( 0.00%) } . . pub fn to_global(self) -> WithOptConstParam { . WithOptConstParam { did: self.did.to_def_id(), const_param_did: self.const_param_did } 31,961 ( 0.00%) } . 21,348 ( 0.00%) pub fn def_id_for_type_of(self) -> DefId { 58,443 ( 0.00%) if let Some(did) = self.const_param_did { did } else { self.did.to_def_id() } 5,337 ( 0.00%) } . } . . impl WithOptConstParam { 19,510 ( 0.00%) pub fn as_local(self) -> Option> { . self.did . .as_local() . .map(|did| WithOptConstParam { did, const_param_did: self.const_param_did }) 19,510 ( 0.00%) } . . pub fn as_const_arg(self) -> Option<(LocalDefId, DefId)> { 20,118,003 ( 0.02%) if let Some(param_did) = self.const_param_did { 30,115,102 ( 0.03%) if let Some(did) = self.did.as_local() { . return Some((did, param_did)); . } . } . . None 103,584 ( 0.00%) } . . pub fn is_local(self) -> bool { . self.did.is_local() . } . 3,671 ( 0.00%) pub fn def_id_for_type_of(self) -> DefId { . self.const_param_did.unwrap_or(self.did) 3,671 ( 0.00%) } . } . . /// When type checking, we use the `ParamEnv` to track . /// details about the set of where-clauses that are in scope at this . /// particular point. . #[derive(Copy, Clone, Hash, PartialEq, Eq)] . pub struct ParamEnv<'tcx> { . /// This packs both caller bounds and the reveal enum into one pointer. -- line 1285 ---------------------------------------- -- line 1302 ---------------------------------------- . reveal: traits::Reveal, . constness: hir::Constness, . } . . unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag { . const BITS: usize = 2; . #[inline] . fn into_usize(self) -> usize { 10,946,767 ( 0.01%) match self { . Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst } => 0, . Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst } => 1, . Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const } => 2, . Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3, . } . } . #[inline] . unsafe fn from_usize(ptr: usize) -> Self { 100,487,017 ( 0.09%) match ptr { . 0 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::NotConst }, . 1 => Self { reveal: traits::Reveal::All, constness: hir::Constness::NotConst }, . 2 => Self { reveal: traits::Reveal::UserFacing, constness: hir::Constness::Const }, . 3 => Self { reveal: traits::Reveal::All, constness: hir::Constness::Const }, . _ => std::hint::unreachable_unchecked(), . } . } . } -- line 1327 ---------------------------------------- -- line 1405 ---------------------------------------- . pub fn new( . caller_bounds: &'tcx List>, . reveal: Reveal, . constness: hir::Constness, . ) -> Self { . ty::ParamEnv { packed: CopyTaggedPtr::new(caller_bounds, ParamTag { reveal, constness }) } . } . 558 ( 0.00%) pub fn with_user_facing(mut self) -> Self { . self.packed.set_tag(ParamTag { reveal: Reveal::UserFacing, ..self.packed.tag() }); . self 558 ( 0.00%) } . . #[inline] . pub fn with_constness(mut self, constness: hir::Constness) -> Self { . self.packed.set_tag(ParamTag { constness, ..self.packed.tag() }); . self . } . . #[inline] -- line 1424 ---------------------------------------- -- line 1430 ---------------------------------------- . #[inline] . pub fn without_const(mut self) -> Self { . self.packed.set_tag(ParamTag { constness: hir::Constness::NotConst, ..self.packed.tag() }); . self . } . . #[inline] . pub fn remap_constness_with(&mut self, mut constness: ty::BoundConstness) { 274,090 ( 0.00%) *self = self.with_constness(constness.and(self.constness())) . } . . /// Returns a new parameter environment with the same clauses, but . /// which "reveals" the true results of projections in all cases . /// (even for associated types that are specializable). This is . /// the desired behavior during codegen and certain other special . /// contexts; normally though we want to use `Reveal::UserFacing`, . /// which is the default. . /// All opaque types in the caller_bounds of the `ParamEnv` . /// will be normalized to their underlying types. . /// See PR #65989 and issue #65918 for more details 80,436,848 ( 0.07%) pub fn with_reveal_all_normalized(self, tcx: TyCtxt<'tcx>) -> Self { . if self.packed.tag().reveal == traits::Reveal::All { . return self; . } . . ParamEnv::new( . tcx.normalize_opaque_types(self.caller_bounds()), . Reveal::All, . self.constness(), . ) 90,491,454 ( 0.08%) } . . /// Returns this same environment but with no caller bounds. . #[inline] . pub fn without_caller_bounds(self) -> Self { . Self::new(List::empty(), self.reveal(), self.constness()) . } . . /// Creates a suitable environment in which to perform trait -- line 1468 ---------------------------------------- -- line 1472 ---------------------------------------- . /// pair it with the empty environment. This improves caching and is generally . /// invisible. . /// . /// N.B., we preserve the environment when type-checking because it . /// is possible for the user to have wacky where-clauses like . /// `where Box: Copy`, which are clearly never . /// satisfiable. We generally want to behave as if they were true, . /// although the surrounding function is never reachable. 101,791,809 ( 0.09%) pub fn and>(self, value: T) -> ParamEnvAnd<'tcx, T> { . match self.reveal() { . Reveal::UserFacing => ParamEnvAnd { param_env: self, value }, . . Reveal::All => { 30,345,125 ( 0.03%) if value.is_global() { 112 ( 0.00%) ParamEnvAnd { param_env: self.without_caller_bounds(), value } . } else { . ParamEnvAnd { param_env: self, value } . } . } . } 91,700,275 ( 0.08%) } . } . . // FIXME(ecstaticmorse): Audit all occurrences of `without_const().to_predicate(tcx)` to ensure that . // the constness of trait bounds is being propagated correctly. . impl<'tcx> PolyTraitRef<'tcx> { . #[inline] . pub fn with_constness(self, constness: BoundConstness) -> PolyTraitPredicate<'tcx> { 336,590 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness, . polarity: ty::ImplPolarity::Positive, . }) . } . #[inline] . pub fn without_const(self) -> PolyTraitPredicate<'tcx> { . self.with_constness(BoundConstness::NotConst) . } . } . 10,061,206 ( 0.01%) #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable)] . pub struct ParamEnvAnd<'tcx, T> { 507,004 ( 0.00%) pub param_env: ParamEnv<'tcx>, 29,044,184 ( 0.02%) pub value: T, . } . . impl<'tcx, T> ParamEnvAnd<'tcx, T> { . pub fn into_parts(self) -> (ParamEnv<'tcx>, T) { . (self.param_env, self.value) . } . . #[inline] . pub fn without_const(mut self) -> Self { . self.param_env = self.param_env.without_const(); 50,193,086 ( 0.04%) self . } . } . . impl<'a, 'tcx, T> HashStable> for ParamEnvAnd<'tcx, T> . where . T: HashStable>, . { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { -- line 1534 ---------------------------------------- -- line 1542 ---------------------------------------- . #[derive(Copy, Clone, Debug, HashStable)] . pub struct Destructor { . /// The `DefId` of the destructor method . pub did: DefId, . /// The constness of the destructor method . pub constness: hir::Constness, . } . 9,401 ( 0.00%) bitflags! { 31,293 ( 0.00%) #[derive(HashStable, TyEncodable, TyDecodable)] . pub struct VariantFlags: u32 { . const NO_VARIANT_FLAGS = 0; . /// Indicates whether the field list of this variant is `#[non_exhaustive]`. . const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0; . /// Indicates whether this variant was obtained as part of recovering from . /// a syntactic error. May be incomplete or bogus. . const IS_RECOVERED = 1 << 1; . } . } . . /// Definition of a variant -- a struct's fields or an enum variant. 197,515 ( 0.00%) #[derive(Debug, HashStable, TyEncodable, TyDecodable)] . pub struct VariantDef { . /// `DefId` that identifies the variant itself. . /// If this variant belongs to a struct or union, then this is a copy of its `DefId`. . pub def_id: DefId, . /// `DefId` that identifies the variant's constructor. . /// If this variant is a struct variant, then this is `None`. . pub ctor_def_id: Option, . /// Variant or struct name. -- line 1571 ---------------------------------------- -- line 1592 ---------------------------------------- . /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that . /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having . /// to go through the redirect of checking the ctor's attributes - but compiling a small crate . /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any . /// built-in trait), and we do not want to load attributes twice. . /// . /// If someone speeds up attribute loading to not be a performance concern, they can . /// remove this hack and use the constructor `DefId` everywhere. 1,184 ( 0.00%) pub fn new( . name: Symbol, . variant_did: Option, . ctor_def_id: Option, . discr: VariantDiscr, . fields: Vec, . ctor_kind: CtorKind, . adt_kind: AdtKind, . parent_did: DefId, -- line 1608 ---------------------------------------- -- line 1611 ---------------------------------------- . ) -> Self { . debug!( . "VariantDef::new(name = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?}, . fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})", . name, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did, . ); . . let mut flags = VariantFlags::NO_VARIANT_FLAGS; 148 ( 0.00%) if is_field_list_non_exhaustive { . flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE; . } . 444 ( 0.00%) if recovered { . flags |= VariantFlags::IS_RECOVERED; . } . 1,332 ( 0.00%) VariantDef { . def_id: variant_did.unwrap_or(parent_did), . ctor_def_id, . name, . discr, 592 ( 0.00%) fields, . ctor_kind, . flags, . } 592 ( 0.00%) } . . /// Is this field list non-exhaustive? . #[inline] . pub fn is_field_list_non_exhaustive(&self) -> bool { . self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE) . } . . /// Was this variant obtained as part of recovering from a syntactic error? . #[inline] . pub fn is_recovered(&self) -> bool { . self.flags.intersects(VariantFlags::IS_RECOVERED) . } . . /// Computes the `Ident` of this variant by looking up the `Span` 2,933 ( 0.00%) pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident { 1,676 ( 0.00%) Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap()) 3,771 ( 0.00%) } . } . 114,570 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)] . pub enum VariantDiscr { . /// Explicit value for this variant, i.e., `X = 123`. . /// The `DefId` corresponds to the embedded constant. . Explicit(DefId), . . /// The previous variant's discriminant plus one. . /// For efficiency reasons, the distance from the . /// last `Explicit` discriminant is being stored, . /// or `0` for the first variant, if it has none. . Relative(u32), . } . 301,766 ( 0.00%) #[derive(Debug, HashStable, TyEncodable, TyDecodable)] . pub struct FieldDef { . pub did: DefId, . pub name: Symbol, . pub vis: Visibility, . } . 20,474 ( 0.00%) bitflags! { . #[derive(TyEncodable, TyDecodable, Default, HashStable)] . pub struct ReprFlags: u8 { . const IS_C = 1 << 0; . const IS_SIMD = 1 << 1; . const IS_TRANSPARENT = 1 << 2; . // Internal only for now. If true, don't reorder fields. . const IS_LINEAR = 1 << 3; . // If true, don't expose any niche to type's context. -- line 1684 ---------------------------------------- -- line 1689 ---------------------------------------- . // Any of these flags being set prevent field reordering optimisation. . const IS_UNOPTIMISABLE = ReprFlags::IS_C.bits . | ReprFlags::IS_SIMD.bits . | ReprFlags::IS_LINEAR.bits; . } . } . . /// Represents the repr options provided by the user, 180,650 ( 0.00%) #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Default, HashStable)] . pub struct ReprOptions { . pub int: Option, . pub align: Option, . pub pack: Option, . pub flags: ReprFlags, . /// The seed to be used for randomizing a type's layout . /// . /// Note: This could technically be a `[u8; 16]` (a `u128`) which would -- line 1705 ---------------------------------------- -- line 1706 ---------------------------------------- . /// be the "most accurate" hash as it'd encompass the item and crate . /// hash without loss, but it does pay the price of being larger. . /// Everything's a tradeoff, a `u64` seed should be sufficient for our . /// purposes (primarily `-Z randomize-layout`) . pub field_shuffle_seed: u64, . } . . impl ReprOptions { 1,079 ( 0.00%) pub fn new(tcx: TyCtxt<'_>, did: DefId) -> ReprOptions { . let mut flags = ReprFlags::empty(); . let mut size = None; . let mut max_align: Option = None; . let mut min_pack: Option = None; . . // Generate a deterministically-derived seed from the item's path hash . // to allow for cross-crate compilation to actually work . let mut field_shuffle_seed = tcx.def_path_hash(did).0.to_smaller_hash(); . . // If the user defined a custom seed for layout randomization, xor the item's . // path hash with the user defined seed, this will allowing determinism while . // still allowing users to further randomize layout generation for e.g. fuzzing 249 ( 0.00%) if let Some(user_seed) = tcx.sess.opts.debugging_opts.layout_seed { . field_shuffle_seed ^= user_seed; . } . 332 ( 0.00%) for attr in tcx.get_attrs(did).iter() { 2,167 ( 0.00%) for r in attr::find_repr_attrs(&tcx.sess, attr) { . flags.insert(match r { . attr::ReprC => ReprFlags::IS_C, . attr::ReprPacked(pack) => { . let pack = Align::from_bytes(pack as u64).unwrap(); . min_pack = Some(if let Some(min_pack) = min_pack { . min_pack.min(pack) . } else { . pack -- line 1740 ---------------------------------------- -- line 1753 ---------------------------------------- . ReprFlags::empty() . } . }); . } . } . . // If `-Z randomize-layout` was enabled for the type definition then we can . // consider performing layout randomization 664 ( 0.00%) if tcx.sess.opts.debugging_opts.randomize_layout { . flags.insert(ReprFlags::RANDOMIZE_LAYOUT); . } . . // This is here instead of layout because the choice must make it into metadata. 498 ( 0.00%) if !tcx.consider_optimizing(|| format!("Reorder fields of {:?}", tcx.def_path_str(did))) { . flags.insert(ReprFlags::IS_LINEAR); . } . 166 ( 0.00%) Self { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed } 2,324 ( 0.00%) } . . #[inline] . pub fn simd(&self) -> bool { . self.flags.contains(ReprFlags::IS_SIMD) . } . . #[inline] . pub fn c(&self) -> bool { -- line 1779 ---------------------------------------- -- line 1798 ---------------------------------------- . #[inline] . pub fn hide_niche(&self) -> bool { . self.flags.contains(ReprFlags::HIDE_NICHE) . } . . /// Returns the discriminant type, given these `repr` options. . /// This must only be called on enums! . pub fn discr_type(&self) -> attr::IntType { 9,916 ( 0.00%) self.int.unwrap_or(attr::SignedInt(ast::IntTy::Isize)) 5,779 ( 0.00%) } . . /// Returns `true` if this `#[repr()]` should inhabit "smart enum . /// layout" optimizations, such as representing `Foo<&T>` as a . /// single pointer. . pub fn inhibit_enum_layout_opt(&self) -> bool { 1,585 ( 0.00%) self.c() || self.int.is_some() . } . . /// Returns `true` if this `#[repr()]` should inhibit struct field reordering . /// optimizations, such as with `repr(C)`, `repr(packed(1))`, or `repr()`. . pub fn inhibit_struct_field_reordering_opt(&self) -> bool { 5,215 ( 0.00%) if let Some(pack) = self.pack { . if pack.bytes() == 1 { . return true; . } . } . 10,548 ( 0.00%) self.flags.intersects(ReprFlags::IS_UNOPTIMISABLE) || self.int.is_some() . } . . /// Returns `true` if this type is valid for reordering and `-Z randomize-layout` . /// was enabled for its declaration crate . pub fn can_randomize_type_layout(&self) -> bool { 2,578 ( 0.00%) !self.inhibit_struct_field_reordering_opt() . && self.flags.contains(ReprFlags::RANDOMIZE_LAYOUT) . } . . /// Returns `true` if this `#[repr()]` should inhibit union ABI optimisations. . pub fn inhibit_union_abi_opt(&self) -> bool { . self.c() . } . } . . impl<'tcx> FieldDef { . /// Returns the type of this field. The resulting type is not normalized. The `subst` is . /// typically obtained via the second field of [`TyKind::Adt`]. 308,336 ( 0.00%) pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> { 88,096 ( 0.00%) tcx.type_of(self.did).subst(tcx, subst) 352,384 ( 0.00%) } . . /// Computes the `Ident` of this variant by looking up the `Span` 94,990 ( 0.00%) pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident { 54,280 ( 0.00%) Ident::new(self.name, tcx.def_ident_span(self.did).unwrap()) 122,130 ( 0.00%) } . } . . pub type Attributes<'tcx> = &'tcx [ast::Attribute]; . . #[derive(Debug, PartialEq, Eq)] . pub enum ImplOverlapKind { . /// These impls are always allowed to overlap. . Permitted { -- line 1859 ---------------------------------------- -- line 1891 ---------------------------------------- . /// marker traits. . /// 4. Neither of the impls can have any where-clauses. . /// . /// Once `traitobject` 0.1.0 is no longer an active concern, this hack can be removed. . Issue33140, . } . . impl<'tcx> TyCtxt<'tcx> { 395,328 ( 0.00%) pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> { 98,832 ( 0.00%) self.typeck(self.hir().body_owner_def_id(body)) 395,328 ( 0.00%) } . 56 ( 0.00%) pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator { . self.associated_items(id) . .in_definition_order() 96 ( 0.00%) .filter(|item| item.kind == AssocKind::Fn && item.defaultness.has_value()) 64 ( 0.00%) } . . fn item_name_from_hir(self, def_id: DefId) -> Option { . self.hir().get_if_local(def_id).and_then(|node| node.ident()) . } . 567 ( 0.00%) fn item_name_from_def_id(self, def_id: DefId) -> Option { 63 ( 0.00%) if def_id.index == CRATE_DEF_INDEX { . Some(self.crate_name(def_id.krate)) . } else { 189 ( 0.00%) let def_key = self.def_key(def_id); 315 ( 0.00%) match def_key.disambiguated_data.data { . // The name of a constructor is that of its parent. . rustc_hir::definitions::DefPathData::Ctor => self.item_name_from_def_id(DefId { . krate: def_id.krate, . index: def_key.parent.unwrap(), . }), 126 ( 0.00%) _ => def_key.disambiguated_data.data.get_opt_name(), . } . } 504 ( 0.00%) } . . /// Look up the name of an item across crates. This does not look at HIR. . /// . /// When possible, this function should be used for cross-crate lookups over . /// [`opt_item_name`] to avoid invalidating the incremental cache. If you . /// need to handle items without a name, or HIR items that will not be . /// serialized cross-crate, or if you need the span of the item, use . /// [`opt_item_name`] instead. . /// . /// [`opt_item_name`]: Self::opt_item_name 441 ( 0.00%) pub fn item_name(self, id: DefId) -> Symbol { . // Look at cross-crate items first to avoid invalidating the incremental cache . // unless we have to. 63 ( 0.00%) self.item_name_from_def_id(id).unwrap_or_else(|| { . bug!("item_name: no name for {:?}", self.def_path(id)); . }) 315 ( 0.00%) } . . /// Look up the name and span of an item or [`Node`]. . /// . /// See [`item_name`][Self::item_name] for more information. . pub fn opt_item_name(self, def_id: DefId) -> Option { . // Look at the HIR first so the span will be correct if this is a local item. . self.item_name_from_hir(def_id) . .or_else(|| self.item_name_from_def_id(def_id).map(Ident::with_dummy_span)) . } . 4,087,190 ( 0.00%) pub fn opt_associated_item(self, def_id: DefId) -> Option<&'tcx AssocItem> { 1,634,876 ( 0.00%) if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) { . Some(self.associated_item(def_id)) . } else { . None . } 3,678,471 ( 0.00%) } . 22,413 ( 0.00%) pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize { . typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field") 44,826 ( 0.00%) } . . pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option { . variant . .fields . .iter() . .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id)) . } . . /// Returns `true` if the impls are the same polarity and the trait either . /// has no items or is annotated `#[marker]` and prevents item overrides. 63,571,120 ( 0.05%) pub fn impls_are_allowed_to_overlap( . self, . def_id1: DefId, . def_id2: DefId, . ) -> Option { . // If either trait impl references an error, they're allowed to overlap, . // as one of them essentially doesn't exist. . if self.impl_trait_ref(def_id1).map_or(false, |tr| tr.references_error()) 12,714,224 ( 0.01%) || self.impl_trait_ref(def_id2).map_or(false, |tr| tr.references_error()) . { . return Some(ImplOverlapKind::Permitted { marker: false }); . } . 63,571,120 ( 0.05%) match (self.impl_polarity(def_id1), self.impl_polarity(def_id2)) { . (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => { . // `#[rustc_reservation_impl]` impls don't overlap with anything . debug!( . "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (reservations)", . def_id1, def_id2 . ); . return Some(ImplOverlapKind::Permitted { marker: false }); . } -- line 1997 ---------------------------------------- -- line 2004 ---------------------------------------- . ); . return None; . } . (ImplPolarity::Positive, ImplPolarity::Positive) . | (ImplPolarity::Negative, ImplPolarity::Negative) => {} . }; . . let is_marker_overlap = { 63,571,120 ( 0.05%) let is_marker_impl = |def_id: DefId| -> bool { 19,071,336 ( 0.02%) let trait_ref = self.impl_trait_ref(def_id); 19,071,336 ( 0.02%) trait_ref.map_or(false, |tr| self.trait_def(tr.def_id).is_marker) 50,856,896 ( 0.04%) }; 25,428,448 ( 0.02%) is_marker_impl(def_id1) && is_marker_impl(def_id2) . }; . . if is_marker_overlap { . debug!( . "impls_are_allowed_to_overlap({:?}, {:?}) = Some(Permitted) (marker overlap)", . def_id1, def_id2 . ); . Some(ImplOverlapKind::Permitted { marker: true }) . } else { 25,428,448 ( 0.02%) if let Some(self_ty1) = self.issue33140_self_ty(def_id1) { . if let Some(self_ty2) = self.issue33140_self_ty(def_id2) { . if self_ty1 == self_ty2 { . debug!( . "impls_are_allowed_to_overlap({:?}, {:?}) - issue #33140 HACK", . def_id1, def_id2 . ); . return Some(ImplOverlapKind::Issue33140); . } else { -- line 2034 ---------------------------------------- -- line 2038 ---------------------------------------- . ); . } . } . } . . debug!("impls_are_allowed_to_overlap({:?}, {:?}) = None", def_id1, def_id2); . None . } 50,856,896 ( 0.04%) } . . /// Returns `ty::VariantDef` if `res` refers to a struct, . /// or variant or their constructors, panics otherwise. 602 ( 0.00%) pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef { 1,032 ( 0.00%) match res { . Res::Def(DefKind::Variant, did) => { . let enum_did = self.parent(did).unwrap(); . self.adt_def(enum_did).variant_with_id(did) . } . Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(), . Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => { . let variant_did = self.parent(variant_ctor_did).unwrap(); . let enum_did = self.parent(variant_did).unwrap(); -- line 2059 ---------------------------------------- -- line 2060 ---------------------------------------- . self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did) . } . Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => { . let struct_did = self.parent(ctor_did).expect("struct ctor has no parent"); . self.adt_def(struct_did).non_enum_variant() . } . _ => bug!("expect_variant_res used with unexpected res {:?}", res), . } 688 ( 0.00%) } . . /// Returns the possibly-auto-generated MIR of a `(DefId, Subst)` pair. 304 ( 0.00%) pub fn instance_mir(self, instance: ty::InstanceDef<'tcx>) -> &'tcx Body<'tcx> { 76 ( 0.00%) match instance { 330 ( 0.00%) ty::InstanceDef::Item(def) => match self.def_kind(def.did) { . DefKind::Const . | DefKind::Static . | DefKind::AssocConst . | DefKind::Ctor(..) . | DefKind::AnonConst . | DefKind::InlineConst => self.mir_for_ctfe_opt_const_arg(def), . // If the caller wants `mir_for_ctfe` of a function they should not be using . // `instance_mir`, so we'll assume const fn also wants the optimized version. . _ => { 33 ( 0.00%) assert_eq!(def.const_param_did, None); . self.optimized_mir(def.did) . } . }, . ty::InstanceDef::VtableShim(..) . | ty::InstanceDef::ReifyShim(..) . | ty::InstanceDef::Intrinsic(..) . | ty::InstanceDef::FnPtrShim(..) . | ty::InstanceDef::Virtual(..) . | ty::InstanceDef::ClosureOnceShim { .. } . | ty::InstanceDef::DropGlue(..) . | ty::InstanceDef::CloneShim(..) => self.mir_shims(instance), . } 342 ( 0.00%) } . . /// Gets the attributes of a definition. 3,402,610 ( 0.00%) pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> { 1,020,783 ( 0.00%) if let Some(did) = did.as_local() { 965,205 ( 0.00%) self.hir().attrs(self.hir().local_def_id_to_hir_id(did)) . } else { . self.item_attrs(did) . } 2,722,088 ( 0.00%) } . . /// Determines whether an item is annotated with an attribute. 270,264 ( 0.00%) pub fn has_attr(self, did: DefId, attr: Symbol) -> bool { 803,385 ( 0.00%) self.sess.contains_name(&self.get_attrs(did), attr) . } . . /// Determines whether an item is annotated with `doc(hidden)`. 9,366 ( 0.00%) pub fn is_doc_hidden(self, did: DefId) -> bool { 1,338 ( 0.00%) self.get_attrs(did) . .iter() 1,240 ( 0.00%) .filter_map(|attr| if attr.has_name(sym::doc) { attr.meta_item_list() } else { None }) . .any(|items| items.iter().any(|item| item.has_name(sym::hidden))) 10,704 ( 0.00%) } . . /// Returns `true` if this is an `auto trait`. 150,640 ( 0.00%) pub fn trait_is_auto(self, trait_def_id: DefId) -> bool { 21,520 ( 0.00%) self.trait_def(trait_def_id).has_auto_impl 172,160 ( 0.00%) } . . /// Returns layout of a generator. Layout might be unavailable if the . /// generator is tainted by errors. . pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> { . self.optimized_mir(def_id).generator_layout() . } . . /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements. . /// If it implements no trait, returns `None`. 389,249 ( 0.00%) pub fn trait_id_of_impl(self, def_id: DefId) -> Option { . self.impl_trait_ref(def_id).map(|tr| tr.def_id) 500,463 ( 0.00%) } . . /// If the given defid describes a method belonging to an impl, returns the . /// `DefId` of the impl that the method belongs to; otherwise, returns `None`. 4,804 ( 0.00%) pub fn impl_of_method(self, def_id: DefId) -> Option { 19,210 ( 0.00%) self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container { . TraitContainer(_) => None, . ImplContainer(def_id) => Some(def_id), . }) 9,608 ( 0.00%) } . . /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err` . /// with the name of the crate containing the impl. . pub fn span_of_impl(self, impl_did: DefId) -> Result { . if let Some(impl_did) = impl_did.as_local() { . Ok(self.def_span(impl_did)) . } else { . Err(self.crate_name(impl_did.krate)) . } . } . . /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with . /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed . /// definition's parent/scope to perform comparison. 296,880 ( 0.00%) pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool { . // We could use `Ident::eq` here, but we deliberately don't. The name . // comparison fails frequently, and we want to avoid the expensive . // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible. 37,110 ( 0.00%) use_name.name == def_name.name 111,330 ( 0.00%) && use_name . .span . .ctxt() . .hygienic_eq(def_name.span.ctxt(), self.expn_that_defined(def_parent_def_id)) 296,880 ( 0.00%) } . 47,988 ( 0.00%) pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident { 10,664 ( 0.00%) ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope)); 10,664 ( 0.00%) ident 42,656 ( 0.00%) } . 325,386 ( 0.00%) pub fn adjust_ident_and_get_scope( . self, . mut ident: Ident, . scope: DefId, . block: hir::HirId, . ) -> (Ident, DefId) { 36,154 ( 0.00%) let scope = ident . .span . .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope)) 658 ( 0.00%) .and_then(|actual_expansion| actual_expansion.expn_data().parent_module) 143,300 ( 0.00%) .unwrap_or_else(|| self.parent_module(block).to_def_id()); 216,924 ( 0.00%) (ident, scope) 325,386 ( 0.00%) } . 4,452 ( 0.00%) pub fn is_object_safe(self, key: DefId) -> bool { . self.object_safety_violations(key).is_empty() 5,088 ( 0.00%) } . } . . /// Yields the parent function's `LocalDefId` if `def_id` is an `impl Trait` definition. 51,870 ( 0.00%) pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option { 51,870 ( 0.00%) let def_id = def_id.as_local()?; 67,088 ( 0.00%) if let Node::Item(item) = tcx.hir().get_by_def_id(def_id) { 12,720 ( 0.00%) if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind { . return match opaque_ty.origin { . hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent) => { . Some(parent) . } . hir::OpaqueTyOrigin::TyAlias => None, . }; . } . } . None 69,160 ( 0.00%) } . . pub fn int_ty(ity: ast::IntTy) -> IntTy { . match ity { . ast::IntTy::Isize => IntTy::Isize, . ast::IntTy::I8 => IntTy::I8, . ast::IntTy::I16 => IntTy::I16, . ast::IntTy::I32 => IntTy::I32, . ast::IntTy::I64 => IntTy::I64, -- line 2216 ---------------------------------------- -- line 2224 ---------------------------------------- . ast::UintTy::U8 => UintTy::U8, . ast::UintTy::U16 => UintTy::U16, . ast::UintTy::U32 => UintTy::U32, . ast::UintTy::U64 => UintTy::U64, . ast::UintTy::U128 => UintTy::U128, . } . } . 326 ( 0.00%) pub fn float_ty(fty: ast::FloatTy) -> FloatTy { . match fty { . ast::FloatTy::F32 => FloatTy::F32, . ast::FloatTy::F64 => FloatTy::F64, . } 326 ( 0.00%) } . 4,652 ( 0.00%) pub fn ast_int_ty(ity: IntTy) -> ast::IntTy { . match ity { . IntTy::Isize => ast::IntTy::Isize, . IntTy::I8 => ast::IntTy::I8, . IntTy::I16 => ast::IntTy::I16, . IntTy::I32 => ast::IntTy::I32, . IntTy::I64 => ast::IntTy::I64, . IntTy::I128 => ast::IntTy::I128, . } 4,652 ( 0.00%) } . . pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy { . match uty { . UintTy::Usize => ast::UintTy::Usize, . UintTy::U8 => ast::UintTy::U8, . UintTy::U16 => ast::UintTy::U16, . UintTy::U32 => ast::UintTy::U32, . UintTy::U64 => ast::UintTy::U64, -- line 2256 ---------------------------------------- -- line 2262 ---------------------------------------- . closure::provide(providers); . context::provide(providers); . erase_regions::provide(providers); . layout::provide(providers); . util::provide(providers); . print::provide(providers); . super::util::bug::provide(providers); . super::middle::provide(providers); 8 ( 0.00%) *providers = ty::query::Providers { . trait_impls_of: trait_def::trait_impls_of_provider, . type_uninhabited_from: inhabitedness::type_uninhabited_from, . const_param_default: consts::const_param_default, . vtable_allocation: vtable::vtable_allocation_provider, . ..*providers . }; 1 ( 0.00%) } . . /// A map for the local crate mapping each type to a vector of its . /// inherent impls. This is not meant to be used outside of coherence; . /// rather, you should request the vector for a specific type via . /// `tcx.inherent_impls(def_id)` so as to minimize your dependencies . /// (constructing this map requires touching the entire crate). . #[derive(Clone, Debug, Default, HashStable)] . pub struct CrateInherentImpls { . pub inherent_impls: LocalDefIdMap>, . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)] . pub struct SymbolName<'tcx> { . /// `&str` gives a consistent ordering, which ensures reproducible builds. 119 ( 0.00%) pub name: &'tcx str, . } . . impl<'tcx> SymbolName<'tcx> { 162 ( 0.00%) pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> { . SymbolName { . name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) }, . } 216 ( 0.00%) } . } . . impl<'tcx> fmt::Display for SymbolName<'tcx> { 11 ( 0.00%) fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(&self.name, fmt) . } . } . . impl<'tcx> fmt::Debug for SymbolName<'tcx> { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(&self.name, fmt) . } -- line 2312 ---------------------------------------- 853,729,751 ( 0.73%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/equate.rs -------------------------------------------------------------------------------- Ir -- line 24 ---------------------------------------- . } . . impl<'tcx> TypeRelation<'tcx> for Equate<'_, '_, 'tcx> { . fn tag(&self) -> &'static str { . "Equate" . } . . fn tcx(&self) -> TyCtxt<'tcx> { 24,007,750 ( 0.02%) self.fields.tcx() 10,258,794 ( 0.01%) } . . fn param_env(&self) -> ty::ParamEnv<'tcx> { 19,777,592 ( 0.02%) self.fields.param_env . } . . fn a_is_expected(&self) -> bool { 28,467,714 ( 0.02%) self.a_is_expected . } . 51,366,745 ( 0.04%) fn relate_item_substs( . &mut self, . _item_def_id: DefId, . a_subst: SubstsRef<'tcx>, . b_subst: SubstsRef<'tcx>, . ) -> RelateResult<'tcx, SubstsRef<'tcx>> { . // N.B., once we are equating types, we don't care about . // variance, so don't try to lookup the variance here. This . // also avoids some cycles (e.g., #41849) since looking up . // variance requires computing types which can require . // performing trait matching (which then performs equality . // unification). . 10,273,349 ( 0.01%) relate::relate_substs(self, None, a_subst, b_subst) 61,640,094 ( 0.05%) } . . fn relate_with_variance>( . &mut self, . _: ty::Variance, . _info: ty::VarianceDiagInfo<'tcx>, . a: T, . b: T, . ) -> RelateResult<'tcx, T> { . self.relate(a, b) . } . 113,218,218 ( 0.10%) fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { . debug!("{}.tys({:?}, {:?})", self.tag(), a, b); 12,579,802 ( 0.01%) if a == b { . return Ok(a); . } . 22,788,726 ( 0.02%) let infcx = self.fields.infcx; 22,788,726 ( 0.02%) let a = infcx.inner.borrow_mut().type_variables().replace_if_possible(a); 22,788,726 ( 0.02%) let b = infcx.inner.borrow_mut().type_variables().replace_if_possible(b); . . debug!("{}.tys: replacements ({:?}, {:?})", self.tag(), a, b); . 57,968,218 ( 0.05%) match (a.kind(), b.kind()) { . (&ty::Infer(TyVar(a_id)), &ty::Infer(TyVar(b_id))) => { . infcx.inner.borrow_mut().type_variables().equate(a_id, b_id); . } . 30,654 ( 0.00%) (&ty::Infer(TyVar(a_id)), _) => { 122,616 ( 0.00%) self.fields.instantiate(b, RelationDir::EqTo, a_id, self.a_is_expected)?; . } . 317,234 ( 0.00%) (_, &ty::Infer(TyVar(b_id))) => { 1,586,170 ( 0.00%) self.fields.instantiate(a, RelationDir::EqTo, b_id, self.a_is_expected)?; . } . . _ => { 77,098,217 ( 0.07%) self.fields.infcx.super_combine_tys(self, a, b)?; . } . } . . Ok(a) 113,218,218 ( 0.10%) } . 2,760,939 ( 0.00%) fn regions( . &mut self, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) -> RelateResult<'tcx, ty::Region<'tcx>> { . debug!("{}.regions({:?}, {:?})", self.tag(), a, b); 920,313 ( 0.00%) let origin = Subtype(Box::new(self.fields.trace.clone())); 1,840,626 ( 0.00%) self.fields . .infcx . .inner . .borrow_mut() . .unwrap_region_constraints() 1,840,626 ( 0.00%) .make_eqregion(origin, a, b); 613,542 ( 0.00%) Ok(a) 2,760,939 ( 0.00%) } . 8,120 ( 0.00%) fn consts( . &mut self, . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { 49,614,517 ( 0.04%) self.fields.infcx.super_combine_consts(self, a, b) 4,872 ( 0.00%) } . . fn binders( . &mut self, . a: ty::Binder<'tcx, T>, . b: ty::Binder<'tcx, T>, . ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> . where . T: Relate<'tcx>, -- line 132 ---------------------------------------- 29,677,794 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . . use super::BuiltinImplConditions; . use super::IntercrateAmbiguityCause; . use super::OverflowError; . use super::SelectionCandidate::{self, *}; . use super::{EvaluatedCandidate, SelectionCandidateSet, SelectionContext, TraitObligationStack}; . . impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { 5,346,272 ( 0.00%) #[instrument(level = "debug", skip(self))] 6,682,840 ( 0.01%) pub(super) fn candidate_from_obligation<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . // Watch out for overflow. This intentionally bypasses (and does . // not update) the cache. 1,336,568 ( 0.00%) self.check_recursion_limit(&stack.obligation, &stack.obligation)?; . . // Check the cache. Note that we freshen the trait-ref . // separately rather than using `stack.fresh_trait_ref` -- . // this is because we want the unbound variables to be . // replaced with fresh types starting from index 0. 6,014,556 ( 0.01%) let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate); . debug!(?cache_fresh_trait_pred); . debug_assert!(!stack.obligation.predicate.has_escaping_bound_vars()); . 7,495,121 ( 0.01%) if let Some(c) = 2,004,852 ( 0.00%) self.check_candidate_cache(stack.obligation.param_env, cache_fresh_trait_pred) . { . debug!(candidate = ?c, "CACHE HIT"); . return c; . } . . // If no match, compute result and insert into cache. . // . // FIXME(nikomatsakis) -- this cache is not taking into . // account cycles that may have occurred in forming the . // candidate. I don't know of any specific problems that . // result but it seems awfully suspicious. 1,369,890 ( 0.00%) let (candidate, dep_node) = 684,945 ( 0.00%) self.in_task(|this| this.candidate_from_obligation_no_cache(stack)); . . debug!(?candidate, "CACHE MISS"); . self.insert_candidate_cache( 456,630 ( 0.00%) stack.obligation.param_env, 913,260 ( 0.00%) cache_fresh_trait_pred, . dep_node, . candidate.clone(), . ); 2,739,780 ( 0.00%) candidate . } . 2,283,150 ( 0.00%) fn candidate_from_obligation_no_cache<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { 517,345 ( 0.00%) if let Some(conflict) = self.is_knowable(stack) { . debug!("coherence stage: not knowable"); 44,401 ( 0.00%) if self.intercrate_ambiguity_causes.is_some() { . debug!("evaluate_stack: intercrate_ambiguity_causes is some"); . // Heuristics: show the diagnostics when there are no candidates in crate. . if let Ok(candidate_set) = self.assemble_candidates(stack) { . let mut no_candidates_apply = true; . . for c in candidate_set.vec.iter() { . if self.evaluate_candidate(stack, &c)?.may_apply() { . no_candidates_apply = false; -- line 87 ---------------------------------------- -- line 106 ---------------------------------------- . } else { . IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } . }; . debug!(?cause, "evaluate_stack: pushing cause"); . self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause); . } . } . } 88,802 ( 0.00%) return Ok(None); . } . 551,742 ( 0.00%) let candidate_set = self.assemble_candidates(stack)?; . 367,828 ( 0.00%) if candidate_set.ambiguous { . debug!("candidate set contains ambig"); 13,972 ( 0.00%) return Ok(None); . } . . let candidates = candidate_set.vec; . . debug!(?stack, ?candidates, "assembled {} candidates", candidates.len()); . . // At this point, we know that each of the entries in the . // candidate set is *individually* applicable. Now we have to . // figure out if they contain mutual incompatibilities. This . // frequently arises if we have an unconstrained input type -- . // for example, we are looking for `$0: Eq` where `$0` is some . // unconstrained type variable. In that case, we'll get a . // candidate which assumes $0 == int, one that assumes `$0 == . // usize`, etc. This spells an ambiguity. . 707,712 ( 0.00%) let mut candidates = self.filter_impls(candidates, stack.obligation); . . // If there is more than one candidate, first winnow them down . // by considering extra conditions (nested obligations and so . // forth). We don't winnow if there is exactly one . // candidate. This is a relatively minor distinction but it . // can lead to better inference and error-reporting. An . // example would be if there was an impl: . // . // impl Vec { fn push_clone(...) { ... } } . // . // and we were to see some code `foo.push_clone()` where `boo` . // is a `Vec` and `Bar` does not implement `Clone`. If . // we were to winnow, we'd wind up with zero candidates. . // Instead, we select the right impl now but report "`Bar` does . // not implement `Clone`". 353,856 ( 0.00%) if candidates.len() == 1 { 379,518 ( 0.00%) return self.filter_reservation_impls(candidates.pop().unwrap(), stack.obligation); . } . . // Winnow, but record the exact outcome of evaluation, which . // is needed for specialization. Propagate overflow if it occurs. 302,532 ( 0.00%) let mut candidates = candidates . .into_iter() . .map(|c| match self.evaluate_candidate(stack, &c) { 19,372,038 ( 0.02%) Ok(eval) if eval.may_apply() => { 25,808,376 ( 0.02%) Ok(Some(EvaluatedCandidate { candidate: c, evaluation: eval })) . } . Ok(_) => Ok(None), . Err(OverflowError::Canonical) => Err(Overflow), . Err(OverflowError::ErrorReporting) => Err(ErrorReporting), . }) . .flat_map(Result::transpose) . .collect::, _>>()?; . . debug!(?stack, ?candidates, "winnowed to {} candidates", candidates.len()); . 50,422 ( 0.00%) let needs_infer = stack.obligation.predicate.has_infer_types_or_consts(); . 151,266 ( 0.00%) let sized_predicate = self.tcx().lang_items().sized_trait() 100,844 ( 0.00%) == Some(stack.obligation.predicate.skip_binder().def_id()); . . // If there are STILL multiple candidates, we can further . // reduce the list by dropping duplicates -- including . // resolving specializations. 151,266 ( 0.00%) if candidates.len() > 1 { . let mut i = 0; 83,162 ( 0.00%) while i < candidates.len() { 6,442,654 ( 0.01%) let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| { . self.candidate_should_be_dropped_in_favor_of( . sized_predicate, . &candidates[i], . &candidates[j], . needs_infer, . ) . }); . if is_dup { . debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len()); . candidates.swap_remove(i); . } else { . debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len()); 121,876 ( 0.00%) i += 1; . . // If there are *STILL* multiple candidates, give up . // and report ambiguity. 182,814 ( 0.00%) if i > 1 { . debug!("multiple matches, ambig"); 325,080 ( 0.00%) return Err(Ambiguous( . candidates . .into_iter() 3,209,768 ( 0.00%) .filter_map(|c| match c.candidate { . SelectionCandidate::ImplCandidate(def_id) => Some(def_id), . _ => None, . }) . .collect(), . )); . } . } . } -- line 215 ---------------------------------------- -- line 219 ---------------------------------------- . // that we know of, anyway. Note that in the case where there . // are unbound type variables within the obligation, it might . // be the case that you could still satisfy the obligation . // from another crate by instantiating the type variables with . // a type from another crate that does have an impl. This case . // is checked for in `evaluate_stack` (and hence users . // who might care about this case, like coherence, should use . // that function). 23,332 ( 0.00%) if candidates.is_empty() { . // If there's an error type, 'downgrade' our result from . // `Err(Unimplemented)` to `Ok(None)`. This helps us avoid . // emitting additional spurious errors, since we're guaranteed . // to have emitted at least one. 29,572 ( 0.00%) if stack.obligation.references_error() { . debug!("no results for error type, treating as ambiguous"); 14,786 ( 0.00%) return Ok(None); . } . return Err(Unimplemented); . } . . // Just one candidate left. 25,638 ( 0.00%) self.filter_reservation_impls(candidates.pop().unwrap().candidate, stack.obligation) 2,101,499 ( 0.00%) } . 1,471,312 ( 0.00%) #[instrument(skip(self, stack), level = "debug")] 1,839,140 ( 0.00%) pub(super) fn assemble_candidates<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . ) -> Result, SelectionError<'tcx>> { 183,914 ( 0.00%) let TraitObligationStack { obligation, .. } = *stack; 3,494,366 ( 0.00%) let obligation = &Obligation { 183,914 ( 0.00%) param_env: obligation.param_env, . cause: obligation.cause.clone(), 551,742 ( 0.00%) recursion_depth: obligation.recursion_depth, 2,206,968 ( 0.00%) predicate: self.infcx().resolve_vars_if_possible(obligation.predicate), . }; . 381,682 ( 0.00%) if obligation.predicate.skip_binder().self_ty().is_ty_var() { . // Self is a type variable (e.g., `_: AsRef`). . // . // This is somewhat problematic, as the current scheme can't really . // handle it turning to be a projection. This does end up as truly . // ambiguous in most cases anyway. . // . // Take the fast path out - this also improves . // performance by preventing assemble_candidates_from_impls from . // matching every impl for this trait. 19,749 ( 0.00%) return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true }); . } . 531,993 ( 0.00%) let mut candidates = SelectionCandidateSet { vec: Vec::new(), ambiguous: false }; . . // The only way to prove a NotImplemented(T: Foo) predicate is via a negative impl. . // There are no compiler built-in rules for this. 354,662 ( 0.00%) if obligation.polarity() == ty::ImplPolarity::Negative { . self.assemble_candidates_for_trait_alias(obligation, &mut candidates); . self.assemble_candidates_from_impls(obligation, &mut candidates); . } else { 177,331 ( 0.00%) self.assemble_candidates_for_trait_alias(obligation, &mut candidates); . . // Other bounds. Consider both in-scope bounds from fn decl . // and applicable impls. There is a certain set of precedence rules here. 1,063,986 ( 0.00%) let def_id = obligation.predicate.def_id(); 177,331 ( 0.00%) let lang_items = self.tcx().lang_items(); . 555,311 ( 0.00%) if lang_items.copy_trait() == Some(def_id) { . debug!(obligation_self_ty = ?obligation.predicate.skip_binder().self_ty()); . . // User-defined copy impls are permitted, but only for . // structs and enums. 11,659 ( 0.00%) self.assemble_candidates_from_impls(obligation, &mut candidates); . . // For other types, we'll use the builtin rules. 46,636 ( 0.00%) let copy_conditions = self.copy_clone_conditions(obligation); 116,590 ( 0.00%) self.assemble_builtin_bound_candidates(copy_conditions, &mut candidates); 497,016 ( 0.00%) } else if lang_items.discriminant_kind_trait() == Some(def_id) { . // `DiscriminantKind` is automatically implemented for every type. . candidates.vec.push(DiscriminantKindCandidate); 497,016 ( 0.00%) } else if lang_items.pointee_trait() == Some(def_id) { . // `Pointee` is automatically implemented for every type. . candidates.vec.push(PointeeCandidate); 546,988 ( 0.00%) } else if lang_items.sized_trait() == Some(def_id) { . // Sized is never implementable by end-users, it is . // always automatically computed. 24,986 ( 0.00%) let sized_conditions = self.sized_conditions(obligation); 249,860 ( 0.00%) self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates); 426,970 ( 0.00%) } else if lang_items.unsize_trait() == Some(def_id) { 4,912 ( 0.00%) self.assemble_candidates_for_unsizing(obligation, &mut candidates); 415,503 ( 0.00%) } else if lang_items.drop_trait() == Some(def_id) . && obligation.predicate.skip_binder().constness == ty::BoundConstness::ConstIfConst . { 1,355 ( 0.00%) self.assemble_const_drop_candidates(obligation, &mut candidates); . } else { 421,615 ( 0.00%) if lang_items.clone_trait() == Some(def_id) { . // Same builtin conditions as `Copy`, i.e., every type which has builtin support . // for `Copy` also has builtin support for `Clone`, and tuples/arrays of `Clone` . // types have builtin support for `Clone`. 15,476 ( 0.00%) let clone_conditions = self.copy_clone_conditions(obligation); 34,821 ( 0.00%) self.assemble_builtin_bound_candidates(clone_conditions, &mut candidates); . } . 137,959 ( 0.00%) self.assemble_generator_candidates(obligation, &mut candidates); 137,959 ( 0.00%) self.assemble_closure_candidates(obligation, &mut candidates); 137,959 ( 0.00%) self.assemble_fn_pointer_candidates(obligation, &mut candidates); 413,877 ( 0.00%) self.assemble_candidates_from_impls(obligation, &mut candidates); . self.assemble_candidates_from_object_ty(obligation, &mut candidates); . } . . self.assemble_candidates_from_projected_tys(obligation, &mut candidates); . self.assemble_candidates_from_caller_bounds(stack, &mut candidates)?; . // Auto implementations have lower priority, so we only . // consider triggering a default if there is no other impl that can apply. 177,331 ( 0.00%) if candidates.vec.is_empty() { . self.assemble_candidates_from_auto_impls(obligation, &mut candidates); . } . } . debug!("candidate list size: {}", candidates.vec.len()); 2,305,303 ( 0.00%) Ok(candidates) . } . . #[tracing::instrument(level = "debug", skip(self, candidates))] . fn assemble_candidates_from_projected_tys( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . // Before we go into the whole placeholder thing, just . // quickly check if the self-type is a projection at all. 1,580,229 ( 0.00%) match obligation.predicate.skip_binder().trait_ref.self_ty().kind() { . ty::Projection(_) | ty::Opaque(..) => {} . ty::Infer(ty::TyVar(_)) => { . span_bug!( . obligation.cause.span, . "Self=_ should have been handled by assemble_candidates" . ); . } . _ => return, . } . 16,438 ( 0.00%) let result = self . .infcx 8,219 ( 0.00%) .probe(|_| self.match_projection_obligation_against_definition_bounds(obligation)); . 16,438 ( 0.00%) candidates.vec.extend(result.into_iter().map(ProjectionCandidate)); . } . . /// Given an obligation like ``, searches the obligations that the caller . /// supplied to find out whether it is listed among them. . /// . /// Never affects the inference environment. . #[tracing::instrument(level = "debug", skip(self, stack, candidates))] . fn assemble_candidates_from_caller_bounds<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) -> Result<(), SelectionError<'tcx>> { . debug!(?stack.obligation); . 709,324 ( 0.00%) let all_bounds = stack . .obligation . .param_env . .caller_bounds() . .iter() 11,854,936 ( 0.01%) .filter_map(|o| o.to_opt_poly_trait_pred()); . . // Micro-optimization: filter out predicates relating to different traits. . let matching_bounds = 59,807,076 ( 0.05%) all_bounds.filter(|p| p.def_id() == stack.obligation.predicate.def_id()); . . // Keep only those bounds which may apply, and propagate overflow if it occurs. . for bound in matching_bounds { . // FIXME(oli-obk): it is suspicious that we are dropping the constness and . // polarity here. 446,620 ( 0.00%) let wc = self.evaluate_where_clause(stack, bound.map_bound(|t| t.trait_ref))?; 893,240 ( 0.00%) if wc.may_apply() { . candidates.vec.push(ParamCandidate(bound)); . } . } . . Ok(()) . } . 1,103,672 ( 0.00%) fn assemble_generator_candidates( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { 1,655,508 ( 0.00%) if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) { . return; . } . . // Okay to skip binder because the substs on generator types never . // touch bound regions, they just capture the in-scope . // type/region parameters. . let self_ty = obligation.self_ty().skip_binder(); . match self_ty.kind() { -- line 414 ---------------------------------------- -- line 418 ---------------------------------------- . candidates.vec.push(GeneratorCandidate); . } . ty::Infer(ty::TyVar(_)) => { . debug!("assemble_generator_candidates: ambiguous self-type"); . candidates.ambiguous = true; . } . _ => {} . } 965,713 ( 0.00%) } . . /// Checks for the artificial impl that the compiler will create for an obligation like `X : . /// FnMut<..>` where `X` is a closure type. . /// . /// Note: the type parameters on a closure candidate are modeled as *output* type . /// parameters and hence do not affect whether this trait is a match or not. They will be . /// unified during the confirmation step. 965,713 ( 0.00%) fn assemble_closure_candidates( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { 1,517,549 ( 0.00%) let kind = match self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()) { . Some(k) => k, . None => { . return; . } . }; . . // Okay to skip binder because the substs on closure types never . // touch bound regions, they just capture the in-scope . // type/region parameters 5,717 ( 0.00%) match *obligation.self_ty().skip_binder().kind() { 694 ( 0.00%) ty::Closure(_, closure_substs) => { . debug!(?kind, ?obligation, "assemble_unboxed_candidates"); 2,776 ( 0.00%) match self.infcx.closure_kind(closure_substs) { . Some(closure_kind) => { . debug!(?closure_kind, "assemble_unboxed_candidates"); 3,465 ( 0.00%) if closure_kind.extends(kind) { . candidates.vec.push(ClosureCandidate); . } . } . None => { . debug!("assemble_unboxed_candidates: closure_kind not yet known"); . candidates.vec.push(ClosureCandidate); . } . } . } . ty::Infer(ty::TyVar(_)) => { . debug!("assemble_unboxed_closure_candidates: ambiguous self-type"); . candidates.ambiguous = true; . } . _ => {} . } 827,754 ( 0.00%) } . . /// Implements one of the `Fn()` family for a fn pointer. 1,241,631 ( 0.00%) fn assemble_fn_pointer_candidates( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . // We provide impl of all fn traits for fn pointers. 1,379,590 ( 0.00%) if self.tcx().fn_trait_kind_from_lang_item(obligation.predicate.def_id()).is_none() { . return; . } . . // Okay to skip binder because what we are inspecting doesn't involve bound regions. 2,030 ( 0.00%) let self_ty = obligation.self_ty().skip_binder(); 7,001 ( 0.00%) match *self_ty.kind() { . ty::Infer(ty::TyVar(_)) => { . debug!("assemble_fn_pointer_candidates: ambiguous self-type"); . candidates.ambiguous = true; // Could wind up being a fn() type. . } . // Provide an impl, but only for suitable `fn` pointers. . ty::FnPtr(_) => { . if let ty::FnSig { . unsafety: hir::Unsafety::Normal, -- line 494 ---------------------------------------- -- line 496 ---------------------------------------- . c_variadic: false, . .. . } = self_ty.fn_sig(self.tcx()).skip_binder() . { . candidates.vec.push(FnPointerCandidate { is_const: false }); . } . } . // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396). 52 ( 0.00%) ty::FnDef(def_id, _) => { 78 ( 0.00%) if let ty::FnSig { . unsafety: hir::Unsafety::Normal, . abi: Abi::Rust, . c_variadic: false, . .. 52 ( 0.00%) } = self_ty.fn_sig(self.tcx()).skip_binder() . { 49 ( 0.00%) if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() { . candidates . .vec 104 ( 0.00%) .push(FnPointerCandidate { is_const: self.tcx().is_const_fn(def_id) }); . } . } . } . _ => {} . } 1,103,672 ( 0.00%) } . . /// Searches for impls that might apply to `obligation`. 1,496,180 ( 0.00%) fn assemble_candidates_from_impls( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . debug!(?obligation, "assemble_candidates_from_impls"); . . // Essentially any user-written impl will match with an error type, . // so creating `ImplCandidates` isn't useful. However, we might . // end up finding a candidate elsewhere (e.g. a `BuiltinCandidate` for `Sized) . // This helps us avoid overflow: see issue #72839 . // Since compilation is already guaranteed to fail, this is just . // to try to show the 'nicest' possible errors to the user. . // We don't check for errors in the `ParamEnv` - in practice, . // it seems to cause us to be overly aggressive in deciding . // to give up searching for candidates, leading to spurious errors. 299,236 ( 0.00%) if obligation.predicate.references_error() { . return; . } . 448,854 ( 0.00%) self.tcx().for_each_relevant_impl( 1,196,944 ( 0.00%) obligation.predicate.def_id(), . obligation.predicate.skip_binder().trait_ref.self_ty(), 748,090 ( 0.00%) |impl_def_id| { 57,289,096 ( 0.05%) self.infcx.probe(|_| { 56,097,574 ( 0.05%) if let Ok(_substs) = self.match_impl(impl_def_id, obligation) { 6,565,376 ( 0.01%) candidates.vec.push(ImplCandidate(impl_def_id)); . } . }); . }, . ); 1,196,944 ( 0.00%) } . . fn assemble_candidates_from_auto_impls( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . // Okay to skip binder here because the tests we do below do not involve bound regions. 15,900 ( 0.00%) let self_ty = obligation.self_ty().skip_binder(); . debug!(?self_ty, "assemble_candidates_from_auto_impls"); . 95,400 ( 0.00%) let def_id = obligation.predicate.def_id(); . 63,600 ( 0.00%) if self.tcx().trait_is_auto(def_id) { 2,212 ( 0.00%) match self_ty.kind() { . ty::Dynamic(..) => { . // For object types, we don't know what the closed . // over types are. This means we conservatively . // say nothing; a candidate may be added by . // `assemble_candidates_from_object_ty`. . } . ty::Foreign(..) => { . // Since the contents of foreign types is unknown, -- line 577 ---------------------------------------- -- line 625 ---------------------------------------- . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . debug!( . self_ty = ?obligation.self_ty().skip_binder(), . "assemble_candidates_from_object_ty", . ); . 1,103,672 ( 0.00%) self.infcx.probe(|_snapshot| { . // The code below doesn't care about regions, and the . // self-ty here doesn't escape this probe, so just erase . // any LBR. 137,959 ( 0.00%) let self_ty = self.tcx().erase_late_bound_regions(obligation.self_ty()); 690,067 ( 0.00%) let poly_trait_ref = match self_ty.kind() { . ty::Dynamic(ref data, ..) => { . if data.auto_traits().any(|did| did == obligation.predicate.def_id()) { . debug!( . "assemble_candidates_from_object_ty: matched builtin bound, \ . pushing candidate" . ); . candidates.vec.push(BuiltinObjectCandidate); . return; -- line 646 ---------------------------------------- -- line 739 ---------------------------------------- . }; . . let def_id = data.principal_def_id()?; . . return Some((normalized_ty, def_id)); . } . . /// Searches for unsizing that might apply to `obligation`. 24,560 ( 0.00%) fn assemble_candidates_for_unsizing( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . // We currently never consider higher-ranked obligations e.g. . // `for<'a> &'a T: Unsize` to be implemented. This is not . // because they are a priori invalid, and we could potentially add support . // for them later, it's just that there isn't really a strong need for it. -- line 755 ---------------------------------------- -- line 758 ---------------------------------------- . // . // That said, one might try to write a fn with a where clause like . // for<'a> Foo<'a, T>: Unsize> . // where the `'a` is kind of orthogonal to the relevant part of the `Unsize`. . // Still, you'd be more likely to write that where clause as . // T: Trait . // so it seems ok if we (conservatively) fail to accept that `Unsize` . // obligation above. Should be possible to extend this in the future. 12,280 ( 0.00%) let source = match obligation.self_ty().no_bound_vars() { 2,456 ( 0.00%) Some(t) => t, . None => { . // Don't add any candidates if there are bound regions. . return; . } . }; 7,368 ( 0.00%) let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1); . . debug!(?source, ?target, "assemble_candidates_for_unsizing"); . 35,472 ( 0.00%) match (source.kind(), target.kind()) { . // Trait+Kx+'a -> Trait+Ky+'b (upcasts). . (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => { . // Upcast coercions permit several things: . // . // 1. Dropping auto traits, e.g., `Foo + Send` to `Foo` . // 2. Tightening the region bound, e.g., `Foo + 'a` to `Foo + 'b` if `'a: 'b` . // 3. Tightening trait to its super traits, eg. `Foo` to `Bar` if `Foo: Bar` . // -- line 785 ---------------------------------------- -- line 843 ---------------------------------------- . candidates.vec.push(BuiltinUnsizeCandidate); . } . . // Ambiguous handling is below `T` -> `Trait`, because inference . // variables can still implement `Unsize` and nested . // obligations will have the final say (likely deferred). . (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => { . debug!("assemble_candidates_for_unsizing: ambiguous"); 806 ( 0.00%) candidates.ambiguous = true; . } . . // `[T; n]` -> `[T]` . (&ty::Array(..), &ty::Slice(_)) => { . candidates.vec.push(BuiltinUnsizeCandidate); . } . . // `Struct` -> `Struct` 3,435 ( 0.00%) (&ty::Adt(def_id_a, _), &ty::Adt(def_id_b, _)) if def_id_a.is_struct() => { 5,669 ( 0.00%) if def_id_a == def_id_b { . candidates.vec.push(BuiltinUnsizeCandidate); . } . } . . // `(.., T)` -> `(.., U)` . (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => { . if tys_a.len() == tys_b.len() { . candidates.vec.push(BuiltinUnsizeCandidate); . } . } . . _ => {} . }; 19,648 ( 0.00%) } . 2,482,634 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, obligation, candidates))] . fn assemble_candidates_for_trait_alias( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . // Okay to skip binder here because the tests we do below do not involve bound regions. 354,662 ( 0.00%) let self_ty = obligation.self_ty().skip_binder(); . debug!(?self_ty); . 1,418,648 ( 0.00%) let def_id = obligation.predicate.def_id(); . 709,324 ( 0.00%) if self.tcx().is_trait_alias(def_id) { . candidates.vec.push(TraitAliasCandidate(def_id)); . } . } . . /// Assembles the trait which are built-in to the language itself: . /// `Copy`, `Clone` and `Sized`. 324,112 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, candidates))] . fn assemble_builtin_bound_candidates( . &mut self, . conditions: BuiltinImplConditions<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { 170,388 ( 0.00%) match conditions { . BuiltinImplConditions::Where(nested) => { . candidates . .vec . .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() }); . } . BuiltinImplConditions::None => {} . BuiltinImplConditions::Ambiguous => { . candidates.ambiguous = true; . } . } . } . 2,168 ( 0.00%) fn assemble_const_drop_candidates( . &mut self, . obligation: &TraitObligation<'tcx>, . candidates: &mut SelectionCandidateSet<'tcx>, . ) { . // If the predicate is `~const Drop` in a non-const environment, we don't actually need . // to check anything. We'll short-circuit checking any obligations in confirmation, too. . if obligation.param_env.constness() == hir::Constness::NotConst { . candidates.vec.push(ConstDropCandidate(None)); . return; . } . 388 ( 0.00%) let self_ty = self.infcx().shallow_resolve(obligation.self_ty()); 970 ( 0.00%) match self_ty.skip_binder().kind() { . ty::Opaque(..) . | ty::Dynamic(..) . | ty::Error(_) . | ty::Bound(..) . | ty::Param(_) . | ty::Placeholder(_) . | ty::Projection(_) => { . // We don't know if these are `~const Drop`, at least -- line 936 ---------------------------------------- -- line 958 ---------------------------------------- . | ty::Tuple(_) . | ty::GeneratorWitness(_) => { . // These are built-in, and cannot have a custom `impl const Drop`. . candidates.vec.push(ConstDropCandidate(None)); . } . . ty::Adt(..) => { . // Find a custom `impl Drop` impl, if it exists 450 ( 0.00%) let relevant_impl = self.tcx().find_map_relevant_impl( 900 ( 0.00%) obligation.predicate.def_id(), 450 ( 0.00%) obligation.predicate.skip_binder().trait_ref.self_ty(), . Some, . ); . 300 ( 0.00%) if let Some(impl_def_id) = relevant_impl { . // Check that `impl Drop` is actually const, if there is a custom impl 1 ( 0.00%) if self.tcx().impl_constness(impl_def_id) == hir::Constness::Const { . candidates.vec.push(ConstDropCandidate(Some(impl_def_id))); . } . } else { . // Otherwise check the ADT like a built-in type (structurally) . candidates.vec.push(ConstDropCandidate(None)); . } . } . . ty::Infer(_) => { . candidates.ambiguous = true; . } . } 2,168 ( 0.00%) } . } 34,948,943 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs -------------------------------------------------------------------------------- Ir -- line 94 ---------------------------------------- . /// Adds packed 32-bit integers in `a` and `b`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_add_epi32) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(paddd))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_add_epi32(a: __m128i, b: __m128i) -> __m128i { 17 ( 0.00%) transmute(simd_add(a.as_i32x4(), b.as_i32x4())) . } . . /// Adds packed 64-bit integers in `a` and `b`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_add_epi64) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(paddq))] -- line 110 ---------------------------------------- -- line 767 ---------------------------------------- . /// `b`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_or_si128) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(orps))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_or_si128(a: __m128i, b: __m128i) -> __m128i { 96 ( 0.00%) simd_or(a, b) . } . . /// Computes the bitwise XOR of 128 bits (representing integer data) in `a` and . /// `b`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_xor_si128) . #[inline] . #[target_feature(enable = "sse2")] -- line 783 ---------------------------------------- -- line 790 ---------------------------------------- . /// Compares packed 8-bit integers in `a` and `b` for equality. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmpeq_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpeqb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_cmpeq_epi8(a: __m128i, b: __m128i) -> __m128i { 15,948,230 ( 0.01%) transmute::(simd_eq(a.as_i8x16(), b.as_i8x16())) . } . . /// Compares packed 16-bit integers in `a` and `b` for equality. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmpeq_epi16) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpeqw))] -- line 806 ---------------------------------------- -- line 823 ---------------------------------------- . /// Compares packed 8-bit integers in `a` and `b` for greater-than. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmpgt_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpgtb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_cmpgt_epi8(a: __m128i, b: __m128i) -> __m128i { 192 ( 0.00%) transmute::(simd_gt(a.as_i8x16(), b.as_i8x16())) . } . . /// Compares packed 16-bit integers in `a` and `b` for greater-than. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmpgt_epi16) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpgtw))] -- line 839 ---------------------------------------- -- line 856 ---------------------------------------- . /// Compares packed 8-bit integers in `a` and `b` for less-than. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmplt_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpgtb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_cmplt_epi8(a: __m128i, b: __m128i) -> __m128i { 192,576 ( 0.00%) transmute::(simd_lt(a.as_i8x16(), b.as_i8x16())) . } . . /// Compares packed 16-bit integers in `a` and `b` for less-than. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmplt_epi16) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpgtw))] -- line 872 ---------------------------------------- -- line 1174 ---------------------------------------- . /// `mem_addr` must be aligned on a 16-byte boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_si128) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(movaps))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_load_si128(mem_addr: *const __m128i) -> __m128i { 1,583,901 ( 0.00%) *mem_addr . } . . /// Loads 128-bits of integer data from memory into a new vector. . /// . /// `mem_addr` does not need to be aligned on any particular boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadu_si128) . #[inline] -- line 1190 ---------------------------------------- -- line 1224 ---------------------------------------- . /// `mem_addr` must be aligned on a 16-byte boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_store_si128) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(movaps))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_store_si128(mem_addr: *mut __m128i, a: __m128i) { 96 ( 0.00%) *mem_addr = a; . } . . /// Stores 128-bits of integer data from `a` into memory. . /// . /// `mem_addr` does not need to be aligned on any particular boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_storeu_si128) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(movups))] // FIXME movdqu expected . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_storeu_si128(mem_addr: *mut __m128i, a: __m128i) { 16 ( 0.00%) storeudq(mem_addr as *mut i8, a); . } . . /// Stores the lower 64-bit integer `a` to a memory location. . /// . /// `mem_addr` does not need to be aligned on any particular boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_storel_epi64) . #[inline] -- line 1253 ---------------------------------------- -- line 1373 ---------------------------------------- . /// Returns a mask of the most significant bit of each element in `a`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_movemask_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pmovmskb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_movemask_epi8(a: __m128i) -> i32 { 1,134,141,358 ( 0.97%) pmovmskb(a.as_i8x16()) . } . . /// Shuffles 32-bit integers in `a` using the control in `IMM8`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_shuffle_epi32) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pshufd, IMM8 = 9))] -- line 1389 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/relate.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . . /// Returns a static string we can use for printouts. . fn tag(&self) -> &'static str; . . /// Returns `true` if the value `a` is the "expected" type in the . /// relation. Just affects error messages. . fn a_is_expected(&self) -> bool; . 17,892 ( 0.00%) fn with_cause(&mut self, _cause: Cause, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . f(self) 15,780 ( 0.00%) } . . /// Generic relation routine suitable for most anything. 2,759,389 ( 0.00%) fn relate>(&mut self, a: T, b: T) -> RelateResult<'tcx, T> { 103,015,641 ( 0.09%) Relate::relate(self, a, b) 2,261,929 ( 0.00%) } . . /// Relate the two substitutions for the given item. The default . /// is to look up the variance for the item and proceed . /// accordingly. 457,480 ( 0.00%) fn relate_item_substs( . &mut self, . item_def_id: DefId, . a_subst: SubstsRef<'tcx>, . b_subst: SubstsRef<'tcx>, . ) -> RelateResult<'tcx, SubstsRef<'tcx>> { . debug!( . "relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})", . item_def_id, a_subst, b_subst . ); . . let tcx = self.tcx(); . let opt_variances = tcx.variances_of(item_def_id); 182,992 ( 0.00%) relate_substs(self, Some((item_def_id, opt_variances)), a_subst, b_subst) 411,732 ( 0.00%) } . . /// Switch variance for the purpose of relating `a` and `b`. . fn relate_with_variance>( . &mut self, . variance: ty::Variance, . info: ty::VarianceDiagInfo<'tcx>, . a: T, . b: T, -- line 73 ---------------------------------------- -- line 108 ---------------------------------------- . a: Self, . b: Self, . ) -> RelateResult<'tcx, Self>; . } . . /////////////////////////////////////////////////////////////////////////// . // Relate impls . 799,640 ( 0.00%) pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>( . relation: &mut R, . a: ty::TypeAndMut<'tcx>, . b: ty::TypeAndMut<'tcx>, . base_ty: Ty<'tcx>, . ) -> RelateResult<'tcx, ty::TypeAndMut<'tcx>> { . debug!("{}.mts({:?}, {:?})", relation.tag(), a, b); 300,236 ( 0.00%) if a.mutbl != b.mutbl { 3,528 ( 0.00%) Err(TypeError::Mutability) . } else { . let mutbl = a.mutbl; . let (variance, info) = match mutbl { . ast::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None), . ast::Mutability::Mut => { . (ty::Invariant, ty::VarianceDiagInfo::Invariant { ty: base_ty, param_index: 0 }) . } . }; 57,497 ( 0.00%) let ty = relation.relate_with_variance(variance, info, a.ty, b.ty)?; 369,228 ( 0.00%) Ok(ty::TypeAndMut { ty, mutbl }) . } 941,648 ( 0.00%) } . . pub fn relate_substs<'tcx, R: TypeRelation<'tcx>>( . relation: &mut R, . variances: Option<(DefId, &[ty::Variance])>, . a_subst: SubstsRef<'tcx>, . b_subst: SubstsRef<'tcx>, . ) -> RelateResult<'tcx, SubstsRef<'tcx>> { 64,948,155 ( 0.06%) let tcx = relation.tcx(); 21,534,331 ( 0.02%) let mut cached_ty = None; . . let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| { 113,448,490 ( 0.10%) let (variance, variance_info) = match variances { 416,370 ( 0.00%) Some((ty_def_id, variances)) => { 624,555 ( 0.00%) let variance = variances[i]; 208,185 ( 0.00%) let variance_info = if variance == ty::Invariant { . let ty = 116,042 ( 0.00%) cached_ty.get_or_insert_with(|| tcx.type_of(ty_def_id).subst(tcx, a_subst)); . ty::VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() } . } else { . ty::VarianceDiagInfo::default() . }; . (variance, variance_info) . } . None => (ty::Invariant, ty::VarianceDiagInfo::default()), . }; 23,061,725 ( 0.02%) relation.relate_with_variance(variance, variance_info, a, b) . }); . . tcx.mk_substs(params) . } . . impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> { 28,704 ( 0.00%) fn relate>( . relation: &mut R, . a: ty::FnSig<'tcx>, . b: ty::FnSig<'tcx>, . ) -> RelateResult<'tcx, ty::FnSig<'tcx>> { . let tcx = relation.tcx(); . 13,248 ( 0.00%) if a.c_variadic != b.c_variadic { . return Err(TypeError::VariadicMismatch(expected_found( . relation, . a.c_variadic, . b.c_variadic, . ))); . } 11,848 ( 0.00%) let unsafety = relation.relate(a.unsafety, b.unsafety)?; . let abi = relation.relate(a.abi, b.abi)?; . 18,364 ( 0.00%) if a.inputs().len() != b.inputs().len() { . return Err(TypeError::ArgCount); . } . 19,872 ( 0.00%) let inputs_and_output = iter::zip(a.inputs(), b.inputs()) 9,016 ( 0.00%) .map(|(&a, &b)| ((a, b), false)) 17,664 ( 0.00%) .chain(iter::once(((a.output(), b.output()), true))) 3,274 ( 0.00%) .map(|((a, b), is_output)| { 3,274 ( 0.00%) if is_output { 1,260 ( 0.00%) relation.relate(a, b) . } else { . relation.relate_with_variance( . ty::Contravariant, . ty::VarianceDiagInfo::default(), . a, . b, . ) . } . }) . .enumerate() 13,045 ( 0.00%) .map(|(i, r)| match r { . Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => { . Err(TypeError::ArgumentSorts(exp_found, i)) . } . Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => { . Err(TypeError::ArgumentMutability(i)) . } 20,423 ( 0.00%) r => r, . }); 16,964 ( 0.00%) Ok(ty::FnSig { . inputs_and_output: tcx.mk_type_list(inputs_and_output)?, 2,208 ( 0.00%) c_variadic: a.c_variadic, . unsafety, . abi, . }) 19,872 ( 0.00%) } . } . . impl<'tcx> Relate<'tcx> for ty::BoundConstness { . fn relate>( . relation: &mut R, . a: ty::BoundConstness, . b: ty::BoundConstness, . ) -> RelateResult<'tcx, ty::BoundConstness> { -- line 229 ---------------------------------------- -- line 236 ---------------------------------------- . } . . impl<'tcx> Relate<'tcx> for ast::Unsafety { . fn relate>( . relation: &mut R, . a: ast::Unsafety, . b: ast::Unsafety, . ) -> RelateResult<'tcx, ast::Unsafety> { 2,208 ( 0.00%) if a != b { . Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b))) . } else { . Ok(a) . } . } . } . . impl<'tcx> Relate<'tcx> for abi::Abi { -- line 252 ---------------------------------------- -- line 255 ---------------------------------------- . a: abi::Abi, . b: abi::Abi, . ) -> RelateResult<'tcx, abi::Abi> { . if a == b { Ok(a) } else { Err(TypeError::AbiMismatch(expected_found(relation, a, b))) } . } . } . . impl<'tcx> Relate<'tcx> for ty::ProjectionTy<'tcx> { 1,304,881 ( 0.00%) fn relate>( . relation: &mut R, . a: ty::ProjectionTy<'tcx>, . b: ty::ProjectionTy<'tcx>, . ) -> RelateResult<'tcx, ty::ProjectionTy<'tcx>> { 349,576 ( 0.00%) if a.item_def_id != b.item_def_id { 2,568 ( 0.00%) Err(TypeError::ProjectionMismatched(expected_found( . relation, . a.item_def_id, . b.item_def_id, . ))) . } else { . let substs = relation.relate(a.substs, b.substs)?; 394,264 ( 0.00%) Ok(ty::ProjectionTy { item_def_id: a.item_def_id, substs: &substs }) . } 917,450 ( 0.00%) } . } . . impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> { . fn relate>( . relation: &mut R, . a: ty::ExistentialProjection<'tcx>, . b: ty::ExistentialProjection<'tcx>, . ) -> RelateResult<'tcx, ty::ExistentialProjection<'tcx>> { -- line 286 ---------------------------------------- -- line 304 ---------------------------------------- . b.substs, . )?; . Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, term }) . } . } . } . . impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> { 151,964,759 ( 0.13%) fn relate>( . relation: &mut R, . a: ty::TraitRef<'tcx>, . b: ty::TraitRef<'tcx>, . ) -> RelateResult<'tcx, ty::TraitRef<'tcx>> { . // Different traits cannot be related. 32,578,422 ( 0.03%) if a.def_id != b.def_id { 28,116 ( 0.00%) Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id))) . } else { 10,856,350 ( 0.01%) let substs = relate_substs(relation, None, a.substs, b.substs)?; 27,989,684 ( 0.02%) Ok(ty::TraitRef { def_id: a.def_id, substs }) . } 97,687,932 ( 0.08%) } . } . . impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> { 5,478 ( 0.00%) fn relate>( . relation: &mut R, . a: ty::ExistentialTraitRef<'tcx>, . b: ty::ExistentialTraitRef<'tcx>, . ) -> RelateResult<'tcx, ty::ExistentialTraitRef<'tcx>> { . // Different traits cannot be related. 7,830 ( 0.00%) if a.def_id != b.def_id { . Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id))) . } else { 3,606 ( 0.00%) let substs = relate_substs(relation, None, a.substs, b.substs)?; 4,224 ( 0.00%) Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs }) . } 3,486 ( 0.00%) } . } . . #[derive(Copy, Debug, Clone, TypeFoldable)] . struct GeneratorWitness<'tcx>(&'tcx ty::List>); . . impl<'tcx> Relate<'tcx> for GeneratorWitness<'tcx> { . fn relate>( . relation: &mut R, -- line 348 ---------------------------------------- -- line 358 ---------------------------------------- . . impl<'tcx> Relate<'tcx> for Ty<'tcx> { . #[inline] . fn relate>( . relation: &mut R, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> { 18,524,991 ( 0.02%) relation.tys(a, b) . } . } . . /// The main "type relation" routine. Note that this does not handle . /// inference artifacts, so you should filter those out before calling . /// it. 95,312,808 ( 0.08%) pub fn super_relate_tys<'tcx, R: TypeRelation<'tcx>>( . relation: &mut R, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> { . let tcx = relation.tcx(); . debug!("super_relate_tys: a={:?} b={:?}", a, b); 214,333,802 ( 0.18%) match (a.kind(), b.kind()) { . (&ty::Infer(_), _) | (_, &ty::Infer(_)) => { . // The caller should handle these cases! . bug!("var types encountered in super_relate_tys") . } . . (ty::Bound(..), _) | (_, ty::Bound(..)) => { . bug!("bound types encountered in super_relate_tys") . } -- line 388 ---------------------------------------- -- line 391 ---------------------------------------- . . (&ty::Never, _) . | (&ty::Char, _) . | (&ty::Bool, _) . | (&ty::Int(_), _) . | (&ty::Uint(_), _) . | (&ty::Float(_), _) . | (&ty::Str, _) 60,008 ( 0.00%) if a == b => . { . Ok(a) . } . 1,791,575 ( 0.00%) (&ty::Param(ref a_p), &ty::Param(ref b_p)) if a_p.index == b_p.index => Ok(a), . . (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a), . 106,332,770 ( 0.09%) (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => { 41,938,376 ( 0.04%) let substs = relation.relate_item_substs(a_def.did, a_substs, b_substs)?; . Ok(tcx.mk_adt(a_def, substs)) . } . . (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(tcx.mk_foreign(a_id)), . 18,270 ( 0.00%) (&ty::Dynamic(a_obj, a_region), &ty::Dynamic(b_obj, b_region)) => { 5,220 ( 0.00%) let region_bound = relation.with_cause(Cause::ExistentialRegionBound, |relation| { . relation.relate_with_variance( . ty::Contravariant, . ty::VarianceDiagInfo::default(), 2,610 ( 0.00%) a_region, . b_region, . ) . })?; . Ok(tcx.mk_dynamic(relation.relate(a_obj, b_obj)?, region_bound)) . } . . (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _)) . if a_id == b_id => -- line 428 ---------------------------------------- -- line 439 ---------------------------------------- . // inside the binder so we can related them . let a_types = a_types.map_bound(GeneratorWitness); . let b_types = b_types.map_bound(GeneratorWitness); . // Then remove the GeneratorWitness for the result . let types = relation.relate(a_types, b_types)?.map_bound(|witness| witness.0); . Ok(tcx.mk_generator_witness(types)) . } . 5,352 ( 0.00%) (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => { . // All Closure types with the same id represent . // the (anonymous) type of the same closure expression. So . // all of their regions should be equated. 1,338 ( 0.00%) let substs = relation.relate(a_substs, b_substs)?; . Ok(tcx.mk_closure(a_id, &substs)) . } . 12,401 ( 0.00%) (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => { 5,420 ( 0.00%) let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?; . Ok(tcx.mk_ptr(mt)) . } . 3,376,856 ( 0.00%) (&ty::Ref(a_r, a_ty, a_mutbl), &ty::Ref(b_r, b_ty, b_mutbl)) => { 583,408 ( 0.00%) let r = relation.relate_with_variance( . ty::Contravariant, . ty::VarianceDiagInfo::default(), . a_r, . b_r, . )?; . let a_mt = ty::TypeAndMut { ty: a_ty, mutbl: a_mutbl }; . let b_mt = ty::TypeAndMut { ty: b_ty, mutbl: b_mutbl }; 919,192 ( 0.00%) let mt = relate_type_and_mut(relation, a_mt, b_mt, a)?; . Ok(tcx.mk_ref(r, mt)) . } . 65,788 ( 0.00%) (&ty::Array(a_t, sz_a), &ty::Array(b_t, sz_b)) => { 6,073 ( 0.00%) let t = relation.relate(a_t, b_t)?; 25,854 ( 0.00%) match relation.relate(sz_a, sz_b) { 37,053 ( 0.00%) Ok(sz) => Ok(tcx.mk_ty(ty::Array(t, sz))), . Err(err) => { . // Check whether the lengths are both concrete/known values, . // but are unequal, for better diagnostics. . // . // It might seem dubious to eagerly evaluate these constants here, . // we however cannot end up with errors in `Relate` during both . // `type_of` and `predicates_of`. This means that evaluating the . // constants should not cause cycle errors here. 2,880 ( 0.00%) let sz_a = sz_a.try_eval_usize(tcx, relation.param_env()); 1,728 ( 0.00%) let sz_b = sz_b.try_eval_usize(tcx, relation.param_env()); 3,360 ( 0.00%) match (sz_a, sz_b) { 2,112 ( 0.00%) (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err( . TypeError::FixedArraySize(expected_found(relation, sz_a_val, sz_b_val)), . ), 192 ( 0.00%) _ => Err(err), . } . } . } . } . 24,142 ( 0.00%) (&ty::Slice(a_t), &ty::Slice(b_t)) => { 1,512 ( 0.00%) let t = relation.relate(a_t, b_t)?; . Ok(tcx.mk_slice(t)) . } . 98,126 ( 0.00%) (&ty::Tuple(as_), &ty::Tuple(bs)) => { 98,126 ( 0.00%) if as_.len() == bs.len() { . Ok(tcx.mk_tup( 427,903 ( 0.00%) iter::zip(as_, bs).map(|(a, b)| relation.relate(a.expect_ty(), b.expect_ty())), . )?) 6 ( 0.00%) } else if !(as_.is_empty() || bs.is_empty()) { 8 ( 0.00%) Err(TypeError::TupleSize(expected_found(relation, as_.len(), bs.len()))) . } else { . Err(TypeError::Sorts(expected_found(relation, a, b))) . } . } . 8,799 ( 0.00%) (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs)) 14,665 ( 0.00%) if a_def_id == b_def_id => . { 11,732 ( 0.00%) let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?; . Ok(tcx.mk_fn_def(a_def_id, substs)) . } . . (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => { 25,438 ( 0.00%) let fty = relation.relate(a_fty, b_fty)?; . Ok(tcx.mk_fn_ptr(fty)) . } . . // these two are already handled downstream in case of lazy normalization 341,035 ( 0.00%) (&ty::Projection(a_data), &ty::Projection(b_data)) => { . let projection_ty = relation.relate(a_data, b_data)?; . Ok(tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs)) . } . . (&ty::Opaque(a_def_id, a_substs), &ty::Opaque(b_def_id, b_substs)) . if a_def_id == b_def_id => . { . let substs = relate_substs(relation, None, a_substs, b_substs)?; . Ok(tcx.mk_opaque(a_def_id, substs)) . } . . _ => Err(TypeError::Sorts(expected_found(relation, a, b))), . } 107,226,909 ( 0.09%) } . . /// The main "const relation" routine. Note that this does not handle . /// inference artifacts, so you should filter those out before calling . /// it. 100,008,410 ( 0.09%) pub fn super_relate_consts<'tcx, R: TypeRelation<'tcx>>( . relation: &mut R, . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { . debug!("{}.super_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b); . let tcx = relation.tcx(); . . // FIXME(oli-obk): once const generics can have generic types, this assertion . // will likely get triggered. Move to `normalize_erasing_regions` at that point. 20,001,682 ( 0.02%) let a_ty = tcx.erase_regions(a.ty); 20,001,682 ( 0.02%) let b_ty = tcx.erase_regions(b.ty); 10,000,841 ( 0.01%) if a_ty != b_ty { . relation.tcx().sess.delay_span_bug( . DUMMY_SP, . &format!("cannot relate constants of different types: {} != {}", a_ty, b_ty), . ); . } . . let eagerly_eval = |x: &'tcx ty::Const<'tcx>| x.eval(tcx, relation.param_env()); 10,000,841 ( 0.01%) let a = eagerly_eval(a); 20,001,682 ( 0.02%) let b = eagerly_eval(b); . . // Currently, the values that can be unified are primitive types, . // and those that derive both `PartialEq` and `Eq`, corresponding . // to structural-match types. 110,133,297 ( 0.09%) let is_match = match (a.val, b.val) { . (ty::ConstKind::Infer(_), _) | (_, ty::ConstKind::Infer(_)) => { . // The caller should handle these cases! . bug!("var types encountered in super_relate_consts: {:?} {:?}", a, b) . } . . (ty::ConstKind::Error(_), _) => return Ok(a), . (_, ty::ConstKind::Error(_)) => return Ok(b), . -- line 580 ---------------------------------------- -- line 608 ---------------------------------------- . substs, . promoted: au.promoted, . }), . ty: a.ty, . })); . } . _ => false, . }; 56,342,620 ( 0.05%) if is_match { Ok(a) } else { Err(TypeError::ConstMismatch(expected_found(relation, a, b))) } 90,007,569 ( 0.08%) } . . fn check_const_value_eq<'tcx, R: TypeRelation<'tcx>>( . relation: &mut R, . a_val: ConstValue<'tcx>, . b_val: ConstValue<'tcx>, . // FIXME(oli-obk): these arguments should go away with valtrees . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . // FIXME(oli-obk): this should just be `bool` with valtrees . ) -> RelateResult<'tcx, bool> { 9,869,184 ( 0.01%) let tcx = relation.tcx(); 108,561,024 ( 0.09%) Ok(match (a_val, b_val) { 217,122,048 ( 0.19%) (ConstValue::Scalar(Scalar::Int(a_val)), ConstValue::Scalar(Scalar::Int(b_val))) => { 9,869,184 ( 0.01%) a_val == b_val . } . ( . ConstValue::Scalar(Scalar::Ptr(a_val, _a_size)), . ConstValue::Scalar(Scalar::Ptr(b_val, _b_size)), . ) => { . a_val == b_val . || match (tcx.global_alloc(a_val.provenance), tcx.global_alloc(b_val.provenance)) { . (GlobalAlloc::Function(a_instance), GlobalAlloc::Function(b_instance)) => { -- line 639 ---------------------------------------- -- line 672 ---------------------------------------- . } . } . . _ => false, . }) . } . . impl<'tcx> Relate<'tcx> for &'tcx ty::List>> { 26,100 ( 0.00%) fn relate>( . relation: &mut R, . a: Self, . b: Self, . ) -> RelateResult<'tcx, Self> { 2,610 ( 0.00%) let tcx = relation.tcx(); . . // FIXME: this is wasteful, but want to do a perf run to see how slow it is. . // We need to perform this deduplication as we sometimes generate duplicate projections . // in `a`. . let mut a_v: Vec<_> = a.into_iter().collect(); . let mut b_v: Vec<_> = b.into_iter().collect(); . // `skip_binder` here is okay because `stable_cmp` doesn't look at binders . a_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder())); . a_v.dedup(); . b_v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder())); . b_v.dedup(); 7,830 ( 0.00%) if a_v.len() != b_v.len() { . return Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))); . } . 10,440 ( 0.00%) let v = iter::zip(a_v, b_v).map(|(ep_a, ep_b)| { . use crate::ty::ExistentialPredicate::*; 10,440 ( 0.00%) match (ep_a.skip_binder(), ep_b.skip_binder()) { 10,440 ( 0.00%) (Trait(a), Trait(b)) => Ok(ep_a . .rebind(Trait(relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder()))), . (Projection(a), Projection(b)) => Ok(ep_a.rebind(Projection( . relation.relate(ep_a.rebind(a), ep_b.rebind(b))?.skip_binder(), . ))), . (AutoTrait(a), AutoTrait(b)) if a == b => Ok(ep_a.rebind(AutoTrait(a))), . _ => Err(TypeError::ExistentialMismatch(expected_found(relation, a, b))), . } . }); 5,220 ( 0.00%) tcx.mk_poly_existential_predicates(v) 20,880 ( 0.00%) } . } . . impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> { . fn relate>( . relation: &mut R, . a: ty::ClosureSubsts<'tcx>, . b: ty::ClosureSubsts<'tcx>, . ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> { -- line 722 ---------------------------------------- -- line 737 ---------------------------------------- . } . . impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> { . fn relate>( . relation: &mut R, . a: SubstsRef<'tcx>, . b: SubstsRef<'tcx>, . ) -> RelateResult<'tcx, SubstsRef<'tcx>> { 116,909 ( 0.00%) relate_substs(relation, None, a, b) . } . } . . impl<'tcx> Relate<'tcx> for ty::Region<'tcx> { . fn relate>( . relation: &mut R, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) -> RelateResult<'tcx, ty::Region<'tcx>> { 1,395,430 ( 0.00%) relation.regions(a, b) . } . } . . impl<'tcx> Relate<'tcx> for &'tcx ty::Const<'tcx> { . fn relate>( . relation: &mut R, . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { 19,569,391 ( 0.02%) relation.consts(a, b) . } . } . . impl<'tcx, T: Relate<'tcx>> Relate<'tcx> for ty::Binder<'tcx, T> { . fn relate>( . relation: &mut R, . a: ty::Binder<'tcx, T>, . b: ty::Binder<'tcx, T>, . ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> { 159,224 ( 0.00%) relation.binders(a, b) . } . } . . impl<'tcx> Relate<'tcx> for GenericArg<'tcx> { 111,225,824 ( 0.10%) fn relate>( . relation: &mut R, . a: GenericArg<'tcx>, . b: GenericArg<'tcx>, . ) -> RelateResult<'tcx, GenericArg<'tcx>> { 134,855,748 ( 0.12%) match (a.unpack(), b.unpack()) { . (GenericArgKind::Lifetime(a_lt), GenericArgKind::Lifetime(b_lt)) => { . Ok(relation.relate(a_lt, b_lt)?.into()) . } . (GenericArgKind::Type(a_ty), GenericArgKind::Type(b_ty)) => { 31,076 ( 0.00%) Ok(relation.relate(a_ty, b_ty)?.into()) . } . (GenericArgKind::Const(a_ct), GenericArgKind::Const(b_ct)) => { . Ok(relation.relate(a_ct, b_ct)?.into()) . } . (GenericArgKind::Lifetime(unpacked), x) => { . bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x) . } . (GenericArgKind::Type(unpacked), x) => { . bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x) . } . (GenericArgKind::Const(unpacked), x) => { . bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x) . } . } 101,821,925 ( 0.09%) } . } . . impl<'tcx> Relate<'tcx> for ty::ImplPolarity { . fn relate>( . relation: &mut R, . a: ty::ImplPolarity, . b: ty::ImplPolarity, . ) -> RelateResult<'tcx, ty::ImplPolarity> { -- line 813 ---------------------------------------- -- line 815 ---------------------------------------- . Err(TypeError::PolarityMismatch(expected_found(relation, a, b))) . } else { . Ok(a) . } . } . } . . impl<'tcx> Relate<'tcx> for ty::TraitPredicate<'tcx> { 109,098 ( 0.00%) fn relate>( . relation: &mut R, . a: ty::TraitPredicate<'tcx>, . b: ty::TraitPredicate<'tcx>, . ) -> RelateResult<'tcx, ty::TraitPredicate<'tcx>> { . Ok(ty::TraitPredicate { 49,590 ( 0.00%) trait_ref: relation.relate(a.trait_ref, b.trait_ref)?, . constness: relation.relate(a.constness, b.constness)?, . polarity: relation.relate(a.polarity, b.polarity)?, . }) 89,262 ( 0.00%) } . } . . impl<'tcx> Relate<'tcx> for ty::Term<'tcx> { . fn relate>( . relation: &mut R, . a: Self, . b: Self, . ) -> RelateResult<'tcx, Self> { -- line 841 ---------------------------------------- -- line 862 ---------------------------------------- . . /////////////////////////////////////////////////////////////////////////// . // Error handling . . pub fn expected_found<'tcx, R, T>(relation: &mut R, a: T, b: T) -> ExpectedFound . where . R: TypeRelation<'tcx>, . { 18,744 ( 0.00%) ExpectedFound::new(relation.a_is_expected(), a, b) . } 832,684,866 ( 0.72%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 357 ---------------------------------------- . /// . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 144,140 ( 0.00%) pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { . Self::from_inner( 122,969,603 ( 0.11%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 144,140 ( 0.00%) } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or . /// indirectly, should not hold a strong reference to prevent a memory leak. . /// In `data_fn`, initialization of `T` can make use of the weak reference . /// by cloning and storing it inside `T` for use at a later time. -- line 383 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 84,057 ( 0.00%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1023 ---------------------------------------- . pub unsafe fn decrement_strong_count(ptr: *const T) { . unsafe { mem::drop(Rc::from_raw(ptr)) }; . } . . /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to . /// this allocation. . #[inline] . fn is_unique(this: &Self) -> bool { 13,344 ( 0.00%) Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 . } . . /// Returns a mutable reference into the given `Rc`, if there are . /// no other `Rc` or [`Weak`] pointers to the same allocation. . /// . /// Returns [`None`] otherwise, because it is not safe to . /// mutate a shared value. . /// -- line 1039 ---------------------------------------- -- line 1053 ---------------------------------------- . /// assert_eq!(*x, 4); . /// . /// let _y = Rc::clone(&x); . /// assert!(Rc::get_mut(&mut x).is_none()); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn get_mut(this: &mut Self) -> Option<&mut T> { 4,448 ( 0.00%) if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } . } . . /// Returns a mutable reference into the given `Rc`, . /// without any check. . /// . /// See also [`get_mut`], which is safe and does appropriate checks. . /// . /// [`get_mut`]: Rc::get_mut -- line 1069 ---------------------------------------- -- line 1088 ---------------------------------------- . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] . pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 15,485,177 ( 0.01%) unsafe { &mut (*this.ptr.as_ptr()).value } . } . . #[inline] . #[stable(feature = "ptr_eq", since = "1.17.0")] . /// Returns `true` if the two `Rc`s point to the same allocation . /// (in a vein similar to [`ptr::eq`]). . /// . /// # Examples -- line 1104 ---------------------------------------- -- line 1109 ---------------------------------------- . /// let five = Rc::new(5); . /// let same_five = Rc::clone(&five); . /// let other_five = Rc::new(5); . /// . /// assert!(Rc::ptr_eq(&five, &same_five)); . /// assert!(!Rc::ptr_eq(&five, &other_five)); . /// ``` . pub fn ptr_eq(this: &Self, other: &Self) -> bool { 452,636 ( 0.00%) this.ptr.as_ptr() == other.ptr.as_ptr() . } . } . . impl Rc { . /// Makes a mutable reference into the given `Rc`. . /// . /// If there are other `Rc` pointers to the same allocation, then `make_mut` will . /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also -- line 1125 ---------------------------------------- -- line 1167 ---------------------------------------- . /// *Rc::make_mut(&mut data) += 1; . /// . /// assert!(76 == *data); . /// assert!(weak.upgrade().is_none()); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] 275,248 ( 0.00%) pub fn make_mut(this: &mut Self) -> &mut T { 164,652 ( 0.00%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 40,422 ( 0.00%) let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . (**this).write_clone_into_raw(data.as_mut_ptr()); 80,844 ( 0.00%) *this = rc.assume_init(); . } 47,142 ( 0.00%) } else if Rc::weak_count(this) != 0 { . // Can just steal the data, all that's left is Weaks . let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); . . this.inner().dec_strong(); . // Remove implicit strong-weak ref (no need to craft a fake -- line 1193 ---------------------------------------- -- line 1196 ---------------------------------------- . ptr::write(this, rc.assume_init()); . } . } . // This unsafety is ok because we're guaranteed that the pointer . // returned is the *only* pointer that will ever be returned to T. Our . // reference count is guaranteed to be 1 at this point, and we required . // the `Rc` itself to be `mut`, so we're returning the only possible . // reference to the allocation. 63,993 ( 0.00%) unsafe { &mut this.ptr.as_mut().value } 330,132 ( 0.00%) } . } . . impl Rc { . #[inline] . #[stable(feature = "rc_downcast", since = "1.29.0")] . /// Attempt to downcast the `Rc` to a concrete type. . /// . /// # Examples -- line 1213 ---------------------------------------- -- line 1344 ---------------------------------------- . ) . } . } . . /// Copy elements from slice into newly allocated Rc<\[T\]> . /// . /// Unsafe because the caller must either take ownership or bind `T: Copy` . #[cfg(not(no_global_oom_handling))] 129,054 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 27,643 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 165,938 ( 0.00%) } . . /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. . /// . /// Behavior is undefined should the size be wrong. . #[cfg(not(no_global_oom_handling))] . unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Rc<[T]> { . // Panic guard while cloning T elements. . // In the event of a panic, elements that have been written -- line 1366 ---------------------------------------- -- line 1419 ---------------------------------------- . unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } . } . } . . #[cfg(not(no_global_oom_handling))] . impl RcFromSlice for Rc<[T]> { . #[inline] . fn from_slice(v: &[T]) -> Self { 13 ( 0.00%) unsafe { Rc::copy_from_slice(v) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Deref for Rc { . type Target = T; . . #[inline(always)] . fn deref(&self) -> &T { 2,489,046 ( 0.00%) &self.inner().value . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Rc {} . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { -- line 1445 ---------------------------------------- -- line 1463 ---------------------------------------- . /// } . /// . /// let foo = Rc::new(Foo); . /// let foo2 = Rc::clone(&foo); . /// . /// drop(foo); // Doesn't print anything . /// drop(foo2); // Prints "dropped!" . /// ``` 18,258,867 ( 0.02%) fn drop(&mut self) { . unsafe { 13,193,758 ( 0.01%) self.inner().dec_strong(); 96,141,229 ( 0.08%) if self.inner().strong() == 0 { . // destroy the contained object 15,416,205 ( 0.01%) ptr::drop_in_place(Self::get_mut_unchecked(self)); . . // remove the implicit "strong weak" pointer now that we've . // destroyed the contents. 1 ( 0.00%) self.inner().dec_weak(); . 35,114,833 ( 0.03%) if self.inner().weak() == 0 { 18,562 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 27,293,802 ( 0.02%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Rc { . /// Makes a clone of the `Rc` pointer. . /// . /// This creates another pointer to the same allocation, increasing the . /// strong reference count. -- line 1495 ---------------------------------------- -- line 1562 ---------------------------------------- . /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to . /// the same value, than two `&T`s. . /// . /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. . #[stable(feature = "rust1", since = "1.0.0")] . impl RcEqIdent for Rc { . #[inline] . fn eq(&self, other: &Rc) -> bool { 491,415 ( 0.00%) Rc::ptr_eq(self, other) || **self == **other . } . . #[inline] . fn ne(&self, other: &Rc) -> bool { . !Rc::ptr_eq(self, other) && **self != **other . } . } . -- line 1578 ---------------------------------------- -- line 1879 ---------------------------------------- . /// # use std::rc::Rc; . /// let original: Box> = Box::new(vec![1, 2, 3]); . /// let shared: Rc> = Rc::from(original); . /// assert_eq!(vec![1, 2, 3], *shared); . /// ``` . #[inline] . fn from(mut v: Vec) -> Rc<[T]> { . unsafe { 36,910 ( 0.00%) let rc = Rc::copy_from_slice(&v); . . // Allow the Vec to free its memory, but not destroy its contents . v.set_len(0); . . rc . } . } . } -- line 1895 ---------------------------------------- -- line 2080 ---------------------------------------- . #[must_use] . pub fn new() -> Weak { . Weak { ptr: NonNull::new(usize::MAX as *mut RcBox).expect("MAX is not 0") } . } . } . . pub(crate) fn is_dangling(ptr: *mut T) -> bool { . let address = ptr as *mut () as usize; 77 ( 0.00%) address == usize::MAX . } . . /// Helper type to allow accessing the reference counts without . /// making any assertions about the data field. . struct WeakInner<'a> { . weak: &'a Cell, . strong: &'a Cell, . } -- line 2096 ---------------------------------------- -- line 2299 ---------------------------------------- . }) . .unwrap_or(0) . } . . /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`, . /// (i.e., when this `Weak` was created by `Weak::new`). . #[inline] . fn inner(&self) -> Option> { 1 ( 0.00%) if is_dangling(self.ptr.as_ptr()) { . None . } else { . // We are careful to *not* create a reference covering the "data" field, as . // the field may be mutated concurrently (for example, if the last `Rc` . // is dropped, the data field will be dropped in-place). . Some(unsafe { . let ptr = self.ptr.as_ptr(); . WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } -- line 2315 ---------------------------------------- -- line 2391 ---------------------------------------- . /// assert!(other_weak_foo.upgrade().is_none()); . /// ``` . fn drop(&mut self) { . let inner = if let Some(inner) = self.inner() { inner } else { return }; . . inner.dec_weak(); . // the weak count starts at 1, and will only go to zero if all . // the strong pointers have disappeared. 2 ( 0.00%) if inner.weak() == 0 { . unsafe { . Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); . } . } . } . } . . #[stable(feature = "rc_weak", since = "1.4.0")] -- line 2407 ---------------------------------------- -- line 2469 ---------------------------------------- . . #[inline] . fn strong(&self) -> usize { . self.strong_ref().get() . } . . #[inline] . fn inc_strong(&self) { 32,434,162 ( 0.03%) let strong = self.strong(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at . // an otherwise missed optimization. 97,931,792 ( 0.08%) if strong == 0 || strong == usize::MAX { . abort(); . } 46,907 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 144,156,898 ( 0.12%) self.strong_ref().set(self.strong() - 1); . } . . #[inline] . fn weak(&self) -> usize { . self.weak_ref().get() . } . . #[inline] -- line 2499 ---------------------------------------- -- line 2507 ---------------------------------------- . if weak == 0 || weak == usize::MAX { . abort(); . } . self.weak_ref().set(weak + 1); . } . . #[inline] . fn dec_weak(&self) { 47,242,670 ( 0.04%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 5,517,215 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/confirmation.rs -------------------------------------------------------------------------------- Ir -- line 41 ---------------------------------------- . use super::BuiltinImplConditions; . use super::SelectionCandidate::{self, *}; . use super::SelectionContext; . . use std::iter; . use std::ops::ControlFlow; . . impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { 29,758,448 ( 0.03%) #[instrument(level = "debug", skip(self))] 37,198,060 ( 0.03%) pub(super) fn confirm_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . candidate: SelectionCandidate<'tcx>, . ) -> Result, SelectionError<'tcx>> { . let mut obligation = obligation; . let new_obligation; . . // HACK(const_trait_impl): the surrounding environment is remapped to a non-const context -- line 58 ---------------------------------------- -- line 67 ---------------------------------------- . // ``` . // . // The procedure to check the code above without the remapping code is as follows: . // ``` . // CheckWf(impl const Sub for &A where A: ~const Sub) // <- const env . // CheckPredicate(&A: Super) . // CheckPredicate(A: ~const Super) // <- still const env, failure . // ``` 7,441,438 ( 0.01%) if obligation.param_env.constness() == Constness::Const . && obligation.predicate.skip_binder().constness == ty::BoundConstness::NotConst . { 16,016 ( 0.00%) new_obligation = TraitObligation { . cause: obligation.cause.clone(), 1,878 ( 0.00%) param_env: obligation.param_env.without_const(), . ..*obligation . }; . obligation = &new_obligation; . } . 18,600,031 ( 0.02%) match candidate { 263,280 ( 0.00%) BuiltinCandidate { has_nested } => { . let data = self.confirm_builtin_candidate(obligation, has_nested); 421,248 ( 0.00%) Ok(ImplSource::Builtin(data)) . } . . ParamCandidate(param) => { . let obligations = 602,344 ( 0.00%) self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref)); 2,108,204 ( 0.00%) Ok(ImplSource::Param(obligations, param.skip_binder().constness)) . } . 9,988,287 ( 0.01%) ImplCandidate(impl_def_id) => { 29,964,861 ( 0.03%) Ok(ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))) . } . 2,388 ( 0.00%) AutoImplCandidate(trait_def_id) => { . let data = self.confirm_auto_impl_candidate(obligation, trait_def_id); 9,552 ( 0.00%) Ok(ImplSource::AutoImpl(data)) . } . 89,151 ( 0.00%) ProjectionCandidate(idx) => { 59,434 ( 0.00%) let obligations = self.confirm_projection_candidate(obligation, idx)?; . // FIXME(jschievink): constness 267,453 ( 0.00%) Ok(ImplSource::Param(obligations, ty::BoundConstness::NotConst)) . } . . ObjectCandidate(idx) => { . let data = self.confirm_object_candidate(obligation, idx)?; . Ok(ImplSource::Object(data)) . } . . ClosureCandidate => { . let vtable_closure = self.confirm_closure_candidate(obligation)?; 6,600 ( 0.00%) Ok(ImplSource::Closure(vtable_closure)) . } . . GeneratorCandidate => { . let vtable_generator = self.confirm_generator_candidate(obligation)?; . Ok(ImplSource::Generator(vtable_generator)) . } . . FnPointerCandidate { .. } => { . let data = self.confirm_fn_pointer_candidate(obligation)?; 348 ( 0.00%) Ok(ImplSource::FnPointer(data)) . } . . DiscriminantKindCandidate => { . Ok(ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)) . } . . PointeeCandidate => Ok(ImplSource::Pointee(ImplSourcePointeeData)), . -- line 138 ---------------------------------------- -- line 145 ---------------------------------------- . // This indicates something like `Trait + Send: Send`. In this case, we know that . // this holds because that's what the object type is telling us, and there's really . // no additional obligations to prove and no types in particular to unify, etc. . Ok(ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)) . } . . BuiltinUnsizeCandidate => { . let data = self.confirm_builtin_unsize_candidate(obligation)?; 18,848 ( 0.00%) Ok(ImplSource::Builtin(data)) . } . . TraitUpcastingUnsizeCandidate(idx) => { . let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?; . Ok(ImplSource::TraitUpcasting(data)) . } . . ConstDropCandidate(def_id) => { . let data = self.confirm_const_drop_candidate(obligation, def_id)?; 1,818 ( 0.00%) Ok(ImplSource::ConstDrop(data)) . } . } 11,155,733 ( 0.01%) } . . fn confirm_projection_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . idx: usize, . ) -> Result>, SelectionError<'tcx>> { 267,453 ( 0.00%) self.infcx.commit_unconditionally(|_| { . let tcx = self.tcx(); . . let trait_predicate = self.infcx.shallow_resolve(obligation.predicate); . let placeholder_trait_predicate = . self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref; 29,717 ( 0.00%) let placeholder_self_ty = placeholder_trait_predicate.self_ty(); . let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate); 89,151 ( 0.00%) let (def_id, substs) = match *placeholder_self_ty.kind() { 118,868 ( 0.00%) ty::Projection(proj) => (proj.item_def_id, proj.substs), . ty::Opaque(def_id, substs) => (def_id, substs), . _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty), . }; . 148,585 ( 0.00%) let candidate_predicate = tcx.item_bounds(def_id)[idx].subst(tcx, substs); 59,434 ( 0.00%) let candidate = candidate_predicate . .to_opt_poly_trait_pred() . .expect("projection candidate is not a trait predicate") . .map_bound(|t| t.trait_ref); . let mut obligations = Vec::new(); 267,453 ( 0.00%) let candidate = normalize_with_depth_to( . self, 29,717 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 89,151 ( 0.00%) obligation.recursion_depth + 1, 89,151 ( 0.00%) candidate, . &mut obligations, . ); . 59,434 ( 0.00%) obligations.extend(self.infcx.commit_if_ok(|_| { . self.infcx 29,717 ( 0.00%) .at(&obligation.cause, obligation.param_env) . .sup(placeholder_trait_predicate, candidate) . .map(|InferOk { obligations, .. }| obligations) . .map_err(|_| Unimplemented) . })?); . 118,868 ( 0.00%) if let ty::Projection(..) = placeholder_self_ty.kind() { 148,585 ( 0.00%) let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates; . debug!(?predicates, "projection predicates"); 118,868 ( 0.00%) for predicate in predicates { . let normalized = normalize_with_depth_to( . self, . obligation.param_env, . obligation.cause.clone(), . obligation.recursion_depth + 1, . predicate, . &mut obligations, . ); -- line 221 ---------------------------------------- -- line 223 ---------------------------------------- . obligation.cause.clone(), . obligation.recursion_depth + 1, . obligation.param_env, . normalized, . )); . } . } . 148,585 ( 0.00%) Ok(obligations) . }) . } . . fn confirm_param_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . param: ty::PolyTraitRef<'tcx>, . ) -> Vec> { . debug!(?obligation, ?param, "confirm_param_candidate"); . . // During evaluation, we already checked that this . // where-clause trait-ref could be unified with the obligation . // trait-ref. Repeat that unification now without any . // transactional boundary; it should not fail. 1,807,032 ( 0.00%) match self.match_where_clause_trait_ref(obligation, param) { 602,344 ( 0.00%) Ok(obligations) => obligations, . Err(()) => { . bug!( . "Where clause `{:?}` was applicable to `{:?}` but now is not", . param, . obligation . ); . } . } -- line 255 ---------------------------------------- -- line 257 ---------------------------------------- . . fn confirm_builtin_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . has_nested: bool, . ) -> ImplSourceBuiltinData> { . debug!(?obligation, ?has_nested, "confirm_builtin_candidate"); . 52,656 ( 0.00%) let lang_items = self.tcx().lang_items(); 52,656 ( 0.00%) let obligations = if has_nested { 18,760 ( 0.00%) let trait_def = obligation.predicate.def_id(); 8,878 ( 0.00%) let conditions = if Some(trait_def) == lang_items.sized_trait() { 3,250 ( 0.00%) self.sized_conditions(obligation) 1,199 ( 0.00%) } else if Some(trait_def) == lang_items.copy_trait() { 669 ( 0.00%) self.copy_clone_conditions(obligation) 140 ( 0.00%) } else if Some(trait_def) == lang_items.clone_trait() { 112 ( 0.00%) self.copy_clone_conditions(obligation) . } else { . bug!("unexpected builtin trait {:?}", trait_def) . }; 3,752 ( 0.00%) let nested = match conditions { 7,504 ( 0.00%) BuiltinImplConditions::Where(nested) => nested, . _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation), . }; . . let cause = obligation.derived_cause(BuiltinDerivedObligation); 30,016 ( 0.00%) ensure_sufficient_stack(|| { 13,132 ( 0.00%) self.collect_predicates_for_types( 3,752 ( 0.00%) obligation.param_env, 5,628 ( 0.00%) cause, 5,628 ( 0.00%) obligation.recursion_depth + 1, 5,628 ( 0.00%) trait_def, 11,256 ( 0.00%) nested, . ) . }) . } else { . vec![] . }; . . debug!(?obligations); . 210,624 ( 0.00%) ImplSourceBuiltinData { nested: obligations } . } . . /// This handles the case where an `auto trait Foo` impl is being used. . /// The idea is that the impl applies to `X : Foo` if the following conditions are met: . /// . /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds . /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds. . fn confirm_auto_impl_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . trait_def_id: DefId, . ) -> ImplSourceAutoImplData> { . debug!(?obligation, ?trait_def_id, "confirm_auto_impl_candidate"); . 6,368 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty()); . let types = self.constituent_types_for_ty(self_ty); . self.vtable_auto_impl(obligation, trait_def_id, types) . } . . /// See `confirm_auto_impl_candidate`. . fn vtable_auto_impl( . &mut self, . obligation: &TraitObligation<'tcx>, . trait_def_id: DefId, . nested: ty::Binder<'tcx, Vec>>, . ) -> ImplSourceAutoImplData> { . debug!(?nested, "vtable_auto_impl"); 12,736 ( 0.00%) ensure_sufficient_stack(|| { 796 ( 0.00%) let cause = obligation.derived_cause(BuiltinDerivedObligation); 4,776 ( 0.00%) let mut obligations = self.collect_predicates_for_types( 796 ( 0.00%) obligation.param_env, 3,980 ( 0.00%) cause, 2,388 ( 0.00%) obligation.recursion_depth + 1, 2,388 ( 0.00%) trait_def_id, 4,776 ( 0.00%) nested, . ); . . let trait_obligations: Vec> = 5,572 ( 0.00%) self.infcx.commit_unconditionally(|_| { 3,184 ( 0.00%) let poly_trait_ref = obligation.predicate.to_poly_trait_ref(); 6,368 ( 0.00%) let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref); . let cause = obligation.derived_cause(ImplDerivedObligation); 3,184 ( 0.00%) self.impl_or_trait_obligations( 3,184 ( 0.00%) cause, 2,388 ( 0.00%) obligation.recursion_depth + 1, 1,592 ( 0.00%) obligation.param_env, 3,980 ( 0.00%) trait_def_id, . &trait_ref.substs, . ) . }); . . // Adds the predicates from the trait. Note that this contains a `Self: Trait` . // predicate as usual. It won't have any effect since auto traits are coinductive. . obligations.extend(trait_obligations); . . debug!(?obligations, "vtable_auto_impl"); . 5,572 ( 0.00%) ImplSourceAutoImplData { trait_def_id, nested: obligations } . }) . } . . fn confirm_impl_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . impl_def_id: DefId, . ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> { . debug!(?obligation, ?impl_def_id, "confirm_impl_candidate"); . . // First, create the substitutions by matching the impl again, . // this time not in a probe. 29,964,861 ( 0.03%) self.infcx.commit_unconditionally(|_| { 19,976,574 ( 0.02%) let substs = self.rematch_impl(impl_def_id, obligation); . debug!(?substs, "impl substs"); . let cause = obligation.derived_cause(ImplDerivedObligation); 49,941,435 ( 0.04%) ensure_sufficient_stack(|| { 19,976,574 ( 0.02%) self.vtable_impl( 6,658,858 ( 0.01%) impl_def_id, 13,317,716 ( 0.01%) substs, 13,317,716 ( 0.01%) cause, 9,988,287 ( 0.01%) obligation.recursion_depth + 1, . obligation.param_env, . ) . }) . }) . } . 43,282,577 ( 0.04%) fn vtable_impl( . &mut self, . impl_def_id: DefId, . substs: Normalized<'tcx, SubstsRef<'tcx>>, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . param_env: ty::ParamEnv<'tcx>, . ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> { . debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl"); . 23,306,003 ( 0.02%) let mut impl_obligations = self.impl_or_trait_obligations( 13,317,716 ( 0.01%) cause, . recursion_depth, . param_env, . impl_def_id, 13,317,716 ( 0.01%) &substs.value, . ); . . debug!(?impl_obligations, "vtable_impl"); . . // Because of RFC447, the impl-trait-ref and obligations . // are sufficient to determine the impl substs, without . // relying on projections in the impl-trait-ref. . // . // e.g., `impl> Foo<::T> for V` . impl_obligations.extend(substs.obligations); . 33,294,290 ( 0.03%) ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations } 29,964,861 ( 0.03%) } . . fn confirm_object_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . index: usize, . ) -> Result>, SelectionError<'tcx>> { . let tcx = self.tcx(); . debug!(?obligation, ?index, "confirm_object_candidate"); -- line 421 ---------------------------------------- -- line 539 ---------------------------------------- . fn confirm_fn_pointer_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> Result>, SelectionError<'tcx>> . { . debug!(?obligation, "confirm_fn_pointer_candidate"); . . // Okay to skip binder; it is reintroduced below. 174 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); 58 ( 0.00%) let sig = self_ty.fn_sig(self.tcx()); 522 ( 0.00%) let trait_ref = closure_trait_ref_and_return_type( . self.tcx(), 348 ( 0.00%) obligation.predicate.def_id(), . self_ty, 232 ( 0.00%) sig, . util::TupleArgumentsFlag::Yes, . ) . .map_bound(|(trait_ref, _)| trait_ref); . 928 ( 0.00%) let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| { . normalize_with_depth( . self, 58 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 174 ( 0.00%) obligation.recursion_depth + 1, 232 ( 0.00%) trait_ref, . ) . }); . . obligations.extend(self.confirm_poly_trait_refs( . obligation.cause.clone(), 58 ( 0.00%) obligation.param_env, 58 ( 0.00%) obligation.predicate.to_poly_trait_ref(), . trait_ref, . )?); 116 ( 0.00%) Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested: obligations }) . } . . fn confirm_trait_alias_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . alias_def_id: DefId, . ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> { . debug!(?obligation, ?alias_def_id, "confirm_trait_alias_candidate"); -- line 582 ---------------------------------------- -- line 640 ---------------------------------------- . Ok(ImplSourceGeneratorData { generator_def_id, substs, nested: obligations }) . } . . #[instrument(skip(self), level = "debug")] . fn confirm_closure_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> Result>, SelectionError<'tcx>> { 3,300 ( 0.00%) let kind = self . .tcx() 4,950 ( 0.00%) .fn_trait_kind_from_lang_item(obligation.predicate.def_id()) . .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation)); . . // Okay to skip binder because the substs on closure types never . // touch bound regions, they just capture the in-scope . // type/region parameters. 825 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); 1,650 ( 0.00%) let (closure_def_id, substs) = match *self_ty.kind() { 4,950 ( 0.00%) ty::Closure(id, substs) => (id, substs), . _ => bug!("closure candidate for non-closure {:?}", obligation), . }; . 4,125 ( 0.00%) let obligation_predicate = obligation.predicate; 7,425 ( 0.00%) let Normalized { value: obligation_predicate, mut obligations } = 5,775 ( 0.00%) ensure_sufficient_stack(|| { 2,475 ( 0.00%) normalize_with_depth( . self, 825 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 2,475 ( 0.00%) obligation.recursion_depth + 1, 4,950 ( 0.00%) obligation_predicate, . ) . }); . . let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs); 6,600 ( 0.00%) let Normalized { value: trait_ref, obligations: trait_ref_obligations } = 6,600 ( 0.00%) ensure_sufficient_stack(|| { . normalize_with_depth( . self, 825 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 2,475 ( 0.00%) obligation.recursion_depth + 1, 3,300 ( 0.00%) trait_ref, . ) . }); . . debug!(?closure_def_id, ?trait_ref, ?obligations, "confirm closure candidate obligations"); . . obligations.extend(trait_ref_obligations); . obligations.extend(self.confirm_poly_trait_refs( . obligation.cause.clone(), 2,475 ( 0.00%) obligation.param_env, 825 ( 0.00%) obligation_predicate.to_poly_trait_ref(), . trait_ref, . )?); . . // FIXME: Chalk . 2,475 ( 0.00%) if !self.tcx().sess.opts.debugging_opts.chalk { . obligations.push(Obligation::new( . obligation.cause.clone(), 825 ( 0.00%) obligation.param_env, 8,250 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)) . .to_predicate(self.tcx()), . )); . } . 1,650 ( 0.00%) Ok(ImplSourceClosureData { closure_def_id, substs, nested: obligations }) . } . . /// In the case of closure types and fn pointers, . /// we currently treat the input type parameters on the trait as . /// outputs. This means that when we have a match we have only . /// considered the self type, so we have to go back and make sure . /// to relate the argument types too. This is kind of wrong, but . /// since we control the full set of impls, also not that wrong, -- line 715 ---------------------------------------- -- line 735 ---------------------------------------- . #[instrument(skip(self), level = "trace")] . fn confirm_poly_trait_refs( . &mut self, . obligation_cause: ObligationCause<'tcx>, . obligation_param_env: ty::ParamEnv<'tcx>, . obligation_trait_ref: ty::PolyTraitRef<'tcx>, . expected_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, SelectionError<'tcx>> { 883 ( 0.00%) self.infcx . .at(&obligation_cause, obligation_param_env) . .sup(obligation_trait_ref, expected_trait_ref) . .map(|InferOk { obligations, .. }| obligations) . .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e)) . } . . fn confirm_trait_upcasting_unsize_candidate( . &mut self, -- line 751 ---------------------------------------- -- line 854 ---------------------------------------- . . Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested }) . } . . fn confirm_builtin_unsize_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> Result>, SelectionError<'tcx>> { 8,488 ( 0.00%) let tcx = self.tcx(); . . // `assemble_candidates_for_unsizing` should ensure there are no late-bound . // regions here. See the comment there for more details. 4,244 ( 0.00%) let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap()); 12,732 ( 0.00%) let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1); . let target = self.infcx.shallow_resolve(target); . . debug!(?source, ?target, "confirm_builtin_unsize_candidate"); . . let mut nested = vec![]; 49,820 ( 0.00%) match (source.kind(), target.kind()) { . // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping). . (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => { . // See `assemble_candidates_for_unsizing` for more info. . // We already checked the compatiblity of auto traits within `assemble_candidates_for_unsizing`. . let iter = data_a . .principal() . .map(|b| b.map_bound(ty::ExistentialPredicate::Trait)) . .into_iter() -- line 881 ---------------------------------------- -- line 913 ---------------------------------------- . cause, . obligation.recursion_depth + 1, . obligation.param_env, . obligation.predicate.rebind(outlives).to_predicate(tcx), . )); . } . . // `T` -> `Trait` 1,662 ( 0.00%) (_, &ty::Dynamic(ref data, r)) => { 1,662 ( 0.00%) let mut object_dids = data.auto_traits().chain(data.principal_def_id()); 2,216 ( 0.00%) if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) { . return Err(TraitNotObjectSafe(did)); . } . . let cause = ObligationCause::new( 554 ( 0.00%) obligation.cause.span, 1,108 ( 0.00%) obligation.cause.body_id, 1,108 ( 0.00%) ObjectCastObligation(target), . ); . 1,662 ( 0.00%) let predicate_to_obligation = |predicate| { . Obligation::with_depth( 1,662 ( 0.00%) cause.clone(), 6,648 ( 0.00%) obligation.recursion_depth + 1, 1,662 ( 0.00%) obligation.param_env, . predicate, . ) . }; . . // Create obligations: . // - Casting `T` to `Trait` . // - For all the various builtin bounds attached to the object cast. (In other . // words, if the object type is `Foo + Send`, this would create an obligation for . // the `Send` check.) . // - Projection predicates . nested.extend( 554 ( 0.00%) data.iter().map(|predicate| { 1,662 ( 0.00%) predicate_to_obligation(predicate.with_self_ty(tcx, source)) . }), . ); . . // We can only make objects from sized types. 3,324 ( 0.00%) let tr = ty::Binder::dummy(ty::TraitRef::new( 2,770 ( 0.00%) tcx.require_lang_item(LangItem::Sized, None), 2,770 ( 0.00%) tcx.mk_substs_trait(source, &[]), . )); 1,662 ( 0.00%) nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx))); . . // If the type is `Foo + 'a`, ensure that the type . // being cast to `Foo + 'a` outlives `'a`: . let outlives = ty::OutlivesPredicate(source, r); 1,662 ( 0.00%) nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx))); . } . . // `[T; n]` -> `[T]` 1,911 ( 0.00%) (&ty::Array(a, _), &ty::Slice(b)) => { 637 ( 0.00%) let InferOk { obligations, .. } = self . .infcx 637 ( 0.00%) .at(&obligation.cause, obligation.param_env) . .eq(b, a) . .map_err(|_| Unimplemented)?; . nested.extend(obligations); . } . . // `Struct` -> `Struct` 18,318 ( 0.00%) (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => { . let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() { 27,942 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { 7,000 ( 0.00%) ty::Param(p) => Some(p.index), . _ => None, . }, . . // Lifetimes aren't allowed to change during unsizing. . GenericArgKind::Lifetime(_) => None, . 574 ( 0.00%) GenericArgKind::Const(ct) => match ct.val { 216 ( 0.00%) ty::ConstKind::Param(p) => Some(p.index), . _ => None, . }, . }; . . // FIXME(eddyb) cache this (including computing `unsizing_params`) . // by putting it in a query; it would only need the `DefId` as it . // looks at declared field types, not anything substituted. . . // The last field of the structure has to exist and contain type/const parameters. . let (tail_field, prefix_fields) = 3,053 ( 0.00%) def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?; 12,762 ( 0.00%) let tail_field_ty = tcx.type_of(tail_field.did); . . let mut unsizing_params = GrowableBitSet::new_empty(); 52,013 ( 0.00%) for arg in tail_field_ty.walk() { . if let Some(i) = maybe_unsizing_param_idx(arg) { . unsizing_params.insert(i); . } . } . . // Ensure none of the other fields mention the parameters used . // in unsizing. . for field in prefix_fields { 127,450 ( 0.00%) for arg in tcx.type_of(field.did).walk() { . if let Some(i) = maybe_unsizing_param_idx(arg) { . unsizing_params.remove(i); . } . } . } . . if unsizing_params.is_empty() { . return Err(Unimplemented); . } . . // Extract `TailField` and `TailField` from `Struct` and `Struct`. 2,330 ( 0.00%) let source_tail = tail_field_ty.subst(tcx, substs_a); 2,330 ( 0.00%) let target_tail = tail_field_ty.subst(tcx, substs_b); . . // Check that the source struct with the target's . // unsizing parameters is equal to the target. 2,330 ( 0.00%) let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| { 14,095 ( 0.00%) if unsizing_params.contains(i as u32) { substs_b[i] } else { k } . })); 1,165 ( 0.00%) let new_struct = tcx.mk_adt(def, substs); 9,320 ( 0.00%) let InferOk { obligations, .. } = self . .infcx 1,165 ( 0.00%) .at(&obligation.cause, obligation.param_env) . .eq(target, new_struct) . .map_err(|_| Unimplemented)?; 9,320 ( 0.00%) nested.extend(obligations); . . // Construct the nested `TailField: Unsize>` predicate. 13,980 ( 0.00%) nested.push(predicate_for_trait_def( 2,330 ( 0.00%) tcx, 1,165 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 6,990 ( 0.00%) obligation.predicate.def_id(), 3,495 ( 0.00%) obligation.recursion_depth + 1, . source_tail, 3,495 ( 0.00%) &[target_tail.into()], . )); 2,330 ( 0.00%) } . . // `(.., T)` -> `(.., U)` . (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => { . assert_eq!(tys_a.len(), tys_b.len()); . . // The last field of the tuple has to exist. . let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?; . let &b_last = tys_b.last().unwrap(); -- line 1059 ---------------------------------------- -- line 1082 ---------------------------------------- . &[b_last], . ) . })); . } . . _ => bug!(), . }; . 16,492 ( 0.00%) Ok(ImplSourceBuiltinData { nested }) . } . . fn confirm_const_drop_candidate( . &mut self, . obligation: &TraitObligation<'tcx>, . impl_def_id: Option, . ) -> Result>, SelectionError<'tcx>> { . // `~const Drop` in a non-const environment is always trivially true, since our type is `Drop` . if obligation.param_env.constness() == Constness::NotConst { . return Ok(ImplSourceConstDropData { nested: vec![] }); . } . 1,650 ( 0.00%) let tcx = self.tcx(); 2,475 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.self_ty()); . . let mut nested = vec![]; . let cause = obligation.derived_cause(BuiltinDerivedObligation); . . // If we have a custom `impl const Drop`, then . // first check it like a regular impl candidate 1,650 ( 0.00%) if let Some(impl_def_id) = impl_def_id { . nested.extend(self.confirm_impl_candidate(obligation, impl_def_id).nested); . } . . // We want to confirm the ADT's fields if we have an ADT 2,475 ( 0.00%) let mut stack = match *self_ty.skip_binder().kind() { 3,280 ( 0.00%) ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(), 324 ( 0.00%) _ => vec![self_ty.skip_binder()], . }; . 3,108 ( 0.00%) while let Some(nested_ty) = stack.pop() { 4,662 ( 0.00%) match *nested_ty.kind() { . // We know these types are trivially drop . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) -- line 1130 ---------------------------------------- -- line 1185 ---------------------------------------- . )); . }); . } . . // If we have any other type (e.g. an ADT), just register a nested obligation . // since it's either not `const Drop` (and we raise an error during selection), . // or it's an ADT (and we need to check for a custom impl during selection) . _ => { 1,704 ( 0.00%) let predicate = self_ty . .rebind(ty::TraitPredicate { . trait_ref: ty::TraitRef { 3,408 ( 0.00%) def_id: self.tcx().require_lang_item(LangItem::Drop, None), 3,408 ( 0.00%) substs: self.tcx().mk_substs_trait(nested_ty, &[]), . }, . constness: ty::BoundConstness::ConstIfConst, . polarity: ty::ImplPolarity::Positive, . }) 852 ( 0.00%) .to_predicate(tcx); . . nested.push(Obligation::with_depth( . cause.clone(), 2,556 ( 0.00%) obligation.recursion_depth + 1, 852 ( 0.00%) obligation.param_env, . predicate, . )); . } . } . } . 2,475 ( 0.00%) Ok(ImplSourceConstDropData { nested }) . } . } 52,262,758 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/bit.rs -------------------------------------------------------------------------------- Ir -- line 267 ---------------------------------------- . macro_rules! bitor_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ops", issue = "90080")] . impl const BitOr for $t { . type Output = $t; . . #[inline] 37,373 ( 0.00%) fn bitor(self, rhs: $t) -> $t { self | rhs } . } . . forward_ref_binop! { impl const BitOr, bitor for $t, $t } . )*) . } . . bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } . -- line 283 ---------------------------------------- -- line 368 ---------------------------------------- . macro_rules! bitxor_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ops", issue = "90080")] . impl const BitXor for $t { . type Output = $t; . . #[inline] 291,754,622 ( 0.25%) fn bitxor(self, other: $t) -> $t { self ^ other } . } . . forward_ref_binop! { impl const BitXor, bitxor for $t, $t } . )*) . } . . bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } . -- line 384 ---------------------------------------- -- line 468 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ops", issue = "90080")] . impl const Shl<$f> for $t { . type Output = $t; . . #[inline] . #[rustc_inherit_overflow_checks] . fn shl(self, other: $f) -> $t { 118 ( 0.00%) self << other . } . } . . forward_ref_binop! { impl const Shl, shl for $t, $f } . }; . } . . macro_rules! shl_impl_all { -- line 484 ---------------------------------------- 95,161,014 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/value.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . // the value lives here, at offset 0, and that allocation definitely is an `AllocKind::Memory` . // (so you can use `AllocMap::unwrap_memory`). . pub alloc_id: AllocId, . pub ty: Ty<'tcx>, . } . . /// Represents a constant value in Rust. `Scalar` and `Slice` are optimizations for . /// array length computations, enum discriminants and the pattern matching logic. 282,671,101 ( 0.24%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Hash)] 182 ( 0.00%) #[derive(HashStable)] . pub enum ConstValue<'tcx> { . /// Used only for types with `layout::abi::Scalar` ABI and ZSTs. . /// . /// Not using the enum `Value` to encode that this must not be `Uninit`. . Scalar(Scalar), . . /// Used only for `&[u8]` and `&str` 10,691 ( 0.00%) Slice { data: &'tcx Allocation, start: usize, end: usize }, . . /// A value not represented/representable by `Scalar` or `Slice` . ByRef { . /// The backing memory of the value, may contain more memory than needed for just the value . /// in order to share `Allocation`s between values 1 ( 0.00%) alloc: &'tcx Allocation, . /// Offset into `alloc` . offset: Size, . }, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(ConstValue<'_>, 32); . -- line 51 ---------------------------------------- -- line 62 ---------------------------------------- . } . }) . } . } . . impl<'tcx> ConstValue<'tcx> { . #[inline] . pub fn try_to_scalar(&self) -> Option> { 19,974 ( 0.00%) match *self { . ConstValue::ByRef { .. } | ConstValue::Slice { .. } => None, 2,853 ( 0.00%) ConstValue::Scalar(val) => Some(val), . } . } . . pub fn try_to_scalar_int(&self) -> Option { . Some(self.try_to_scalar()?.assert_int()) . } . 154 ( 0.00%) pub fn try_to_bits(&self, size: Size) -> Option { 1,309 ( 0.00%) self.try_to_scalar_int()?.to_bits(size).ok() 231 ( 0.00%) } . . pub fn try_to_bool(&self) -> Option { . self.try_to_scalar_int()?.try_into().ok() . } . 4,992 ( 0.00%) pub fn try_to_machine_usize(&self, tcx: TyCtxt<'tcx>) -> Option { 37,440 ( 0.00%) self.try_to_scalar_int()?.try_to_machine_usize(tcx).ok() 7,488 ( 0.00%) } . 770 ( 0.00%) pub fn try_to_bits_for_ty( . &self, . tcx: TyCtxt<'tcx>, . param_env: ParamEnv<'tcx>, . ty: Ty<'tcx>, . ) -> Option { 231 ( 0.00%) let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size; 154 ( 0.00%) self.try_to_bits(size) 616 ( 0.00%) } . . pub fn from_bool(b: bool) -> Self { . ConstValue::Scalar(Scalar::from_bool(b)) . } . . pub fn from_u64(i: u64) -> Self { . ConstValue::Scalar(Scalar::from_u64(i)) . } -- line 108 ---------------------------------------- -- line 114 ---------------------------------------- . . /// A `Scalar` represents an immediate, primitive value existing outside of a . /// `memory::Allocation`. It is in many ways like a small chunk of an `Allocation`, up to 16 bytes in . /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes . /// of a simple value or a pointer into another `Allocation` . /// . /// These variants would be private if there was a convenient way to achieve that in Rust. . /// Do *not* match on a `Scalar`! Use the various `to_*` methods instead. 90,404,735 ( 0.08%) #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)] 28 ( 0.00%) #[derive(HashStable)] . pub enum Scalar { . /// The raw bytes of a simple value. 41,476,962 ( 0.04%) Int(ScalarInt), . . /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of . /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the . /// relocation and its associated offset together as a `Pointer` here. . /// . /// We also store the size of the pointer, such that a `Scalar` always knows how big it is. . /// The size is always the pointer size of the current target, but this is not information . /// that we always have readily available. 2 ( 0.00%) Ptr(Pointer, u8), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Scalar, 24); . . // We want the `Debug` output to be readable as it is used by `derive(Debug)` for . // all the Miri types. . impl fmt::Debug for Scalar { -- line 143 ---------------------------------------- -- line 179 ---------------------------------------- . } . } . . impl Scalar { . pub const ZST: Self = Scalar::Int(ScalarInt::ZST); . . #[inline(always)] . pub fn from_pointer(ptr: Pointer, cx: &impl HasDataLayout) -> Self { 4,111 ( 0.00%) Scalar::Ptr(ptr, u8::try_from(cx.pointer_size().bytes()).unwrap()) . } . . /// Create a Scalar from a pointer with an `Option<_>` tag (where `None` represents a plain integer). 90 ( 0.00%) pub fn from_maybe_pointer(ptr: Pointer>, cx: &impl HasDataLayout) -> Self { 90 ( 0.00%) match ptr.into_parts() { . (Some(tag), offset) => Scalar::from_pointer(Pointer::new(tag, offset), cx), . (None, offset) => { . Scalar::Int(ScalarInt::try_from_uint(offset.bytes(), cx.pointer_size()).unwrap()) . } . } 180 ( 0.00%) } . . #[inline] . pub fn null_ptr(cx: &impl HasDataLayout) -> Self { . Scalar::Int(ScalarInt::null(cx.pointer_size())) . } . . #[inline] . pub fn from_bool(b: bool) -> Self { -- line 206 ---------------------------------------- -- line 213 ---------------------------------------- . } . . #[inline] . pub fn try_from_uint(i: impl Into, size: Size) -> Option { . ScalarInt::try_from_uint(i, size).map(Scalar::Int) . } . . #[inline] 641 ( 0.00%) pub fn from_uint(i: impl Into, size: Size) -> Self { 51,530 ( 0.00%) let i = i.into(); . Self::try_from_uint(i, size) . .unwrap_or_else(|| bug!("Unsigned value {:#x} does not fit in {} bits", i, size.bits())) 643 ( 0.00%) } . . #[inline] . pub fn from_u8(i: u8) -> Self { . Scalar::Int(i.into()) . } . . #[inline] . pub fn from_u16(i: u16) -> Self { -- line 233 ---------------------------------------- -- line 241 ---------------------------------------- . . #[inline] . pub fn from_u64(i: u64) -> Self { . Scalar::Int(i.into()) . } . . #[inline] . pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self { 1,300 ( 0.00%) Self::from_uint(i, cx.data_layout().pointer_size) . } . . #[inline] . pub fn try_from_int(i: impl Into, size: Size) -> Option { . ScalarInt::try_from_int(i, size).map(Scalar::Int) . } . . #[inline] -- line 257 ---------------------------------------- -- line 278 ---------------------------------------- . . #[inline] . pub fn from_f32(f: Single) -> Self { . Scalar::Int(f.into()) . } . . #[inline] . pub fn from_f64(f: Double) -> Self { 488 ( 0.00%) Scalar::Int(f.into()) . } . . /// This is almost certainly not the method you want! You should dispatch on the type . /// and use `to_{u8,u16,...}`/`scalar_to_ptr` to perform ptr-to-int / int-to-ptr casts as needed. . /// . /// This method only exists for the benefit of low-level operations that truly need to treat the . /// scalar in whatever form it is. . #[inline] . pub fn to_bits_or_ptr_internal(self, target_size: Size) -> Result> { 5,028 ( 0.00%) assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST"); 3,352 ( 0.00%) match self { 10,320 ( 0.00%) Scalar::Int(int) => Ok(int.assert_bits(target_size)), 36 ( 0.00%) Scalar::Ptr(ptr, sz) => { 64 ( 0.00%) assert_eq!(target_size.bytes(), u64::from(sz)); . Err(ptr) . } . } . } . } . . impl<'tcx, Tag: Provenance> Scalar { . /// Fundamental scalar-to-int (cast) operation. Many convenience wrappers exist below, that you . /// likely want to use instead. . /// . /// Will perform ptr-to-int casts if needed and possible. . /// If that fails, we know the offset is relative, so we return an "erased" Scalar . /// (which is useful for error messages but not much else). . #[inline] . pub fn try_to_int(self) -> Result> { 58,129 ( 0.00%) match self { 126 ( 0.00%) Scalar::Int(int) => Ok(int), . Scalar::Ptr(ptr, sz) => { . if Tag::OFFSET_IS_ADDR { . Ok(ScalarInt::try_from_uint(ptr.offset.bytes(), Size::from_bytes(sz)).unwrap()) . } else { . // We know `offset` is relative, since `OFFSET_IS_ADDR == false`. . let (tag, offset) = ptr.into_parts(); . Err(Scalar::Ptr(Pointer::new(tag.get_alloc_id(), offset), sz)) . } . } . } . } . . #[inline(always)] . pub fn assert_int(self) -> ScalarInt { 8,833 ( 0.00%) self.try_to_int().unwrap() . } . . /// This throws UB (instead of ICEing) on a size mismatch since size mismatches can arise in . /// Miri when someone declares a function that we shim (such as `malloc`) with a wrong type. . #[inline] 324 ( 0.00%) pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> { 11,112 ( 0.00%) assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST"); 76,712 ( 0.00%) self.try_to_int().map_err(|_| err_unsup!(ReadPointerAsBytes))?.to_bits(target_size).map_err( . |size| { . err_ub!(ScalarSizeMismatch { . target_size: target_size.bytes(), . data_size: size.bytes(), . }) . .into() . }, . ) 405 ( 0.00%) } . . #[inline(always)] . pub fn assert_bits(self, target_size: Size) -> u128 { 441 ( 0.00%) self.to_bits(target_size).unwrap() . } . 2,068 ( 0.00%) pub fn to_bool(self) -> InterpResult<'tcx, bool> { 4,585 ( 0.00%) let val = self.to_u8()?; 3,186 ( 0.00%) match val { . 0 => Ok(false), . 1 => Ok(true), . _ => throw_ub!(InvalidBool(val)), . } 11,731 ( 0.00%) } . . pub fn to_char(self) -> InterpResult<'tcx, char> { . let val = self.to_u32()?; . match std::char::from_u32(val) { . Some(c) => Ok(c), . None => throw_ub!(InvalidChar(val)), . } . } . . #[inline] . fn to_unsigned_with_bit_width(self, bits: u64) -> InterpResult<'static, u128> { . let sz = Size::from_bits(bits); 5,786 ( 0.00%) self.to_bits(sz) . } . . /// Converts the scalar to produce a `u8`. Fails if the scalar is a pointer. 2,620 ( 0.00%) pub fn to_u8(self) -> InterpResult<'static, u8> { . self.to_unsigned_with_bit_width(8).map(|v| u8::try_from(v).unwrap()) 3,275 ( 0.00%) } . . /// Converts the scalar to produce a `u16`. Fails if the scalar is a pointer. . pub fn to_u16(self) -> InterpResult<'static, u16> { . self.to_unsigned_with_bit_width(16).map(|v| u16::try_from(v).unwrap()) . } . . /// Converts the scalar to produce a `u32`. Fails if the scalar is a pointer. . pub fn to_u32(self) -> InterpResult<'static, u32> { . self.to_unsigned_with_bit_width(32).map(|v| u32::try_from(v).unwrap()) . } . . /// Converts the scalar to produce a `u64`. Fails if the scalar is a pointer. 36 ( 0.00%) pub fn to_u64(self) -> InterpResult<'static, u64> { . self.to_unsigned_with_bit_width(64).map(|v| u64::try_from(v).unwrap()) 48 ( 0.00%) } . . /// Converts the scalar to produce a `u128`. Fails if the scalar is a pointer. . pub fn to_u128(self) -> InterpResult<'static, u128> { . self.to_unsigned_with_bit_width(128) . } . 8 ( 0.00%) pub fn to_machine_usize(self, cx: &impl HasDataLayout) -> InterpResult<'static, u64> { 70 ( 0.00%) let b = self.to_bits(cx.data_layout().pointer_size)?; . Ok(u64::try_from(b).unwrap()) 10 ( 0.00%) } . . #[inline] . fn to_signed_with_bit_width(self, bits: u64) -> InterpResult<'static, i128> { . let sz = Size::from_bits(bits); . let b = self.to_bits(sz)?; . Ok(sz.sign_extend(b) as i128) . } . -- line 415 ---------------------------------------- -- line 447 ---------------------------------------- . . #[inline] . pub fn to_f32(self) -> InterpResult<'static, Single> { . // Going through `u32` to check size and truncation. . Ok(Single::from_bits(self.to_u32()?.into())) . } . . #[inline] 36 ( 0.00%) pub fn to_f64(self) -> InterpResult<'static, Double> { . // Going through `u64` to check size and truncation. 216 ( 0.00%) Ok(Double::from_bits(self.to_u64()?.into())) 36 ( 0.00%) } . } . 942 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, TyEncodable, TyDecodable, HashStable, Hash)] . pub enum ScalarMaybeUninit { . Scalar(Scalar), . Uninit, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(ScalarMaybeUninit, 24); . -- line 469 ---------------------------------------- -- line 502 ---------------------------------------- . . #[inline] . pub fn from_maybe_pointer(ptr: Pointer>, cx: &impl HasDataLayout) -> Self { . ScalarMaybeUninit::Scalar(Scalar::from_maybe_pointer(ptr, cx)) . } . . #[inline] . pub fn check_init(self) -> InterpResult<'static, Scalar> { 11,062 ( 0.00%) match self { 5,750 ( 0.00%) ScalarMaybeUninit::Scalar(scalar) => Ok(scalar), . ScalarMaybeUninit::Uninit => throw_ub!(InvalidUninitBytes(None)), . } . } . } . . impl<'tcx, Tag: Provenance> ScalarMaybeUninit { . #[inline(always)] . pub fn to_bool(self) -> InterpResult<'tcx, bool> { 2,826 ( 0.00%) self.check_init()?.to_bool() . } . . #[inline(always)] . pub fn to_char(self) -> InterpResult<'tcx, char> { . self.check_init()?.to_char() . } . . #[inline(always)] -- line 528 ---------------------------------------- 30,362,632 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/tagged_ptr/copy.rs -------------------------------------------------------------------------------- Ir -- line 59 ---------------------------------------- . // Trigger assert! . let () = Self::ASSERTION; . let packed_tag = tag.into_usize() << Self::TAG_BIT_SHIFT; . . Self { . // SAFETY: We know that the pointer is non-null, as it must be . // dereferenceable per `Pointer` safety contract. . packed: unsafe { 111,903,270 ( 0.10%) NonZeroUsize::new_unchecked((P::into_usize(pointer) >> T::BITS) | packed_tag) . }, . data: PhantomData, . } . } . . pub(super) fn pointer_raw(&self) -> usize { 40,797,449 ( 0.04%) self.packed.get() << T::BITS . } . pub fn pointer(self) -> P . where . P: Copy, . { . // SAFETY: pointer_raw returns the original pointer . // . // Note that this isn't going to double-drop or anything because we have -- line 82 ---------------------------------------- -- line 91 ---------------------------------------- . where . P: std::ops::DerefMut, . { . // SAFETY: pointer_raw returns the original pointer . unsafe { std::mem::transmute_copy(&self.pointer_raw()) } . } . #[inline] . pub fn tag(&self) -> T { 321,027,979 ( 0.28%) unsafe { T::from_usize(self.packed.get() >> Self::TAG_BIT_SHIFT) } . } . #[inline] . pub fn set_tag(&mut self, tag: T) { . let mut packed = self.packed.get(); . let new_tag = T::into_usize(tag) << Self::TAG_BIT_SHIFT; . let tag_mask = (1 << T::BITS) - 1; 21,043,626 ( 0.02%) packed &= !(tag_mask << Self::TAG_BIT_SHIFT); 21,054,392 ( 0.02%) packed |= new_tag; . self.packed = unsafe { NonZeroUsize::new_unchecked(packed) }; . } . } . . impl std::ops::Deref for CopyTaggedPtr . where . P: Pointer, . T: Tag, -- line 115 ---------------------------------------- -- line 145 ---------------------------------------- . } . . impl PartialEq for CopyTaggedPtr . where . P: Pointer, . T: Tag, . { . fn eq(&self, other: &Self) -> bool { 1,409,451 ( 0.00%) self.packed == other.packed . } . } . . impl Eq for CopyTaggedPtr . where . P: Pointer, . T: Tag, . { -- line 161 ---------------------------------------- 48,977,995 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs -------------------------------------------------------------------------------- Ir -- line 11 ---------------------------------------- . } . . impl FlagComputation { . fn new() -> FlagComputation { . FlagComputation { flags: TypeFlags::empty(), outer_exclusive_binder: ty::INNERMOST } . } . . #[allow(rustc::usage_of_ty_tykind)] 1,322,055 ( 0.00%) pub fn for_kind(kind: &ty::TyKind<'_>) -> FlagComputation { 188,865 ( 0.00%) let mut result = FlagComputation::new(); . result.add_kind(kind); . result 1,888,650 ( 0.00%) } . 864,675 ( 0.00%) pub fn for_predicate<'tcx>(binder: ty::Binder<'tcx, ty::PredicateKind<'_>>) -> FlagComputation { . let mut result = FlagComputation::new(); . result.add_predicate(binder); . result 1,210,545 ( 0.00%) } . 1,583,860 ( 0.00%) pub fn for_const(c: &ty::Const<'_>) -> TypeFlags { 1,615,522 ( 0.00%) let mut result = FlagComputation::new(); 810,408 ( 0.00%) result.add_const(c); 812,531 ( 0.00%) result.flags 1,583,860 ( 0.00%) } . 30,084,996 ( 0.03%) pub fn for_unevaluated_const(uv: ty::Unevaluated<'_>) -> TypeFlags { 30,084,996 ( 0.03%) let mut result = FlagComputation::new(); 30,084,996 ( 0.03%) result.add_unevaluated_const(uv); . result.flags 60,169,992 ( 0.05%) } . . fn add_flags(&mut self, flags: TypeFlags) { 2,454,013 ( 0.00%) self.flags = self.flags | flags; . } . . /// indicates that `self` refers to something at binding level `binder` . fn add_bound_var(&mut self, binder: ty::DebruijnIndex) { 19,064 ( 0.00%) let exclusive_binder = binder.shifted_in(1); . self.add_exclusive_binder(exclusive_binder); . } . . /// indicates that `self` refers to something *inside* binding . /// level `binder` -- not bound by `binder`, but bound by the next . /// binder internal to it . fn add_exclusive_binder(&mut self, exclusive_binder: ty::DebruijnIndex) { 3,298,493 ( 0.00%) self.outer_exclusive_binder = self.outer_exclusive_binder.max(exclusive_binder); . } . . /// Adds the flags/depth from a set of types that appear within the current type, but within a . /// region binder. . fn bound_computation(&mut self, value: ty::Binder<'_, T>, f: F) . where . F: FnOnce(&mut Self, T), . { 173,682 ( 0.00%) let mut computation = FlagComputation::new(); . 173,682 ( 0.00%) if !value.bound_vars().is_empty() { 1,312 ( 0.00%) computation.flags = computation.flags | TypeFlags::HAS_RE_LATE_BOUND; . } . . f(&mut computation, value.skip_binder()); . 157,627 ( 0.00%) self.add_flags(computation.flags); . . // The types that contributed to `computation` occurred within . // a region binder, so subtract one from the region depth . // within when adding the depth to `self`. 157,627 ( 0.00%) let outer_exclusive_binder = computation.outer_exclusive_binder; 173,682 ( 0.00%) if outer_exclusive_binder > ty::INNERMOST { 23,592 ( 0.00%) self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1)); . } // otherwise, this binder captures nothing . } . . #[allow(rustc::usage_of_ty_tykind)] . fn add_kind(&mut self, kind: &ty::TyKind<'_>) { 944,325 ( 0.00%) match kind { . &ty::Bool . | &ty::Char . | &ty::Int(_) . | &ty::Float(_) . | &ty::Uint(_) . | &ty::Never . | &ty::Str . | &ty::Foreign(..) => {} -- line 95 ---------------------------------------- -- line 116 ---------------------------------------- . self.add_ty(substs.yield_ty()); . self.add_ty(substs.tupled_upvars_ty()); . } . . &ty::GeneratorWitness(ts) => { . self.bound_computation(ts, |flags, ts| flags.add_tys(ts)); . } . 1,706 ( 0.00%) &ty::Closure(_, substs) => { . let substs = substs.as_closure(); . let should_remove_further_specializable = . !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 1,706 ( 0.00%) self.add_substs(substs.parent_substs()); . if should_remove_further_specializable { . self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; . } . 1,706 ( 0.00%) self.add_ty(substs.sig_as_fn_ptr_ty()); 1,706 ( 0.00%) self.add_ty(substs.kind_ty()); 1,706 ( 0.00%) self.add_ty(substs.tupled_upvars_ty()); . } . 23 ( 0.00%) &ty::Bound(debruijn, _) => { . self.add_bound_var(debruijn); . } . . &ty::Placeholder(..) => { . self.add_flags(TypeFlags::HAS_TY_PLACEHOLDER); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . . &ty::Infer(infer) => { . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 7,844 ( 0.00%) match infer { . ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => { . self.add_flags(TypeFlags::HAS_TY_FRESH) . } . . ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => { . self.add_flags(TypeFlags::HAS_TY_INFER) . } . } . } . . &ty::Adt(_, substs) => { . self.add_substs(substs); . } . 17,386 ( 0.00%) &ty::Projection(data) => { . self.add_flags(TypeFlags::HAS_TY_PROJECTION); . self.add_projection_ty(data); . } . . &ty::Opaque(_, substs) => { . self.add_flags(TypeFlags::HAS_TY_OPAQUE); . self.add_substs(substs); . } . 2,208 ( 0.00%) &ty::Dynamic(obj, r) => { 1,494 ( 0.00%) for predicate in obj.iter() { 1,516 ( 0.00%) self.bound_computation(predicate, |computation, predicate| match predicate { 1,472 ( 0.00%) ty::ExistentialPredicate::Trait(tr) => computation.add_substs(tr.substs), . ty::ExistentialPredicate::Projection(p) => { . computation.add_existential_projection(&p); . } . ty::ExistentialPredicate::AutoTrait(_) => {} . }); . } . . self.add_region(r); . } . 6,300 ( 0.00%) &ty::Array(tt, len) => { 3,150 ( 0.00%) self.add_ty(tt); 6,300 ( 0.00%) self.add_const(len); . } . . &ty::Slice(tt) => self.add_ty(tt), . . &ty::RawPtr(ref m) => { . self.add_ty(m.ty); . } . 162,726 ( 0.00%) &ty::Ref(r, ty, _) => { . self.add_region(r); 81,363 ( 0.00%) self.add_ty(ty); . } . . &ty::Tuple(ref substs) => { 10,406 ( 0.00%) self.add_substs(substs); . } . . &ty::FnDef(_, substs) => { . self.add_substs(substs); . } . 25,850 ( 0.00%) &ty::FnPtr(fn_sig) => self.bound_computation(fn_sig, |computation, fn_sig| { . computation.add_tys(fn_sig.inputs()); 12,925 ( 0.00%) computation.add_ty(fn_sig.output()); . }), . } . } . . fn add_predicate(&mut self, binder: ty::Binder<'_, ty::PredicateKind<'_>>) { 1,037,610 ( 0.00%) self.bound_computation(binder, |computation, atom| computation.add_predicate_atom(atom)); . } . . fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) { 864,675 ( 0.00%) match atom { . ty::PredicateKind::Trait(trait_pred) => { 200,304 ( 0.00%) self.add_substs(trait_pred.trait_ref.substs); . } . ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => { . self.add_region(a); . self.add_region(b); . } . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, region)) => { 18,952 ( 0.00%) self.add_ty(ty); . self.add_region(region); . } . ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => { . self.add_ty(a); . self.add_ty(b); . } . ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => { . self.add_ty(a); . self.add_ty(b); . } . ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => { . self.add_projection_ty(projection_ty); 25,954 ( 0.00%) match term { 12,977 ( 0.00%) Term::Ty(ty) => self.add_ty(ty), . Term::Const(c) => self.add_const(c), . } . } 108,069 ( 0.00%) ty::PredicateKind::WellFormed(arg) => { 108,069 ( 0.00%) self.add_substs(slice::from_ref(&arg)); . } . ty::PredicateKind::ObjectSafe(_def_id) => {} . ty::PredicateKind::ClosureKind(_def_id, substs, _kind) => { 2,100 ( 0.00%) self.add_substs(substs); . } . ty::PredicateKind::ConstEvaluatable(uv) => { . self.add_unevaluated_const(uv); . } . ty::PredicateKind::ConstEquate(expected, found) => { . self.add_const(expected); . self.add_const(found); . } -- line 264 ---------------------------------------- -- line 269 ---------------------------------------- . } . . fn add_ty(&mut self, ty: Ty<'_>) { . self.add_flags(ty.flags()); . self.add_exclusive_binder(ty.outer_exclusive_binder); . } . . fn add_tys(&mut self, tys: &[Ty<'_>]) { 23,695 ( 0.00%) for &ty in tys { 23,695 ( 0.00%) self.add_ty(ty); . } . } . . fn add_region(&mut self, r: ty::Region<'_>) { . self.add_flags(r.type_flags()); 117,293 ( 0.00%) if let ty::ReLateBound(debruijn, _) = *r { . self.add_bound_var(debruijn); . } . } . 3,286,124 ( 0.00%) fn add_const(&mut self, c: &ty::Const<'_>) { 1,643,062 ( 0.00%) self.add_ty(c.ty); 4,107,655 ( 0.00%) match c.val { 4,626 ( 0.00%) ty::ConstKind::Unevaluated(unevaluated) => self.add_unevaluated_const(unevaluated), . ty::ConstKind::Infer(infer) => { . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 937,420 ( 0.00%) match infer { . InferConst::Fresh(_) => self.add_flags(TypeFlags::HAS_CT_FRESH), . InferConst::Var(_) => self.add_flags(TypeFlags::HAS_CT_INFER), . } . } 260 ( 0.00%) ty::ConstKind::Bound(debruijn, _) => { . self.add_bound_var(debruijn); . } . ty::ConstKind::Param(_) => { . self.add_flags(TypeFlags::HAS_CT_PARAM); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . ty::ConstKind::Placeholder(_) => { . self.add_flags(TypeFlags::HAS_CT_PLACEHOLDER); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . ty::ConstKind::Value(_) => {} . ty::ConstKind::Error(_) => self.add_flags(TypeFlags::HAS_ERROR), . } 3,286,124 ( 0.00%) } . . fn add_unevaluated_const

(&mut self, ct: ty::Unevaluated<'_, P>) { 60,179,244 ( 0.05%) self.add_substs(ct.substs); . self.add_flags(TypeFlags::HAS_CT_PROJECTION); . } . . fn add_existential_projection(&mut self, projection: &ty::ExistentialProjection<'_>) { . self.add_substs(projection.substs); . match projection.term { . ty::Term::Ty(ty) => self.add_ty(ty), . ty::Term::Const(ct) => self.add_const(ct), . } . } . . fn add_projection_ty(&mut self, projection_ty: ty::ProjectionTy<'_>) { 12,977 ( 0.00%) self.add_substs(projection_ty.substs); . } . 212,267,979 ( 0.18%) fn add_substs(&mut self, substs: &[GenericArg<'_>]) { . for kind in substs { 514,919 ( 0.00%) match kind.unpack() { 960,142 ( 0.00%) GenericArgKind::Type(ty) => self.add_ty(ty), . GenericArgKind::Lifetime(lt) => self.add_region(lt), 20,190 ( 0.00%) GenericArgKind::Const(ct) => self.add_const(ct), . } . } 242,591,976 ( 0.21%) } . } 1,377,531 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/function.rs -------------------------------------------------------------------------------- Ir -- line 62 ---------------------------------------- . message = "expected a `{Fn}<{Args}>` closure, found `{Self}`", . label = "expected an `Fn<{Args}>` closure, found `{Self}`" . )] . #[fundamental] // so that regex can rely that `&str: !FnMut` . #[must_use = "closures are lazy and do nothing unless called"] . pub trait Fn: FnMut { . /// Performs the call operation. . #[unstable(feature = "fn_traits", issue = "29625")] 1,854 ( 0.00%) extern "rust-call" fn call(&self, args: Args) -> Self::Output; . } . . /// The version of the call operator that takes a mutable receiver. . /// . /// Instances of `FnMut` can be called repeatedly and may mutate state. . /// . /// `FnMut` is implemented automatically by closures which take mutable . /// references to captured variables, as well as all types that implement -- line 78 ---------------------------------------- -- line 142 ---------------------------------------- . message = "expected a `{FnMut}<{Args}>` closure, found `{Self}`", . label = "expected an `FnMut<{Args}>` closure, found `{Self}`" . )] . #[fundamental] // so that regex can rely that `&str: !FnMut` . #[must_use = "closures are lazy and do nothing unless called"] . pub trait FnMut: FnOnce { . /// Performs the call operation. . #[unstable(feature = "fn_traits", issue = "29625")] 1,369,507 ( 0.00%) extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; . } . . /// The version of the call operator that takes a by-value receiver. . /// . /// Instances of `FnOnce` can be called, but might not be callable multiple . /// times. Because of this, if the only thing known about a type is that it . /// implements `FnOnce`, it can only be called once. . /// -- line 158 ---------------------------------------- -- line 219 ---------------------------------------- . pub trait FnOnce { . /// The returned type after the call operator is used. . #[lang = "fn_once_output"] . #[stable(feature = "fn_once_output", since = "1.12.0")] . type Output; . . /// Performs the call operation. . #[unstable(feature = "fn_traits", issue = "29625")] 4,327,293 ( 0.00%) extern "rust-call" fn call_once(self, args: Args) -> Self::Output; . } . . mod impls { . #[stable(feature = "rust1", since = "1.0.0")] . impl Fn for &F . where . F: Fn, . { . extern "rust-call" fn call(&self, args: A) -> F::Output { 4 ( 0.00%) (**self).call(args) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl FnMut for &F . where . F: Fn, . { -- line 245 ---------------------------------------- -- line 251 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . impl FnOnce for &F . where . F: Fn, . { . type Output = F::Output; . . extern "rust-call" fn call_once(self, args: A) -> F::Output { 2 ( 0.00%) (*self).call(args) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl FnMut for &mut F . where . F: FnMut, . { 1,681,080 ( 0.00%) extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output { 5,812,936 ( 0.00%) (*self).call_mut(args) 2,560,638 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl FnOnce for &mut F . where . F: FnMut, . { . type Output = F::Output; 240,533,376 ( 0.21%) extern "rust-call" fn call_once(self, args: A) -> F::Output { 2,076,508 ( 0.00%) (*self).call_mut(args) 197,916,493 ( 0.17%) } . } . } 400,812 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs -------------------------------------------------------------------------------- Ir -- line 504 ---------------------------------------- . use crate::panicking::{panic, panic_str}; . use crate::pin::Pin; . use crate::{ . convert, hint, mem, . ops::{self, ControlFlow, Deref, DerefMut}, . }; . . /// The `Option` type. See [the module level documentation](self) for more. 572,591,988 ( 0.49%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. . #[lang = "Some"] . #[stable(feature = "rust1", since = "1.0.0")] 317,609 ( 0.00%) Some(#[stable(feature = "rust1", since = "1.0.0")] T), . } . . ///////////////////////////////////////////////////////////////////////////// . // Type implementation . ///////////////////////////////////////////////////////////////////////////// . . impl Option { . ///////////////////////////////////////////////////////////////////////// -- line 531 ---------------------------------------- -- line 543 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . pub const fn is_some(&self) -> bool { 192,306,802 ( 0.17%) matches!(*self, Some(_)) . } . . /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] -- line 559 ---------------------------------------- -- line 616 ---------------------------------------- . /// // then consume *that* with `map`, leaving `text` on the stack. . /// let text_length: Option = text.as_ref().map(|s| s.len()); . /// println!("still can print text: {:?}", text); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn as_ref(&self) -> Option<&T> { 117,827,679 ( 0.10%) match *self { . Some(ref x) => Some(x), . None => None, . } . } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples -- line 632 ---------------------------------------- -- line 638 ---------------------------------------- . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn as_mut(&mut self) -> Option<&mut T> { 83,025,460 ( 0.07%) match *self { . Some(ref mut x) => Some(x), . None => None, . } . } . . /// Converts from [Pin]<[&]Option\> to Option<[Pin]<[&]T>>. . /// . /// [&]: reference "shared reference" -- line 654 ---------------------------------------- -- line 705 ---------------------------------------- . /// let x: Option<&str> = None; . /// x.expect("fruits are healthy"); // panics with `fruits are healthy` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn expect(self, msg: &str) -> T { 55,216,828 ( 0.05%) match self { 7,310,497 ( 0.01%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 742 ---------------------------------------- . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn unwrap(self) -> T { 135,157,670 ( 0.12%) match self { 89,868,738 ( 0.08%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } . } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 759 ---------------------------------------- -- line 769 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 10,010,181 ( 0.01%) match self { 456 ( 0.00%) Some(x) => x, 43,400 ( 0.00%) None => default, . } 90,971 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); . /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 1,905 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 11,916,770 ( 0.01%) match self { 597,515 ( 0.00%) Some(x) => x, 72,924 ( 0.00%) None => f(), . } 3,868 ( 0.00%) } . . /// Returns the contained [`Some`] value or a default. . /// . /// Consumes the `self` argument then, if [`Some`], returns the contained . /// value, otherwise if [`None`], returns the [default value] for that . /// type. . /// . /// # Examples -- line 812 ---------------------------------------- -- line 831 ---------------------------------------- . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_default(self) -> T . where . T: ~const Default, . { 81,214 ( 0.00%) match self { 115,161 ( 0.00%) Some(x) => x, . None => Default::default(), . } 17 ( 0.00%) } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety . /// . /// Calling this method on [`None`] is *[undefined behavior]*. . /// -- line 851 ---------------------------------------- -- line 892 ---------------------------------------- . /// // `Option::map` takes self *by value*, consuming `maybe_some_string` . /// let maybe_some_len = maybe_some_string.map(|s| s.len()); . /// . /// assert_eq!(maybe_some_len, Some(13)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 38,262 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 129,063,395 ( 0.11%) match self { 303,151,743 ( 0.26%) Some(x) => Some(f(x)), 708,049 ( 0.00%) None => None, . } 913,824 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 67,940,574 ( 0.06%) match self { 380,694 ( 0.00%) Some(t) => f(t), 64,290 ( 0.00%) None => default, . } . } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples . /// -- line 978 ---------------------------------------- -- line 990 ---------------------------------------- . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 1,802,176 ( 0.00%) match self { 184,653 ( 0.00%) Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// . /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the -- line 1007 ---------------------------------------- -- line 1024 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 6,899,203 ( 0.01%) match self { 22,248 ( 0.00%) Some(v) => Ok(v), 11,108 ( 0.00%) None => Err(err), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// . /// [`Ok(v)`]: Ok . /// [`Err(err())`]: Err -- line 1042 ---------------------------------------- -- line 1049 ---------------------------------------- . /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or_else(|| 0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 252 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 530,087 ( 0.00%) match self { 425,297 ( 0.00%) Some(v) => Ok(v), 143,343 ( 0.00%) None => Err(err()), . } 315 ( 0.00%) } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// . /// # Examples . /// -- line 1074 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 306,508 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1213 ---------------------------------------- . /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); . /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); . /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); . /// assert_eq!(None.and_then(sq).and_then(sq), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 6,114 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 1,211,853 ( 0.00%) match self { 209,706 ( 0.00%) Some(x) => f(x), . None => None, . } 354,048 ( 0.00%) } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped . /// value), and . /// - [`None`] if `predicate` returns `false`. . /// -- line 1238 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 128,784 ( 0.00%) if let Some(x) = self { 39,708 ( 0.00%) if predicate(&x) { 608 ( 0.00%) return Some(x); . } . } . None 24,495 ( 0.00%) } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. . /// . /// [`or_else`]: Option::or_else -- line 1279 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 104,083 ( 0.00%) match self { 1,617 ( 0.00%) Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// . /// # Examples -- line 1316 ---------------------------------------- -- line 1326 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 317,259 ( 0.00%) match self { 200,773 ( 0.00%) Some(x) => Some(x), . None => f(), . } . } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// -- line 1343 ---------------------------------------- -- line 1431 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert(&mut self, value: T) -> &mut T . where . T: ~const Drop, . { 405,117 ( 0.00%) if let None = *self { 945,237 ( 0.00%) *self = Some(value); . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . /// Inserts the default value into the option if it is [`None`], then -- line 1448 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 3,999,039 ( 0.00%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. 48 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 27,940 ( 0.00%) mem::replace(self, Some(value)) . } . . /// Returns `true` if the option is a [`Some`] value containing the given value. . /// . /// # Examples . /// . /// ``` . /// #![feature(option_result_contains)] -- line 1574 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 1,810,975 ( 0.00%) match self { 59,640,669 ( 0.05%) Some(&v) => Some(v), 623,967 ( 0.00%) None => None, . } 94 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 177,253 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 1,587,887 ( 0.00%) match self { 3,650,401 ( 0.00%) Some(t) => Some(t.clone()), 145,599 ( 0.00%) None => None, . } 555,566 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1843 ---------------------------------------- . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] . fn clone(&self) -> Self { 275,435,210 ( 0.24%) match self { 1,823,242 ( 0.00%) Some(x) => Some(x.clone()), 44,230 ( 0.00%) None => None, . } 42,506,833 ( 0.04%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 861,466 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2136 ---------------------------------------- . type Item = A; . . #[inline] . fn next(&mut self) -> Option { . self.inner.next() . } . #[inline] . fn size_hint(&self) -> (usize, Option) { 189 ( 0.00%) self.inner.size_hint() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . self.inner.next_back() -- line 2152 ---------------------------------------- -- line 2241 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Option { . type Output = T; . type Residual = Option; . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) 34,925 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 63,829,927 ( 0.05%) match self { 301,544 ( 0.00%) Some(v) => ControlFlow::Continue(v), . None => ControlFlow::Break(None), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] . fn from_residual(residual: Option) -> Self { . match residual { 1,388,512 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- -- line 2297 ---------------------------------------- . /// let x: Option>> = Some(Some(Some(6))); . /// assert_eq!(Some(Some(6)), x.flatten()); . /// assert_eq!(Some(6), x.flatten().flatten()); . /// ``` . #[inline] . #[stable(feature = "option_flattening", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn flatten(self) -> Option { 988 ( 0.00%) match self { 5,434 ( 0.00%) Some(inner) => inner, 2,353 ( 0.00%) None => None, . } . } . } 143,104,065 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ops/control_flow.rs -------------------------------------------------------------------------------- Ir -- line 96 ---------------------------------------- . . #[unstable(feature = "try_trait_v2", issue = "84277")] . impl ops::Try for ControlFlow { . type Output = C; . type Residual = ControlFlow; . . #[inline] . fn from_output(output: Self::Output) -> Self { 7,985 ( 0.00%) ControlFlow::Continue(output) . } . . #[inline] . fn branch(self) -> ControlFlow { 24,275,851 ( 0.02%) match self { . ControlFlow::Continue(c) => ControlFlow::Continue(c), 90,104,071 ( 0.08%) ControlFlow::Break(b) => ControlFlow::Break(ControlFlow::Break(b)), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . impl ops::FromResidual for ControlFlow { . #[inline] . fn from_residual(residual: ControlFlow) -> Self { . match residual { 43,889 ( 0.00%) ControlFlow::Break(b) => ControlFlow::Break(b), . } 87,415 ( 0.00%) } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for ControlFlow { . type TryType = ControlFlow; . } . . impl ControlFlow { -- line 131 ---------------------------------------- -- line 173 ---------------------------------------- . /// use std::ops::ControlFlow; . /// . /// assert_eq!(ControlFlow::::Break(3).break_value(), Some(3)); . /// assert_eq!(ControlFlow::::Continue(3).break_value(), None); . /// ``` . #[inline] . #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] . pub fn break_value(self) -> Option { 14,004,113 ( 0.01%) match self { 3,330,543 ( 0.00%) ControlFlow::Continue(..) => None, 39,010,288 ( 0.03%) ControlFlow::Break(x) => Some(x), . } . } . . /// Maps `ControlFlow` to `ControlFlow` by applying a function . /// to the break value in case it exists. . #[inline] . #[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] . pub fn map_break(self, f: F) -> ControlFlow -- line 191 ---------------------------------------- -- line 201 ---------------------------------------- . . /// These are used only as part of implementing the iterator adapters. . /// They have mediocre names and non-obvious semantics, so aren't . /// currently on a path to potential stabilization. . impl ControlFlow { . /// Create a `ControlFlow` from any type implementing `Try`. . #[inline] . pub(crate) fn from_try(r: R) -> Self { 100,275 ( 0.00%) match R::branch(r) { . ControlFlow::Continue(v) => ControlFlow::Continue(v), 29,044,156 ( 0.02%) ControlFlow::Break(v) => ControlFlow::Break(R::from_residual(v)), . } . } . . /// Convert a `ControlFlow` into any type implementing `Try`; . #[inline] . pub(crate) fn into_try(self) -> R { 14,265,558 ( 0.01%) match self { . ControlFlow::Continue(v) => R::from_output(v), 32,281,978 ( 0.03%) ControlFlow::Break(v) => v, . } . } . } . . impl ControlFlow { . /// It's frequently the case that there's no value needed with `Continue`, . /// so this provides a way to avoid typing `(())`, if you prefer it. . /// -- line 228 ---------------------------------------- 1,154,671 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs -------------------------------------------------------------------------------- Ir -- line 299 ---------------------------------------- . #[inline(always)] . pub const unsafe fn offset(self, count: isize) -> *mut T . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . // The obtained pointer is valid for writes since the caller must . // guarantee that it points to the same allocated object as `self`. 981,436,148 ( 0.84%) unsafe { intrinsics::offset(self, count) as *mut T } . } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety . /// -- line 315 ---------------------------------------- -- line 360 ---------------------------------------- . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const fn wrapping_offset(self, count: isize) -> *mut T . where . T: Sized, . { . // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called. 2,032 ( 0.00%) unsafe { intrinsics::arith_offset(self, count) as *mut T } . } . . /// Returns `None` if the pointer is null, or else returns a unique reference to . /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`] . /// must be used instead. . /// . /// For the shared counterpart see [`as_ref`]. . /// -- line 376 ---------------------------------------- -- line 496 ---------------------------------------- . /// of this issue. . #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[inline] . pub const fn guaranteed_eq(self, other: *mut T) -> bool . where . T: Sized, . { 1,178 ( 0.00%) intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _) . } . . /// Returns whether two pointers are guaranteed to be unequal. . /// . /// At runtime this function behaves like `self != other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine the inequality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be unequal. -- line 512 ---------------------------------------- -- line 1055 ---------------------------------------- . /// . /// See [`ptr::drop_in_place`] for safety concerns and examples. . /// . /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place() . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[inline(always)] . pub unsafe fn drop_in_place(self) { . // SAFETY: the caller must uphold the safety contract for `drop_in_place`. 6,672 ( 0.00%) unsafe { drop_in_place(self) } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// See [`ptr::write`] for safety concerns and examples. . /// . /// [`ptr::write`]: crate::ptr::write() -- line 1071 ---------------------------------------- -- line 1416 ---------------------------------------- . } . } . . // Equality for pointers . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for *mut T { . #[inline(always)] . fn eq(&self, other: &*mut T) -> bool { 379,549 ( 0.00%) *self == *other . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for *mut T {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for *mut T { -- line 1432 ---------------------------------------- 1,509,041 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs -------------------------------------------------------------------------------- Ir -- line 41 ---------------------------------------- . write!(fmt, "{}", x) . } . _ => write!(fmt, "{}", self.val), . } . } . } . . fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) { 16,197 ( 0.00%) let (int, signed) = match *ty.kind() { 37,793 ( 0.00%) Int(ity) => (Integer::from_int_ty(&tcx, ity), true), . Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false), . _ => bug!("non integer discriminant"), . }; . (int.size(), signed) . } . . impl<'tcx> Discr<'tcx> { . /// Adds `1` to the value and wraps around if the maximum for the type is reached. 20,460 ( 0.00%) pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self { 31,992 ( 0.00%) self.checked_add(tcx, 1).0 8,184 ( 0.00%) } 48,591 ( 0.00%) pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) { . let (size, signed) = int_size_and_signed(tcx, self.ty); . let (val, oflo) = if signed { . let min = size.signed_int_min(); . let max = size.signed_int_max(); . let val = size.sign_extend(self.val) as i128; 21,596 ( 0.00%) assert!(n < (i128::MAX as u128)); . let n = n as i128; 37,793 ( 0.00%) let oflo = val > max - n; 21,596 ( 0.00%) let val = if oflo { min + (n - (max - val) - 1) } else { val + n }; . // zero the upper bits . let val = val as u128; . let val = size.truncate(val); . (val, oflo) . } else { . let max = size.unsigned_int_max(); . let val = self.val; . let oflo = val > max - n; . let val = if oflo { n - (max - val) - 1 } else { val + n }; . (val, oflo) . }; 21,596 ( 0.00%) (Self { val, ty: self.ty }, oflo) 48,591 ( 0.00%) } . } . . pub trait IntTypeExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option>; . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>; . } . . impl IntTypeExt for attr::IntType { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 38,350 ( 0.00%) match *self { . SignedInt(ast::IntTy::I8) => tcx.types.i8, . SignedInt(ast::IntTy::I16) => tcx.types.i16, . SignedInt(ast::IntTy::I32) => tcx.types.i32, . SignedInt(ast::IntTy::I64) => tcx.types.i64, . SignedInt(ast::IntTy::I128) => tcx.types.i128, . SignedInt(ast::IntTy::Isize) => tcx.types.isize, . UnsignedInt(ast::UintTy::U8) => tcx.types.u8, . UnsignedInt(ast::UintTy::U16) => tcx.types.u16, . UnsignedInt(ast::UintTy::U32) => tcx.types.u32, . UnsignedInt(ast::UintTy::U64) => tcx.types.u64, . UnsignedInt(ast::UintTy::U128) => tcx.types.u128, . UnsignedInt(ast::UintTy::Usize) => tcx.types.usize, . } 2,267 ( 0.00%) } . . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> { . Discr { val: 0, ty: self.to_ty(tcx) } 15,231 ( 0.00%) } . . fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option> { . if let Some(val) = val { . assert_eq!(self.to_ty(tcx), val.ty); . let (new, oflo) = val.checked_add(tcx, 1); . if oflo { None } else { Some(new) } . } else { . Some(self.initial_discriminant(tcx)) -- line 121 ---------------------------------------- -- line 138 ---------------------------------------- . hcx.while_hashing_spans(false, |hcx| { . hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { . ty.hash_stable(hcx, &mut hasher); . }); . }); . hasher.finish() . } . 581 ( 0.00%) pub fn has_error_field(self, ty: Ty<'tcx>) -> bool { 332 ( 0.00%) if let ty::Adt(def, substs) = *ty.kind() { . for field in def.all_fields() { 1,587 ( 0.00%) let field_ty = field.ty(self, substs); 1,587 ( 0.00%) if let Error(_) = field_ty.kind() { . return true; . } . } . } . false 664 ( 0.00%) } . . /// Attempts to returns the deeply last field of nested structures, but . /// does not apply any normalization in its search. Returns the same type . /// if input `ty` is not a structure at all. 129,807 ( 0.00%) pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> { . let tcx = self; . tcx.struct_tail_with_normalize(ty, |ty| ty) 115,384 ( 0.00%) } . . /// Returns the deeply last field of nested structures, or the same type if . /// not a structure at all. Corresponds to the only possible unsized field, . /// and its type can be used to determine unsizing strategy. . /// . /// Should only be called if `ty` has no inference variables and does not . /// need its lifetimes preserved (e.g. as part of codegen); otherwise . /// normalization attempt may cause compiler bugs. 1,716 ( 0.00%) pub fn struct_tail_erasing_lifetimes( . self, . ty: Ty<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> Ty<'tcx> { . let tcx = self; . tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty)) 1,404 ( 0.00%) } . . /// Returns the deeply last field of nested structures, or the same type if . /// not a structure at all. Corresponds to the only possible unsized field, . /// and its type can be used to determine unsizing strategy. . /// . /// This is parameterized over the normalization strategy (i.e. how to . /// handle `::Assoc` and `impl Trait`); pass the identity . /// function to indicate no normalization should take place. -- line 188 ---------------------------------------- -- line 189 ---------------------------------------- . /// . /// See also `struct_tail_erasing_lifetimes`, which is suitable for use . /// during codegen. . pub fn struct_tail_with_normalize( . self, . mut ty: Ty<'tcx>, . mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { 72,895 ( 0.00%) let recursion_limit = self.recursion_limit(); . for iteration in 0.. { 17,233 ( 0.00%) if !recursion_limit.value_within_limit(iteration) { . return self.ty_error_with_message( . DUMMY_SP, . &format!("reached the recursion limit finding the struct tail for {}", ty), . ); . } 79,809 ( 0.00%) match *ty.kind() { 3,412 ( 0.00%) ty::Adt(def, substs) => { 6,824 ( 0.00%) if !def.is_struct() { . break; . } 3,276 ( 0.00%) match def.non_enum_variant().fields.last() { 6,510 ( 0.00%) Some(f) => ty = f.ty(self, substs), . None => break, . } . } . 1,015 ( 0.00%) ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => { . ty = last_ty.expect_ty(); . } . . ty::Tuple(_) => break, . . ty::Projection(_) | ty::Opaque(..) => { . let normalized = normalize(ty); . if ty == normalized { -- line 224 ---------------------------------------- -- line 240 ---------------------------------------- . /// keeps going as long as the two types are instances of the same . /// structure definitions. . /// For `(Foo>, Foo)`, the result will be `(Foo, Trait)`, . /// whereas struct_tail produces `T`, and `Trait`, respectively. . /// . /// Should only be called if the types have no inference variables and do . /// not need their lifetimes preserved (e.g., as part of codegen); otherwise, . /// normalization attempt may cause compiler bugs. 90 ( 0.00%) pub fn struct_lockstep_tails_erasing_lifetimes( . self, . source: Ty<'tcx>, . target: Ty<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> (Ty<'tcx>, Ty<'tcx>) { . let tcx = self; . tcx.struct_lockstep_tails_with_normalize(source, target, |ty| { . tcx.normalize_erasing_regions(param_env, ty) . }) 60 ( 0.00%) } . . /// Same as applying `struct_tail` on `source` and `target`, but only . /// keeps going as long as the two types are instances of the same . /// structure definitions. . /// For `(Foo>, Foo)`, the result will be `(Foo, Trait)`, . /// whereas struct_tail produces `T`, and `Trait`, respectively. . /// . /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use -- line 266 ---------------------------------------- -- line 268 ---------------------------------------- . pub fn struct_lockstep_tails_with_normalize( . self, . source: Ty<'tcx>, . target: Ty<'tcx>, . normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>, . ) -> (Ty<'tcx>, Ty<'tcx>) { . let (mut a, mut b) = (source, target); . loop { 72 ( 0.00%) match (&a.kind(), &b.kind()) { . (&Adt(a_def, a_substs), &Adt(b_def, b_substs)) . if a_def == b_def && a_def.is_struct() => . { . if let Some(f) = a_def.non_enum_variant().fields.last() { . a = f.ty(self, a_substs); . b = f.ty(self, b_substs); . } else { . break; -- line 284 ---------------------------------------- -- line 310 ---------------------------------------- . . _ => break, . } . } . (a, b) . } . . /// Calculate the destructor of a given type. 1,572 ( 0.00%) pub fn calculate_dtor( . self, . adt_did: DefId, . validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>, . ) -> Option { 655 ( 0.00%) let drop_trait = self.lang_items().drop_trait()?; . self.ensure().coherent_trait(drop_trait); . 131 ( 0.00%) let ty = self.type_of(adt_did); 1,193 ( 0.00%) let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| { 12 ( 0.00%) if let Some(item_id) = self.associated_item_def_ids(impl_did).first() { . if validate(self, impl_did).is_ok() { 14 ( 0.00%) return Some((*item_id, self.impl_constness(impl_did))); . } . } . None 26 ( 0.00%) })?; . . Some(ty::Destructor { did, constness }) 1,310 ( 0.00%) } . . /// Returns the set of types that are required to be alive in . /// order to run the destructor of `def` (see RFCs 769 and . /// 1238). . /// . /// Note that this returns only the constraints for the . /// destructor of `def` itself. For the destructors of the . /// contents, you need `adt_dtorck_constraint`. 1,419 ( 0.00%) pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec> { 649 ( 0.00%) let dtor = match def.destructor(self) { . None => { . debug!("destructor_constraints({:?}) - no dtor", def.did); . return vec![]; . } . Some(dtor) => dtor.did, . }; . . let impl_def_id = self.associated_item(dtor).container.id(); -- line 355 ---------------------------------------- -- line 371 ---------------------------------------- . // . // impl<#[may_dangle] P0, P1, P2> Drop for S . // . // We want to return the parameters (X, Y). For that, we match . // up the item-substs with the substs on the impl ADT, . // , and then look up which of the impl substs refer to . // parameters marked as pure. . 4 ( 0.00%) let impl_substs = match *self.type_of(impl_def_id).kind() { 14 ( 0.00%) ty::Adt(def_, substs) if def_ == def => substs, . _ => bug!(), . }; . 4 ( 0.00%) let item_substs = match *self.type_of(def.did).kind() { 14 ( 0.00%) ty::Adt(def_, substs) if def_ == def => substs, . _ => bug!(), . }; . . let result = iter::zip(item_substs, impl_substs) . .filter(|&(_, k)| { 8 ( 0.00%) match k.unpack() { . GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => { . !impl_generics.region_param(ebr, self).pure_wrt_drop . } . GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => { 12 ( 0.00%) !impl_generics.type_param(pt, self).pure_wrt_drop . } . GenericArgKind::Const(&ty::Const { . val: ty::ConstKind::Param(ref pc), .. . }) => !impl_generics.const_param(pc, self).pure_wrt_drop, . GenericArgKind::Lifetime(_) . | GenericArgKind::Type(_) . | GenericArgKind::Const(_) => { . // Not a type, const or region param: this should be reported -- line 404 ---------------------------------------- -- line 405 ---------------------------------------- . // as an error. . false . } . } . }) . .map(|(item_param, _)| item_param) . .collect(); . debug!("destructor_constraint({:?}) = {:?}", def.did, result); 10 ( 0.00%) result 1,286 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note . /// that closures have a `DefId`, but the closure *expression* also . /// has a `HirId` that is located within the context where the . /// closure appears (and, sadly, a corresponding `NodeId`, since . /// those are not yet phased out). The parent of the closure's . /// `DefId` will also be the context where it appears. 38,484 ( 0.00%) pub fn is_closure(self, def_id: DefId) -> bool { 192,721 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator) 76,968 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a definition that does not have its own . /// type-checking context, i.e. closure, generator or inline const. 18,402 ( 0.00%) pub fn is_typeck_child(self, def_id: DefId) -> bool { 289,360 ( 0.00%) matches!( 302,690 ( 0.00%) self.def_kind(def_id), . DefKind::Closure | DefKind::Generator | DefKind::InlineConst . ) 36,804 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`). 19,416 ( 0.00%) pub fn is_trait(self, def_id: DefId) -> bool { 19,416 ( 0.00%) self.def_kind(def_id) == DefKind::Trait 38,832 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`), . /// and `false` otherwise. 184,716 ( 0.00%) pub fn is_trait_alias(self, def_id: DefId) -> bool { 184,716 ( 0.00%) self.def_kind(def_id) == DefKind::TraitAlias 369,432 ( 0.00%) } . . /// Returns `true` if this `DefId` refers to the implicit constructor for . /// a tuple struct like `struct Foo(u32)`, and `false` otherwise. 18,455 ( 0.00%) pub fn is_constructor(self, def_id: DefId) -> bool { 165,905 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Ctor(..)) 36,910 ( 0.00%) } . . /// Given the `DefId`, returns the `DefId` of the innermost item that . /// has its own type-checking context or "inference enviornment". . /// . /// For example, a closure has its own `DefId`, but it is type-checked . /// with the containing item. Similarly, an inline const block has its . /// own `DefId` but it is type-checked together with the containing item. . /// . /// Therefore, when we fetch the . /// `typeck` the closure, for example, we really wind up . /// fetching the `typeck` the enclosing fn item. 693,530 ( 0.00%) pub fn typeck_root_def_id(self, def_id: DefId) -> DefId { . let mut def_id = def_id; . while self.is_typeck_child(def_id) { . def_id = self.parent(def_id).unwrap_or_else(|| { . bug!("closure {:?} has no parent", def_id); . }); . } . def_id 554,824 ( 0.00%) } . . /// Given the `DefId` and substs a closure, creates the type of . /// `self` argument that the closure expects. For example, for a . /// `Fn` closure, this would return a reference type `&T` where . /// `T = closure_ty`. . /// . /// Returns `None` if this closure's kind has not yet been inferred. . /// This should only be possible during type checking. . /// . /// Note that the return value is a late-bound region and hence . /// wrapped in a binder. 3,402 ( 0.00%) pub fn closure_env_ty( . self, . closure_def_id: DefId, . closure_substs: SubstsRef<'tcx>, . env_region: ty::RegionKind, . ) -> Option> { . let closure_ty = self.mk_closure(closure_def_id, closure_substs); . let closure_kind_ty = closure_substs.as_closure().kind_ty(); 1,134 ( 0.00%) let closure_kind = closure_kind_ty.to_opt_closure_kind()?; 1,324 ( 0.00%) let env_ty = match closure_kind { 658 ( 0.00%) ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty), 1,442 ( 0.00%) ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty), . ty::ClosureKind::FnOnce => closure_ty, . }; . Some(env_ty) 3,024 ( 0.00%) } . . /// Returns `true` if the node pointed to by `def_id` is a `static` item. 45,178 ( 0.00%) pub fn is_static(self, def_id: DefId) -> bool { . self.static_mutability(def_id).is_some() 51,632 ( 0.00%) } . . /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute. . pub fn is_thread_local_static(self, def_id: DefId) -> bool { . self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) . } . . /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item. . pub fn is_mutable_static(self, def_id: DefId) -> bool { -- line 510 ---------------------------------------- -- line 597 ---------------------------------------- . self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap(); . None . } . } . } . . impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 102,924 ( 0.00%) self.tcx . } . . fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 327,490 ( 0.00%) if let ty::Opaque(def_id, substs) = t.kind { . self.expand_opaque_ty(def_id, substs).unwrap_or(t) 163,696 ( 0.00%) } else if t.has_opaque_types() { . t.super_fold_with(self) . } else { . t . } . } . } . . impl<'tcx> ty::TyS<'tcx> { -- line 619 ---------------------------------------- -- line 658 ---------------------------------------- . . /// Checks whether values of this type `T` are *moved* or *copied* . /// when referenced -- this amounts to a check for whether `T: . /// Copy`, but note that we **don't** consider lifetimes when . /// doing this check. This means that we may generate MIR which . /// does copies even when the type actually doesn't satisfy the . /// full requirements for the `Copy` trait (cc #29149) -- this . /// winds up being reported as an error during NLL borrow check. 113,585 ( 0.00%) pub fn is_copy_modulo_regions( . &'tcx self, . tcx_at: TyCtxtAt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> bool { . tcx_at.is_copy_raw(param_env.and(self)) 90,868 ( 0.00%) } . . /// Checks whether values of this type `T` have a size known at . /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored . /// for the purposes of this check, so it can be an . /// over-approximation in generic contexts, where one can have . /// strange rules like `>::Bar: Sized` that . /// actually carry lifetime requirements. 623,979 ( 0.00%) pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 346,655 ( 0.00%) self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self)) 415,986 ( 0.00%) } . . /// Checks whether values of this type `T` implement the `Freeze` . /// trait -- frozen types are those that do not contain an . /// `UnsafeCell` anywhere. This is a language concept used to . /// distinguish "true immutability", which is relevant to . /// optimization as well as the rules around static values. Note . /// that the `Freeze` trait is not exposed to end users and is . /// effectively an implementation detail. 70,938 ( 0.00%) pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 39,410 ( 0.00%) self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self)) 47,292 ( 0.00%) } . . /// Fast path helper for testing if a type is `Freeze`. . /// . /// Returning true means the type is known to be `Freeze`. Returning . /// `false` means nothing -- could be `Freeze`, might not be. . fn is_trivially_freeze(&self) -> bool { . match self.kind() { . ty::Int(_) -- line 701 ---------------------------------------- -- line 731 ---------------------------------------- . pub fn is_unpin(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { . self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self)) . } . . /// Fast path helper for testing if a type is `Unpin`. . /// . /// Returning true means the type is known to be `Unpin`. Returning . /// `false` means nothing -- could be `Unpin`, might not be. 39,410 ( 0.00%) fn is_trivially_unpin(&self) -> bool { 39,415 ( 0.00%) match self.kind() { . ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Bool . | ty::Char . | ty::Str . | ty::Never . | ty::Ref(..) . | ty::RawPtr(_) . | ty::FnDef(..) . | ty::Error(_) . | ty::FnPtr(_) => true, . ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_unpin), 2 ( 0.00%) ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(), . ty::Adt(..) . | ty::Bound(..) . | ty::Closure(..) . | ty::Dynamic(..) . | ty::Foreign(_) . | ty::Generator(..) . | ty::GeneratorWitness(_) . | ty::Infer(_) . | ty::Opaque(..) . | ty::Param(_) . | ty::Placeholder(_) . | ty::Projection(_) => false, . } 55,174 ( 0.00%) } . . /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely . /// non-copy and *might* have a destructor attached; if it returns . /// `false`, then `ty` definitely has no destructor (i.e., no drop glue). . /// . /// (Note that this implies that if `ty` has a destructor attached, . /// then `needs_drop` will definitely return `true` for `ty`.) . /// . /// Note that this method is used to check eligible types in unions. . #[inline] 1,106,340 ( 0.00%) pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { . // Avoid querying in simple cases. 850,362 ( 0.00%) match needs_drop_components(self, &tcx.data_layout) { . Err(AlwaysRequiresDrop) => true, 493,152 ( 0.00%) Ok(components) => { . let query_ty = match *components { 387,864 ( 0.00%) [] => return false, . // If we've got a single component, call the query with that . // to increase the chance that we hit the query cache. 69,090 ( 0.00%) [component_ty] => component_ty, . _ => self, . }; . . // This doesn't depend on regions, so try to minimize distinct . // query keys used. . // If normalization fails, we just use `query_ty`. . let query_ty = 12 ( 0.00%) tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty); . 6 ( 0.00%) tcx.needs_drop_raw(param_env.and(query_ty)) . } . } 995,706 ( 0.00%) } . . /// Checks if `ty` has has a significant drop. . /// . /// Note that this method can return false even if `ty` has a destructor . /// attached; even if that is the case then the adt has been marked with . /// the attribute `rustc_insignificant_dtor`. . /// . /// Note that this method is used to check for change in drop order for -- line 809 ---------------------------------------- -- line 888 ---------------------------------------- . // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be . // called for known, fully-monomorphized types. . Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false, . . Foreign(_) | GeneratorWitness(..) | Error(_) => false, . } . } . 345 ( 0.00%) pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool { 276 ( 0.00%) match (&a.kind(), &b.kind()) { . (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => { 345 ( 0.00%) if did_a != did_b { . return false; . } . . substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b)) . } . _ => a == b, . } 414 ( 0.00%) } . . /// Peel off all reference types in this type until there are none left. . /// . /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`. . /// . /// # Examples . /// . /// - `u8` -> `u8` . /// - `&'a mut u8` -> `u8` . /// - `&'a &'b u8` -> `u8` . /// - `&'a *const &'b u8 -> *const &'b u8` 10,091 ( 0.00%) pub fn peel_refs(&'tcx self) -> Ty<'tcx> { . let mut ty = self; 32,850 ( 0.00%) while let Ref(_, inner_ty, _) = ty.kind() { 4,223 ( 0.00%) ty = inner_ty; . } . ty 10,091 ( 0.00%) } . . pub fn outer_exclusive_binder(&'tcx self) -> DebruijnIndex { 17,971 ( 0.00%) self.outer_exclusive_binder 17,971 ( 0.00%) } . } . . pub enum ExplicitSelf<'tcx> { . ByValue, . ByReference(ty::Region<'tcx>, hir::Mutability), . ByRawPointer(hir::Mutability), . ByBox, . Other, -- line 937 ---------------------------------------- -- line 976 ---------------------------------------- . _ => Other, . } . } . } . . /// Returns a list of types such that the given type needs drop if and only if . /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if . /// this type always needs drop. 1,020,775 ( 0.00%) pub fn needs_drop_components<'tcx>( . ty: Ty<'tcx>, . target_layout: &TargetDataLayout, . ) -> Result; 2]>, AlwaysRequiresDrop> { 874,960 ( 0.00%) match ty.kind() { . ty::Infer(ty::FreshIntTy(_)) . | ty::Infer(ty::FreshFloatTy(_)) . | ty::Bool . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Never . | ty::FnDef(..) -- line 996 ---------------------------------------- -- line 1001 ---------------------------------------- . | ty::Ref(..) . | ty::Str => Ok(SmallVec::new()), . . // Foreign types can never have destructors. . ty::Foreign(..) => Ok(SmallVec::new()), . . ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop), . 2 ( 0.00%) ty::Slice(ty) => needs_drop_components(ty, target_layout), . ty::Array(elem_ty, size) => { 26,346 ( 0.00%) match needs_drop_components(elem_ty, target_layout) { 9,928 ( 0.00%) Ok(v) if v.is_empty() => Ok(v), 30,546 ( 0.00%) res => match size.val.try_to_bits(target_layout.pointer_size) { . // Arrays of size zero don't need drop, even if their element . // type does. 214 ( 0.00%) Some(0) => Ok(SmallVec::new()), 12,300 ( 0.00%) Some(_) => res, . // We don't know which of the cases above we are in, so . // return the whole type and let the caller decide what to . // do. 7,126 ( 0.00%) None => Ok(smallvec![ty]), . }, . } . } . // If any field needs drop, then the whole tuple does. 11,128 ( 0.00%) ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| { 42,348 ( 0.00%) acc.extend(needs_drop_components(elem, target_layout)?); 28,232 ( 0.00%) Ok(acc) . }), . . // These require checking for `Copy` bounds or `Adt` destructors. . ty::Adt(..) . | ty::Projection(..) . | ty::Param(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Opaque(..) . | ty::Infer(_) . | ty::Closure(..) 166,830 ( 0.00%) | ty::Generator(..) => Ok(smallvec![ty]), . } 874,950 ( 0.00%) } . 49,104 ( 0.00%) pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool { 34,324 ( 0.00%) match *ty.kind() { . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) . | ty::Str -- line 1053 ---------------------------------------- -- line 1070 ---------------------------------------- . // Not trivial because they have components, and instead of looking inside, . // we'll just perform trait selection. . ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false, . . ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty), . . ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty.expect_ty())), . } 65,472 ( 0.00%) } . . // Does the equivalent of . // ``` . // let v = self.iter().map(|p| p.fold_with(folder)).collect::>(); . // folder.tcx().intern_*(&v) . // ``` 9,357,343 ( 0.01%) pub fn fold_list<'tcx, F, T>( . list: &'tcx ty::List, . folder: &mut F, . intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List, . ) -> Result<&'tcx ty::List, F::Error> . where . F: FallibleTypeFolder<'tcx>, . T: TypeFoldable<'tcx> + PartialEq + Copy, . { . let mut iter = list.iter(); . // Look for the first element that changed 89,698,984 ( 0.08%) match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) { 163,123,516 ( 0.14%) Ok(new_t) if new_t == t => None, . new_t => Some((i, new_t)), . }) { . Some((i, Ok(new_t))) => { . // An element changed, prepare to intern the resulting list . let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len()); . new_list.extend_from_slice(&list[..i]); . new_list.push(new_t); . for t in iter { 636 ( 0.00%) new_list.push(t.try_fold_with(folder)?) . } 847,143 ( 0.00%) Ok(intern(folder.tcx(), &new_list)) . } . Some((_, Err(err))) => { . return Err(err); . } . None => Ok(list), . } 9,543,375 ( 0.01%) } . . #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)] . pub struct AlwaysRequiresDrop; . . /// Normalizes all opaque types in the given value, replacing them . /// with their underlying types. 10,336 ( 0.00%) pub fn normalize_opaque_types<'tcx>( . tcx: TyCtxt<'tcx>, . val: &'tcx List>, . ) -> &'tcx List> { 18,088 ( 0.00%) let mut visitor = OpaqueTypeExpander { . seen_opaque_tys: FxHashSet::default(), . expanded_cache: FxHashMap::default(), . primary_def_id: None, . found_recursion: false, . found_any_recursion: false, . check_recursion: false, . tcx, . }; . val.fold_with(&mut visitor) 12,920 ( 0.00%) } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) *providers = ty::query::Providers { normalize_opaque_types, ..*providers } . } 27,751,998 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs -------------------------------------------------------------------------------- Ir -- line 346 ---------------------------------------- . /// . /// let c = Cell::new(5); . /// . /// c.set(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn set(&self, val: T) { 7,159 ( 0.00%) let old = self.replace(val); 36,812 ( 0.00%) drop(old); . } . . /// Swaps the values of two `Cell`s. . /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. . /// . /// # Examples . /// . /// ``` -- line 363 ---------------------------------------- -- line 434 ---------------------------------------- . /// . /// let five = c.get(); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self) -> T { . // SAFETY: This can cause data races if called from a separate thread, . // but `Cell` is `!Sync` so this won't happen. 6,250,941 ( 0.01%) unsafe { *self.value.get() } . } . . /// Updates the contained value using a function and returns the new value. . /// . /// # Examples . /// . /// ``` . /// #![feature(cell_update)] -- line 450 ---------------------------------------- -- line 689 ---------------------------------------- . . #[inline(always)] . fn is_writing(x: BorrowFlag) -> bool { . x < UNUSED . } . . #[inline(always)] . fn is_reading(x: BorrowFlag) -> bool { 5,265,229 ( 0.00%) x > UNUSED . } . . impl RefCell { . /// Creates a new `RefCell` containing `value`. . /// . /// # Examples . /// . /// ``` -- line 705 ---------------------------------------- -- line 706 ---------------------------------------- . /// use std::cell::RefCell; . /// . /// let c = RefCell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")] . #[inline] . pub const fn new(value: T) -> RefCell { 1,219,359 ( 0.00%) RefCell { 834,093 ( 0.00%) value: UnsafeCell::new(value), . borrow: Cell::new(UNUSED), . #[cfg(feature = "debug_refcell")] . borrowed_at: Cell::new(None), . } . } . . /// Consumes the `RefCell`, returning the wrapped value. . /// -- line 723 ---------------------------------------- -- line 731 ---------------------------------------- . /// let five = c.into_inner(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")] . #[inline] . pub const fn into_inner(self) -> T { . // Since this function takes `self` (the `RefCell`) by value, the . // compiler statically verifies that it is not currently borrowed. 30,916 ( 0.00%) self.value.into_inner() . } . . /// Replaces the wrapped value with a new one, returning the old value, . /// without deinitializing either one. . /// . /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html). . /// . /// # Panics -- line 747 ---------------------------------------- -- line 845 ---------------------------------------- . /// let c = RefCell::new(5); . /// . /// let m = c.borrow_mut(); . /// let b = c.borrow(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 114,730 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 344,190 ( 0.00%) } . . /// Immutably borrows the wrapped value, returning an error if the value is currently mutably . /// borrowed. . /// . /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be . /// taken out at the same time. . /// . /// This is the non-panicking variant of [`borrow`](#method.borrow). -- line 863 ---------------------------------------- -- line 937 ---------------------------------------- . /// let c = RefCell::new(5); . /// let m = c.borrow(); . /// . /// let b = c.borrow_mut(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 407,753 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 1,223,259 ( 0.00%) } . . /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed. . /// . /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived . /// from it exit scope. The value cannot be borrowed while this borrow is . /// active. . /// . /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). -- line 955 ---------------------------------------- -- line 975 ---------------------------------------- . match BorrowRefMut::new(&self.borrow) { . Some(b) => { . #[cfg(feature = "debug_refcell")] . { . self.borrowed_at.set(Some(crate::panic::Location::caller())); . } . . // SAFETY: `BorrowRef` guarantees unique access. 52 ( 0.00%) Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) . } . None => Err(BorrowMutError { . // If a borrow occurred, then we must already have an outstanding borrow, . // so `borrowed_at` will be `Some` . #[cfg(feature = "debug_refcell")] . location: self.borrowed_at.get().unwrap(), . }), . } -- line 991 ---------------------------------------- -- line 1254 ---------------------------------------- . . struct BorrowRef<'b> { . borrow: &'b Cell, . } . . impl<'b> BorrowRef<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { 7,499,404 ( 0.01%) let b = borrow.get().wrapping_add(1); 4,446,476 ( 0.00%) if !is_reading(b) { . // Incrementing borrow can result in a non-reading value (<= 0) in these cases: . // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow . // due to Rust's reference aliasing rules . // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed . // into isize::MIN (the max amount of writing borrows) so we can't allow . // an additional read borrow because isize can't represent so many read borrows . // (this can only happen if you mem::forget more than a small constant amount of . // `Ref`s, which is not good practice) -- line 1271 ---------------------------------------- -- line 1279 ---------------------------------------- . Some(BorrowRef { borrow }) . } . } . } . . impl Drop for BorrowRef<'_> { . #[inline] . fn drop(&mut self) { 3,256,092 ( 0.00%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 6,487,015 ( 0.01%) self.borrow.set(borrow - 1); . } . } . . impl Clone for BorrowRef<'_> { . #[inline] . fn clone(&self) -> Self { . // Since this Ref exists, we know the borrow flag . // is a reading borrow. -- line 1297 ---------------------------------------- -- line 1645 ---------------------------------------- . . struct BorrowRefMut<'b> { . borrow: &'b Cell, . } . . impl Drop for BorrowRefMut<'_> { . #[inline] . fn drop(&mut self) { 351,120,935 ( 0.30%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 761,496,178 ( 0.65%) self.borrow.set(borrow + 1); . } . } . . impl<'b> BorrowRefMut<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { . // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial . // mutable reference, and so there must currently be no existing . // references. Thus, while clone increments the mutable refcount, here . // we explicitly only allow going from UNUSED to UNUSED - 1. 766,294,903 ( 0.66%) match borrow.get() { . UNUSED => { . borrow.set(UNUSED - 1); . Some(BorrowRefMut { borrow }) . } . _ => None, . } . } . -- line 1674 ---------------------------------------- -- line 1711 ---------------------------------------- . self.value . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DerefMut for RefMut<'_, T> { . #[inline] . fn deref_mut(&mut self) -> &mut T { 13,497 ( 0.00%) self.value . } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl<'b, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized> for RefMut<'b, T> {} . . #[stable(feature = "std_guard_impls", since = "1.20.0")] . impl fmt::Display for RefMut<'_, T> { -- line 1727 ---------------------------------------- -- line 1909 ---------------------------------------- . /// ``` . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")] . pub const fn get(&self) -> *mut T { . // We can just cast the pointer from `UnsafeCell` to `T` because of . // #[repr(transparent)]. This exploits libstd's special status, there is . // no guarantee for user code that this will work in future versions of the compiler! 325,111,687 ( 0.28%) self as *const UnsafeCell as *const T as *mut T . } . . /// Returns a mutable reference to the underlying data. . /// . /// This call borrows the `UnsafeCell` mutably (at compile-time) which . /// guarantees that we possess the only reference. . /// . /// # Examples -- line 1925 ---------------------------------------- 601,696,307 ( 0.52%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/erase_regions.rs -------------------------------------------------------------------------------- Ir . use crate::mir; . use crate::ty::fold::{TypeFoldable, TypeFolder}; . use crate::ty::{self, Ty, TyCtxt, TypeFlags}; . . pub(super) fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) *providers = ty::query::Providers { erase_regions_ty, ..*providers }; . } . 5,544 ( 0.00%) fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { . // N.B., use `super_fold_with` here. If we used `fold_with`, it . // could invoke the `erase_regions_ty` query recursively. 11,088 ( 0.00%) ty.super_fold_with(&mut RegionEraserVisitor { tcx }) 5,544 ( 0.00%) } . . impl<'tcx> TyCtxt<'tcx> { . /// Returns an equivalent value with all free regions removed (note . /// that late-bound regions remain, because they are important for . /// subtyping, but they are anonymized and normalized as well).. 80,451,991 ( 0.07%) pub fn erase_regions(self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { . // If there's nothing to erase avoid performing the query at all 50,504,385 ( 0.04%) if !value.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND | TypeFlags::HAS_FREE_REGIONS) { 120,440,774 ( 0.10%) return value; . } . debug!("erase_regions({:?})", value); 622,434 ( 0.00%) let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self }); . debug!("erase_regions = {:?}", value1); 42,436 ( 0.00%) value1 80,445,881 ( 0.07%) } . } . . struct RegionEraserVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl<'tcx> TypeFolder<'tcx> for RegionEraserVisitor<'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 669,414 ( 0.00%) self.tcx . } . 234,317,718 ( 0.20%) fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 52,402,428 ( 0.05%) if ty.needs_infer() { ty.super_fold_with(self) } else { self.tcx.erase_regions_ty(ty) } 207,950,592 ( 0.18%) } . . fn fold_binder(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { 161,055,253 ( 0.14%) let u = self.tcx.anonymize_late_bound_regions(t); 16,110,803 ( 0.01%) u.super_fold_with(self) . } . 798,867 ( 0.00%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . // because late-bound regions affect subtyping, we can't . // erase the bound/free distinction, but we can replace . // all free regions with 'erased. . // . // Note that we *CAN* replace early-bound regions -- the . // type system never "sees" those, they get substituted . // away. In codegen, they will always be erased to 'erased . // whenever a substitution occurs. 1,742,410 ( 0.00%) match *r { . ty::ReLateBound(..) => r, 1,754,938 ( 0.00%) _ => self.tcx.lifetimes.re_erased, . } 798,867 ( 0.00%) } . . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } 20,249,563 ( 0.02%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 84,750,485,039 (72.79%) events annotated